Search code examples
phpreact-nativenotificationsexpo

Expo Push Notification with PHP


I am trying to send a Push Notification to my react native app using PHP, the below code is sending too all the users that registered their token and it sends plenty Notification at once though the token is for specific device but it keep pushing the notification to all

$key = "ExponentPushToken[0GAEokJazChx21MOxeC1l2]";
$title = "title";
$interestDetails = ['https://exp.host/--/api/v2/push/send',$key];

  try{

      $expo = \ExponentPhpSDK\Expo::normalSetup();

  // Subscribe the recipient to the server
      $expo->subscribe($interestDetails[0], $interestDetails[1]);

  // Build the notification data

    $notification = ['title' => $title,'body' => $msg];

  // Notify an interest with a notification
   $expo->notify($notification);

  $status = 'success';
}catch(Exception $e){



}


   ?>

I tried changing my code as follow

<?php

$key = "ExponentPushToken[0GAEokJazChx21MOxeC1l2]";
$title = "title";


  try{

      $expo = \ExponentPhpSDK\Expo::normalSetup();



  // Build the notification data

  $notification = ['to' => $key,'title' => $title,'body' => $msg];

  // Notify an interest with a notification
 $expo->notify('https://exp.host/--/api/v2/push/send',$notification);

  $status = 'success';
}catch(Exception $e){
    echo $e;
}




  echo $status;


  ?>

It did sent to a specific user but still it keeps sending plenty notification at once?


Solution

  • Try this

    $key = "ExponentPushToken[0GAEokJazChx21MOxeC1l2]";
    $userId = 'userId from your database';
    $notification = ['title' => $title,'body' => $msg];
      try{
    
          $expo = \ExponentPhpSDK\Expo::normalSetup();
          $expo->notify($userId,$notification);//$userId from database
          $status = 'success';
    }catch(Exception $e){
            $expo->subscribe($userId, $key); //$userId from database
            $expo->notify($userId,$notification);
            $status = 'new subscribtion';
    }
    
      echo $status;
      ?>