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.

93 lines
2.1 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 FcmChannel
  7. {
  8. /**
  9. * The API URL for FCM.
  10. *
  11. * @var string
  12. */
  13. const API_URI = 'https://fcm.googleapis.com/fcm/send';
  14. /**
  15. * The HTTP client instance.
  16. *
  17. * @var \GuzzleHttp\Client
  18. */
  19. protected $http;
  20. /**
  21. * The FCM API key.
  22. *
  23. * @var string
  24. */
  25. protected $apikey;
  26. /**
  27. * Create a new FCM channel instance.
  28. *
  29. * @param \GuzzleHttp\Client $http
  30. * @param string $apiKey
  31. * @return void
  32. */
  33. public function __construct(HttpClient $http, string $apiKey)
  34. {
  35. $this->http = $http;
  36. $this->apiKey = $apiKey;
  37. }
  38. /**
  39. * Send the given notification.
  40. *
  41. * @param mixed $notifiable
  42. * @param \Illuminate\Notifications\Notification $notification
  43. * @return void
  44. */
  45. public function send($notifiable, Notification $notification)
  46. {
  47. $message = $notification->toFcm($notifiable);
  48. $message->to($notifiable->routeNotificationFor('fcm', $notification));
  49. if (! $this->apiKey || (! $message->topic && ! $message->to)) {
  50. return;
  51. }
  52. $this->http->post(self::API_URI, [
  53. 'headers' => [
  54. 'Authorization' => "key={$this->apiKey}",
  55. 'Content-Type' => 'application/json',
  56. ],
  57. 'json' => $this->buildJsonPayload($message),
  58. ]);
  59. }
  60. protected function buildJsonPayload(FcmMessage $message)
  61. {
  62. $payload = array_filter([
  63. 'priority' => $message->priority,
  64. 'data' => $message->data,
  65. 'notification' => $message->notification,
  66. 'condition' => $message->condition,
  67. ]);
  68. if ($message->topic) {
  69. $payload['to'] = "/topics/{$message->topic}";
  70. } else {
  71. if (is_array($message->to)) {
  72. $payload['registration_ids'] = $message->to;
  73. } else {
  74. $payload['to'] = $message->to;
  75. }
  76. }
  77. return $payload;
  78. }
  79. }