src/Services/NotificationService.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\Services;
  3. use Google\Client as GoogleClient;
  4. use GuzzleHttp\Client as GuzzleClient;
  5. use Symfony\Component\HttpKernel\KernelInterface;
  6. class NotificationService
  7. {
  8.     private $httpClient;
  9.     private $fcmUrl 'https://fcm.googleapis.com/v1/projects/pcieictus/messages:send';
  10.     public function __construct(KernelInterface $kernel)
  11.     {
  12.         // Initialisation du client Google et récupération du token
  13.         $googleClient = new GoogleClient();
  14.         $googleClient->setAuthConfig($kernel->getProjectDir()."/pcieictus-firebase-adminsdk-fbsvc-10398550ce.json");
  15.         $googleClient->addScope('https://www.googleapis.com/auth/firebase.messaging');
  16.         // Récupération du token d'accès
  17.         $token $googleClient->fetchAccessTokenWithAssertion()['access_token'];
  18.         $this->httpClient = new GuzzleClient([
  19.             'headers' => [
  20.                 'Authorization' => 'Bearer ' $token,
  21.                 'Content-Type' => 'application/json',
  22.             ]
  23.         ]);
  24.     }
  25.     public function sendNotification($fcmToken$title$body$data = [])
  26.     {
  27.         $message = [
  28.             "message" => "FCM token absent"
  29.         ];
  30.         
  31.         if (!empty($fcmToken)) {
  32.             //Convertir toutes les valeurs dans le tableau $data en chaînes de caractères
  33.                 $data array_map('strval'$data);
  34.                 // Préparer le message pour FCM
  35.                 $message = [
  36.                     'message' => [
  37.                         'token' => $fcmToken,
  38.                         'notification' => [
  39.                             'title'    => $title,
  40.                             'body'     => $body,
  41.                         ],
  42.                         'data'  => $data
  43.                     ]
  44.                 ];
  45.         }
  46.         
  47.         
  48.         // Envoyer la requête POST à l'API FCM
  49.         $response $this->httpClient->post($this->fcmUrl, [
  50.             'body' => json_encode($message)
  51.         ]);
  52.         // Retourner le code de statut de la réponse
  53.         return $response->getStatusCode();
  54.     }
  55. }