WebhookService.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. <?php
  2. namespace App\Module\OpenAPI\Services;
  3. use App\Module\OpenAPI\Models\OpenApiApp;
  4. use App\Module\OpenAPI\Models\OpenApiWebhook;
  5. use Illuminate\Support\Facades\Http;
  6. use Illuminate\Support\Facades\Log;
  7. use Illuminate\Support\Facades\Queue;
  8. /**
  9. * Webhook回调服务
  10. *
  11. * 提供Webhook回调管理和发送功能
  12. */
  13. class WebhookService
  14. {
  15. /**
  16. * 创建Webhook配置
  17. *
  18. * @param OpenApiApp $app
  19. * @param array $data
  20. * @return OpenApiWebhook
  21. */
  22. public function createWebhook(OpenApiApp $app, array $data): OpenApiWebhook
  23. {
  24. $data['app_id'] = $app->app_id;
  25. $data['status'] = $data['status'] ?? 'ACTIVE';
  26. $data['secret'] = $data['secret'] ?? $this->generateWebhookSecret();
  27. return OpenApiWebhook::create($data);
  28. }
  29. /**
  30. * 发送Webhook通知
  31. *
  32. * @param string $appId
  33. * @param string $event
  34. * @param array $payload
  35. * @param bool $async 是否异步发送
  36. * @return bool
  37. */
  38. public function sendWebhook(string $appId, string $event, array $payload, bool $async = true): bool
  39. {
  40. $webhooks = $this->getActiveWebhooks($appId, $event);
  41. if (empty($webhooks)) {
  42. return true; // 没有配置Webhook,视为成功
  43. }
  44. foreach ($webhooks as $webhook) {
  45. if ($async) {
  46. // 异步发送
  47. Queue::push(function () use ($webhook, $event, $payload) {
  48. $this->deliverWebhook($webhook, $event, $payload);
  49. });
  50. } else {
  51. // 同步发送
  52. $this->deliverWebhook($webhook, $event, $payload);
  53. }
  54. }
  55. return true;
  56. }
  57. /**
  58. * 投递Webhook
  59. *
  60. * @param OpenApiWebhook $webhook
  61. * @param string $event
  62. * @param array $payload
  63. * @return bool
  64. */
  65. protected function deliverWebhook(OpenApiWebhook $webhook, string $event, array $payload): bool
  66. {
  67. $deliveryId = uniqid('webhook_');
  68. $timestamp = time();
  69. // 构建请求数据
  70. $requestData = [
  71. 'id' => $deliveryId,
  72. 'event' => $event,
  73. 'timestamp' => $timestamp,
  74. 'data' => $payload,
  75. ];
  76. // 生成签名
  77. $signature = $this->generateSignature($requestData, $webhook->secret);
  78. // 构建请求头
  79. $headers = [
  80. 'Content-Type' => 'application/json',
  81. 'User-Agent' => 'OpenAPI-Webhook/1.0',
  82. 'X-Webhook-Event' => $event,
  83. 'X-Webhook-Delivery' => $deliveryId,
  84. 'X-Webhook-Timestamp' => $timestamp,
  85. 'X-Webhook-Signature' => $signature,
  86. ];
  87. $startTime = microtime(true);
  88. $success = false;
  89. $responseStatus = 0;
  90. $responseBody = '';
  91. $errorMessage = '';
  92. try {
  93. // 发送HTTP请求
  94. $response = Http::timeout($webhook->timeout ?? 30)
  95. ->withHeaders($headers)
  96. ->post($webhook->url, $requestData);
  97. $responseStatus = $response->status();
  98. $responseBody = $response->body();
  99. $success = $response->successful();
  100. if (!$success) {
  101. $errorMessage = "HTTP {$responseStatus}: {$responseBody}";
  102. }
  103. } catch (\Exception $e) {
  104. $errorMessage = $e->getMessage();
  105. Log::error('Webhook delivery failed', [
  106. 'webhook_id' => $webhook->id,
  107. 'url' => $webhook->url,
  108. 'event' => $event,
  109. 'error' => $errorMessage,
  110. ]);
  111. }
  112. $responseTime = (microtime(true) - $startTime) * 1000; // 毫秒
  113. // 记录投递日志
  114. $this->logWebhookDelivery($webhook, $event, $requestData, [
  115. 'delivery_id' => $deliveryId,
  116. 'success' => $success,
  117. 'response_status' => $responseStatus,
  118. 'response_body' => $responseBody,
  119. 'response_time' => $responseTime,
  120. 'error_message' => $errorMessage,
  121. ]);
  122. // 更新Webhook统计
  123. $this->updateWebhookStats($webhook, $success);
  124. // 如果失败且配置了重试,安排重试
  125. if (!$success && $webhook->retry_count > 0) {
  126. $this->scheduleRetry($webhook, $event, $payload, $deliveryId);
  127. }
  128. return $success;
  129. }
  130. /**
  131. * 获取活跃的Webhook配置
  132. *
  133. * @param string $appId
  134. * @param string $event
  135. * @return array
  136. */
  137. protected function getActiveWebhooks(string $appId, string $event): array
  138. {
  139. return OpenApiWebhook::where('app_id', $appId)
  140. ->where('status', 'ACTIVE')
  141. ->where(function ($query) use ($event) {
  142. $query->whereJsonContains('events', $event)
  143. ->orWhereJsonContains('events', '*');
  144. })
  145. ->get()
  146. ->toArray();
  147. }
  148. /**
  149. * 生成Webhook签名
  150. *
  151. * @param array $data
  152. * @param string $secret
  153. * @return string
  154. */
  155. protected function generateSignature(array $data, string $secret): string
  156. {
  157. $payload = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  158. return 'sha256=' . hash_hmac('sha256', $payload, $secret);
  159. }
  160. /**
  161. * 验证Webhook签名
  162. *
  163. * @param string $payload
  164. * @param string $signature
  165. * @param string $secret
  166. * @return bool
  167. */
  168. public function verifySignature(string $payload, string $signature, string $secret): bool
  169. {
  170. $expectedSignature = 'sha256=' . hash_hmac('sha256', $payload, $secret);
  171. return hash_equals($expectedSignature, $signature);
  172. }
  173. /**
  174. * 生成Webhook密钥
  175. *
  176. * @return string
  177. */
  178. protected function generateWebhookSecret(): string
  179. {
  180. return bin2hex(random_bytes(32));
  181. }
  182. /**
  183. * 记录Webhook投递日志
  184. *
  185. * @param OpenApiWebhook $webhook
  186. * @param string $event
  187. * @param array $requestData
  188. * @param array $responseData
  189. * @return void
  190. */
  191. protected function logWebhookDelivery(OpenApiWebhook $webhook, string $event, array $requestData, array $responseData): void
  192. {
  193. Log::info('Webhook delivered', [
  194. 'webhook_id' => $webhook->id,
  195. 'app_id' => $webhook->app_id,
  196. 'url' => $webhook->url,
  197. 'event' => $event,
  198. 'delivery_id' => $responseData['delivery_id'],
  199. 'success' => $responseData['success'],
  200. 'response_status' => $responseData['response_status'],
  201. 'response_time' => $responseData['response_time'],
  202. 'error_message' => $responseData['error_message'] ?? null,
  203. ]);
  204. }
  205. /**
  206. * 更新Webhook统计
  207. *
  208. * @param OpenApiWebhook $webhook
  209. * @param bool $success
  210. * @return void
  211. */
  212. protected function updateWebhookStats(OpenApiWebhook $webhook, bool $success): void
  213. {
  214. $webhook->increment('total_deliveries');
  215. if ($success) {
  216. $webhook->increment('successful_deliveries');
  217. $webhook->update(['last_success_at' => now()]);
  218. } else {
  219. $webhook->increment('failed_deliveries');
  220. $webhook->update(['last_failure_at' => now()]);
  221. }
  222. }
  223. /**
  224. * 安排重试
  225. *
  226. * @param OpenApiWebhook $webhook
  227. * @param string $event
  228. * @param array $payload
  229. * @param string $originalDeliveryId
  230. * @return void
  231. */
  232. protected function scheduleRetry(OpenApiWebhook $webhook, string $event, array $payload, string $originalDeliveryId): void
  233. {
  234. // 计算重试延迟(指数退避)
  235. $retryAttempt = $webhook->current_retry_count ?? 0;
  236. $delay = min(300, pow(2, $retryAttempt) * 10); // 最大5分钟
  237. Queue::later($delay, function () use ($webhook, $event, $payload, $originalDeliveryId, $retryAttempt) {
  238. if ($retryAttempt < $webhook->retry_count) {
  239. $webhook->increment('current_retry_count');
  240. $this->deliverWebhook($webhook, $event, $payload);
  241. }
  242. });
  243. Log::info('Webhook retry scheduled', [
  244. 'webhook_id' => $webhook->id,
  245. 'original_delivery_id' => $originalDeliveryId,
  246. 'retry_attempt' => $retryAttempt + 1,
  247. 'delay_seconds' => $delay,
  248. ]);
  249. }
  250. /**
  251. * 测试Webhook配置
  252. *
  253. * @param OpenApiWebhook $webhook
  254. * @return array
  255. */
  256. public function testWebhook(OpenApiWebhook $webhook): array
  257. {
  258. $testPayload = [
  259. 'test' => true,
  260. 'message' => 'This is a test webhook delivery',
  261. 'timestamp' => now()->toISOString(),
  262. ];
  263. $success = $this->deliverWebhook($webhook, 'test', $testPayload);
  264. return [
  265. 'success' => $success,
  266. 'webhook_id' => $webhook->id,
  267. 'url' => $webhook->url,
  268. 'test_payload' => $testPayload,
  269. ];
  270. }
  271. /**
  272. * 获取Webhook投递统计
  273. *
  274. * @param string $appId
  275. * @param string $period
  276. * @return array
  277. */
  278. public function getWebhookStats(string $appId, string $period = 'day'): array
  279. {
  280. $webhooks = OpenApiWebhook::where('app_id', $appId)->get();
  281. $stats = [
  282. 'total_webhooks' => $webhooks->count(),
  283. 'active_webhooks' => $webhooks->where('status', 'ACTIVE')->count(),
  284. 'total_deliveries' => $webhooks->sum('total_deliveries'),
  285. 'successful_deliveries' => $webhooks->sum('successful_deliveries'),
  286. 'failed_deliveries' => $webhooks->sum('failed_deliveries'),
  287. ];
  288. $stats['success_rate'] = $stats['total_deliveries'] > 0
  289. ? round(($stats['successful_deliveries'] / $stats['total_deliveries']) * 100, 2)
  290. : 0;
  291. return $stats;
  292. }
  293. }