Websocket.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace addons\shopro\channel;
  3. use addons\shopro\notification\Notification;
  4. use addons\shopro\library\Websocket as WebsocketSend;
  5. class Websocket
  6. {
  7. /**
  8. * 发送 Websocket 通知
  9. * @param Notifiable $notifiable
  10. * @param Notification $notification
  11. */
  12. public function send($notifiable, Notification $notification)
  13. {
  14. $data = [];
  15. if (method_exists($notification, 'toSms')) {
  16. $data = $notification->toWebsocket($notifiable);
  17. if ($notification->receiver_type != 'admin') {
  18. // 目前只有 admin 消息类型发送 socket
  19. return true;
  20. }
  21. // 发送数据
  22. $requestData = [
  23. 'notifiable' => $notifiable->toArray(),
  24. 'notification_type' => $notification->notification_type,
  25. 'type' => $notification->event,
  26. 'data' => $data,
  27. 'read_time' => null,
  28. 'createtime' => date('Y-m-d H:i:s')
  29. ];
  30. // 接收人
  31. $receiver = [
  32. 'ids' => $notifiable->id,
  33. 'type' => $notifiable->getNotifiableType()
  34. ];
  35. try {
  36. $websocket = new WebsocketSend();
  37. $result = $websocket->notification([
  38. 'receiver' => $receiver,
  39. 'data' => $requestData
  40. ]);
  41. if ($result !== true) {
  42. // 发送失败
  43. \think\Log::error('websocket 通知发送失败:用户:' . $notifiable['id'] . ';类型:' . get_class($notification) . ";发送类型:" . $notification->event . ";错误信息:" . json_encode($result, JSON_UNESCAPED_UNICODE));
  44. }
  45. } catch (\Exception $e) {
  46. // 因为配置较麻烦,这里捕获异常防止因为缺少字段,导致队列一直执行不成功
  47. format_log_error($e, 'websocket_notification', '用户:' . $notifiable['id'] . ';类型:' . get_class($notification) . ";发送类型:" . $notification->event);
  48. }
  49. }
  50. return true;
  51. }
  52. }