src/Services/NotificationService.php line 53

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/ictuspharma/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()."/ictuspharma-firebase-adminsdk-b8v5v-394c664b5e.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.             if (empty($fcmToken)) {
  28.                 throw new \InvalidArgumentException("FCM token is absent");
  29.             }
  30.             // Convertir toutes les valeurs dans le tableau $data en chaînes de caractères
  31.             $data array_map('strval'$data);
  32.             // Préparer le message pour FCM
  33.             $message = [
  34.                 'message' => [
  35.                     'token' => $fcmToken,
  36.                     'notification' => [
  37.                         'title'    => $title,
  38.                         'body'     => $body,
  39.                     ],
  40.                     'data'  => $data,
  41.                 ]
  42.             ];
  43.         
  44.         
  45.             try {
  46.         
  47.                 // Envoyer la requête POST à l'API FCM 
  48.                 $response $this->httpClient->post($this->fcmUrl, [
  49.                     'json' => $message  // utilisez 'json' au lieu de 'body' pour Guzzle
  50.                 ]);
  51.                 return $response->getStatusCode();
  52.             } catch (\Exception $e) {
  53.                 // Gérer l'exception et loguer l'erreur
  54.                 error_log('Erreur lors de l\'envoi de la notification: ' $e->getMessage());
  55.                 throw $e// Relancez ou gérez l'erreur comme vous le souhaitez
  56.         
  57.             }
  58.         
  59.         }
  60. }