15m44l 工单第二批: GitHub issue 双向同步(OAuth逐次授权+建issue/评论+Webhook回推, 防循环前缀)

This commit is contained in:
ypsdf1
2026-11-25 12:16:37 +08:00
parent 834752f791
commit 16360d4b8d
8 changed files with 560 additions and 15 deletions
+78
View File
@@ -0,0 +1,78 @@
<?php
/**
* 15m44l 工单第二批:GitHub issue 双向同步 —— Webhook 回调端点
*
* 这是【给用户填到 GitHub 仓库 Settings→Webhooks→Payload URL】的地址。
* GitHub 在 issue/评论/关闭等事件发生时,POST JSON 到这里(带 X-Hub-Signature-256 签名)。
* 本端点:
* 1) 校验签名(HMAC-SHA256, secret = img.json.webhook_secret)→ 防伪造
* 2) 解析事件,交给 ghHandleWebhook 回推 PHP web_ticket_replies
* 3) 只认我们 PHP 工单建的 issue(按 gh_issue_number 反查)
*
* 配置:在 GitHub 仓库 → Settings → Webhooks → Add webhook:
* Payload URL : https://caoyuan.ypshidifu.cn/plugin/api/gh_webhook.php
* Content type: application/json
* Secret : 4V8gi9h^&^47 (= img.json.webhook_secret,两边必须一致)
* Events : 勾选 issue_comment + issues
*/
while (ob_get_level() > 0) { @ob_end_clean(); }
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', '0');
if (function_exists('opcache_invalidate')) { @opcache_invalidate(__FILE__); }
require_once __DIR__ . '/../core.php';
require_once __DIR__ . '/../lsky.php';
require_once __DIR__ . '/../gh_api.php';
// Webhook 必须 POST + application/json
if (strtoupper($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['success' => false, 'message' => 'method not allowed (POST only)']);
exit;
}
$rawBody = file_get_contents('php://input');
if ($rawBody === false || $rawBody === '') {
http_response_code(400);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['success' => false, 'message' => 'empty body']);
exit;
}
// 1) 签名校验
$sigHeader = isset($_SERVER['HTTP_X_HUB_SIGNATURE_256']) ? (string)$_SERVER['HTTP_X_HUB_SIGNATURE_256'] : '';
if (!ghWebhookVerify($rawBody, $sigHeader)) {
ghLog('WEBHOOK REJECT: bad X-Hub-Signature-256');
http_response_code(403);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['success' => false, 'message' => 'signature mismatch']);
exit;
}
// 2) 解析 JSON
$payload = json_decode($rawBody, true);
if (!is_array($payload)) {
http_response_code(400);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['success' => false, 'message' => 'invalid json']);
exit;
}
$event = strtolower(isset($_SERVER['HTTP_X_GITHUB_EVENT']) ? (string)$_SERVER['HTTP_X_GITHUB_EVENT'] : '');
if ($event === '') $event = isset($payload['event']) ? (string)$payload['event'] : 'unknown';
// 只关心 issue 相关事件
$handled = ghHandleWebhook($payload, $event);
// GitHub 要求 webhook 返回 2xx 才认为投递成功;处理不了也回 200 + 标记,避免 GitHub 反复重发
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'success' => true,
'message' => $handled ? 'handled' : 'ignored (not our ticket / no action)',
'event' => $event,
]);
exit;