WeChatChannel.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace App\Channels;
  3. use Cache;
  4. use Helpers;
  5. use Http;
  6. use Illuminate\Notifications\Notification;
  7. use Log;
  8. class WeChatChannel
  9. {
  10. private $access_token;
  11. public function __construct()
  12. {
  13. if (Cache::has('wechat_access_token')) {
  14. $this->access_token = Cache::get('wechat_access_token');
  15. } else {
  16. // https://work.weixin.qq.com/api/doc/90000/90135/91039
  17. $response = Http::get('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.sysConfig('wechat_cid').'&corpsecret='.sysConfig('wechat_secret'));
  18. if ($response->ok() && isset($response->json()['access_token'])) {
  19. Cache::put('wechat_access_token', $response->json()['access_token'], 7200); // 2小时
  20. } else {
  21. Log::error('Wechat消息推送异常:获取access_token失败!'.PHP_EOL.'携带访问参数:'.$response->body());
  22. abort(400);
  23. }
  24. }
  25. }
  26. public function send($notifiable, Notification $notification)
  27. {
  28. $message = $notification->toCustom($notifiable);
  29. $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.$this->access_token;
  30. $response = Http::timeout(15)->post($url, [
  31. 'touser' => '@all',
  32. 'agentid' => sysConfig('wechat_aid'),
  33. 'msgtype' => 'text',
  34. 'text' => ['content' => $message['content']],
  35. 'duplicate_check_interval' => 600,
  36. ]);
  37. // 发送成功
  38. if ($response->ok()) {
  39. $ret = $response->json();
  40. if (! $ret['errcode'] && $ret['errmsg'] === 'ok') {
  41. Helpers::addNotificationLog($message['title'], $message['content'], 5);
  42. return $ret;
  43. }
  44. // 发送失败
  45. Helpers::addNotificationLog($message['title'], $message['content'], 5, 'admin', -1, $ret ? $ret['errmsg'] : '未知');
  46. return false;
  47. }
  48. // 发送错误
  49. Log::error('Wechat消息推送异常:'.var_export($response, true));
  50. return false;
  51. }
  52. }