You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
1.9 KiB

  1. <?php
  2. namespace App\Channels;
  3. use App\Channels\Messages\FcmMessage;
  4. use Illuminate\Notifications\Notification;
  5. use GuzzleHttp\Client as HttpClient;
  6. class SocketChannel
  7. {
  8. /**
  9. * The API URL for Socket.
  10. *
  11. * @var string
  12. */
  13. const API_URI = ''; //todo: fill it
  14. /**
  15. * The HTTP client instance.
  16. *
  17. * @var \GuzzleHttp\Client
  18. */
  19. protected $http;
  20. /**
  21. * Create a new Socket channel instance.
  22. *
  23. * @param \GuzzleHttp\Client $http
  24. * @return void
  25. */
  26. public function __construct(HttpClient $http)
  27. {
  28. $this->http = $http;
  29. }
  30. /**
  31. * Send the given notification.
  32. *
  33. * @param mixed $notifiable
  34. * @param \Illuminate\Notifications\Notification $notification
  35. * @return void
  36. */
  37. public function send($notifiable, Notification $notification)
  38. {
  39. $message = $notification->toSocket($notifiable);
  40. $message->to($notifiable->routeNotificationFor('socket', $notification));
  41. if (! $message->to) {
  42. return;
  43. }
  44. $this->http->post(self::API_URI, [
  45. 'headers' => [
  46. 'Authorization' => "key={$this->apiKey}",
  47. 'Content-Type' => 'application/json',
  48. ],
  49. 'json' => $this->buildJsonPayload($message),
  50. ]);
  51. }
  52. protected function buildJsonPayload(FcmMessage $message)
  53. {
  54. $payload = array_filter([
  55. 'priority' => $message->priority,
  56. 'data' => $message->data,
  57. 'notification' => $message->notification,
  58. 'condition' => $message->condition,
  59. ]);
  60. if ($message->topic) {
  61. $payload['to'] = "/topics/{$message->topic}";
  62. } else {
  63. if (is_array($message->to)) {
  64. $payload['registration_ids'] = $message->to;
  65. } else {
  66. $payload['to'] = $message->to;
  67. }
  68. }
  69. return $payload;
  70. }
  71. }