WeChatChannel.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. <?php
  2. namespace App\Channels;
  3. use App\Channels\Components\WeChat;
  4. use Cache;
  5. use Helpers;
  6. use Http;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Notifications\Notification;
  9. use Log;
  10. use Str;
  11. class WeChatChannel
  12. {
  13. private $access_token;
  14. public function __construct()
  15. {
  16. $this->access_token = $this->getAccessToken();
  17. }
  18. private function getAccessToken()
  19. {
  20. if (Cache::has('wechat_access_token')) {
  21. $access_token = Cache::get('wechat_access_token');
  22. } else {
  23. // https://work.weixin.qq.com/api/doc/90000/90135/91039
  24. $response = Http::get('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.sysConfig('wechat_cid').'&corpsecret='.sysConfig('wechat_secret'));
  25. if ($response->ok() && isset($response->json()['access_token'])) {
  26. $access_token = $response->json()['access_token'];
  27. Cache::put('wechat_access_token', $response->json()['access_token'], 7200); // 2小时
  28. } else {
  29. Log::critical('Wechat消息推送异常:获取access_token失败!'.PHP_EOL.'携带访问参数:'.$response->body());
  30. abort(400);
  31. }
  32. }
  33. return $access_token ?? null;
  34. }
  35. public function send($notifiable, Notification $notification)
  36. { // route('message.show', ['type' => 'markdownMsg', 'msgId' => ''])
  37. $message = $notification->toCustom($notifiable);
  38. if (! $this->access_token) {
  39. $this->access_token = $this->getAccessToken();
  40. }
  41. $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.$this->access_token;
  42. if (isset($message['button'])) { // 按钮交互型
  43. // https://work.weixin.qq.com/api/doc/90000/90135/90236#%E6%8C%89%E9%92%AE%E4%BA%A4%E4%BA%92%E5%9E%8B
  44. $body = [
  45. 'touser' => '@all',
  46. 'msgtype' => 'template_card',
  47. 'agentid' => sysConfig('wechat_aid'),
  48. 'template_card' => [
  49. 'card_type' => 'button_interaction',
  50. 'main_title' => ['title' => $message['title']],
  51. 'horizontal_content_list' => $message['body'],
  52. 'task_id' => time().Str::random(),
  53. 'button_list' => [
  54. [
  55. 'type' => 1,
  56. 'text' => '否 決',
  57. 'style' => 3,
  58. 'url' => $message['button'][0],
  59. ],
  60. [
  61. 'type' => 1,
  62. 'text' => '确 认',
  63. 'style' => 1,
  64. 'url' => $message['button'][1],
  65. ],
  66. ],
  67. ],
  68. ];
  69. } elseif (isset($message['url_type'])) { // 文本卡片
  70. $msgId = Str::uuid(); // 生成对公消息查询URL
  71. $body = [
  72. 'touser' => '@all',
  73. 'agentid' => sysConfig('wechat_aid'),
  74. 'msgtype' => 'textcard',
  75. 'textcard' => [
  76. 'title' => $message['title'],
  77. 'description' => '请点击下方按钮【查看详情】',
  78. 'url' => route('message.show', ['type' => $message['url_type'], $msgId]),
  79. 'btntxt' => '查看详情',
  80. ],
  81. ];
  82. } else { // 文本消息
  83. $body = [
  84. 'touser' => '@all',
  85. 'agentid' => sysConfig('wechat_aid'),
  86. 'msgtype' => 'text',
  87. 'text' => ['content' => $message['content']],
  88. 'duplicate_check_interval' => 600,
  89. ];
  90. }
  91. $response = Http::timeout(15)->withBody(json_encode($body, JSON_UNESCAPED_UNICODE), 'application/json; charset=utf-8')->post($url);
  92. // 发送成功
  93. if ($response->ok()) {
  94. $ret = $response->json();
  95. if (! $ret['errcode'] && $ret['errmsg'] === 'ok') {
  96. Helpers::addNotificationLog($message['title'], $message['content'] ?? var_export($message['body'], true), 5, 1, null, $msgId ?? null);
  97. return $ret;
  98. }
  99. // 发送失败
  100. Helpers::addNotificationLog($message['title'], $message['content'] ?? var_export($message['body'], true), 5, -1, $ret ? $ret['errmsg'] : '未知');
  101. return false;
  102. }
  103. // 发送错误
  104. Log::critical('Wechat消息推送异常:'.var_export($response, true));
  105. return false;
  106. }
  107. public function verify(Request $request)
  108. {
  109. $errCode = (new WeChat())->VerifyURL($request->input('msg_signature'), $request->input('timestamp'), $request->input('nonce'), $request->input('echostr'), $sEchoStr);
  110. if ($errCode === 0) {
  111. exit($sEchoStr);
  112. }
  113. Log::critical('Wechat互动消息推送异常:'.var_export($errCode, true));
  114. }
  115. }