WechatOfficialAccount.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace addons\shopro\channel;
  3. use addons\shopro\notification\Notification;
  4. use addons\shopro\facade\Wechat;
  5. class WechatOfficialAccount
  6. {
  7. public function __construct()
  8. {
  9. }
  10. /**
  11. * 发送 微信模板消息
  12. *
  13. * @param mixed $notifiable // 通知用户
  14. * @param 通知内容
  15. * @return void
  16. */
  17. public function send($notifiable, Notification $notification)
  18. {
  19. $data = [];
  20. if (method_exists($notification, 'toWechatOfficialAccount')) {
  21. $data = $notification->toWechatOfficialAccount($notifiable);
  22. if ($data && isset($data['openid']) && isset($data['template_id']) && $data['template_id']) {
  23. $data['touser'] = $data['openid'];
  24. unset($data['openid']);
  25. try {
  26. // 发送模板消息
  27. $result = Wechat::officialAccount()->template_message->send($data);
  28. if ($result['errcode'] != 0) {
  29. // 短信发送失败
  30. \think\Log::error('公众号模板消息发送失败:用户:' . $notifiable['id'] . ';类型:' . get_class($notification) . ";发送类型:" . $notification->event . ";错误信息:" . json_encode($result, JSON_UNESCAPED_UNICODE));
  31. } else {
  32. // 发送成功
  33. $notification->sendOk('WechatOfficialAccount');
  34. }
  35. } catch (\Exception $e) {
  36. // 因为配置较麻烦,这里捕获异常防止因为缺少字段,导致队列一直执行不成功
  37. format_log_error($e, 'WechatOfficialAccount_notification', '用户:' . $notifiable['id'] . ';类型:' . get_class($notification) . ";发送类型:" . $notification->event);
  38. }
  39. return true;
  40. }
  41. // 没有openid
  42. \think\Log::error('公众号模板消息发送失败,没有 openid:用户:' . $notifiable['id'] . ';类型:' . get_class($notification) . ";发送类型:" . $notification->event);
  43. }
  44. return true;
  45. }
  46. }