FeishuBot.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace Longyi\Feishu\Services;
  3. use Illuminate\Support\Facades\Http;
  4. use Illuminate\Support\Facades\Log;
  5. /**
  6. * 飞书群自定义机器人客户端。
  7. *
  8. * 只负责把一条已经构造好的消息投递到 webhook,不关心业务语义。
  9. */
  10. class FeishuBot
  11. {
  12. public function __construct(
  13. protected ?string $webhookUrl = null,
  14. protected ?string $secret = null,
  15. protected ?int $timeout = null,
  16. ) {
  17. $this->webhookUrl ??= (string) config('feishu.webhook_url', '');
  18. $this->secret ??= (string) config('feishu.secret', '');
  19. $this->timeout ??= (int) config('feishu.timeout', 5);
  20. }
  21. /**
  22. * 开关打开且配置了 webhook 才算可用。
  23. */
  24. public function isEnabled(): bool
  25. {
  26. return (bool) config('feishu.enabled', false) && $this->webhookUrl !== '';
  27. }
  28. /**
  29. * 投递一条飞书消息。
  30. *
  31. * @param array $message 形如 ['msg_type' => 'interactive', 'card' => [...]]
  32. *
  33. * @throws \RuntimeException 飞书返回业务错误时抛出,交给调用方重试
  34. */
  35. public function send(array $message): bool
  36. {
  37. if (! $this->isEnabled()) {
  38. return false;
  39. }
  40. if ($this->secret !== '') {
  41. $timestamp = time();
  42. $message['timestamp'] = (string) $timestamp;
  43. $message['sign'] = $this->sign($timestamp);
  44. }
  45. $response = Http::timeout($this->timeout)
  46. ->asJson()
  47. ->post($this->webhookUrl, $message);
  48. /*
  49. * 飞书对业务错误同样返回 HTTP 200,必须看响应体里的 code,
  50. * 否则加签失败、机器人被停用这类问题会被当成发送成功。
  51. */
  52. $body = $response->json() ?? [];
  53. $code = $body['code'] ?? $body['StatusCode'] ?? null;
  54. if ($response->successful() && (int) $code === 0) {
  55. return true;
  56. }
  57. throw new \RuntimeException(sprintf(
  58. 'Feishu webhook rejected the message (http %d, code %s): %s',
  59. $response->status(),
  60. var_export($code, true),
  61. $body['msg'] ?? $body['StatusMessage'] ?? 'unknown error',
  62. ));
  63. }
  64. /**
  65. * 发送但不抛异常,用于绝对不能影响调用方的场景。
  66. */
  67. public function sendQuietly(array $message): bool
  68. {
  69. try {
  70. return $this->send($message);
  71. } catch (\Throwable $e) {
  72. Log::warning('Feishu notification failed: '.$e->getMessage());
  73. return false;
  74. }
  75. }
  76. /**
  77. * 加签:对 "{timestamp}\n{secret}" 做 HMAC-SHA256(空消息体),再 Base64。
  78. */
  79. public function sign(int $timestamp): string
  80. {
  81. return base64_encode(
  82. hash_hmac('sha256', '', $timestamp."\n".$this->secret, true)
  83. );
  84. }
  85. }