Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Push Notification to Multiple Selected Devices with FCM

I am trying to send multiple Selected Devices via FCM, Below are my codes, currently I could only send to one device.

public function send_fcm()
    {
        $project="some-project";
        require_once 'vendor/autoload.php';
        $client = new Google\Client();
        $client->setAuthConfig('../menicon_images/some-project-firebase-adminsdk-kgpuf-afs957ea.json');
        $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
        $result = $client->fetchAccessTokenWithAssertion();
        $accessToken=$result["access_token"];

        $fcmUrl = 'https://fcm.googleapis.com/v1/projects/'.$project.'/messages:send';

        $notification = [
            'title' =>"Some title",
            'body' => "SOme message",
        ];

        $fcmNotification =[
                'message' => [
                    'token' => "some-token-device",
                    'notification' => $notification,
                ],
            ];

        $headers = [
            'Authorization: Bearer '.$accessToken,
            'Content-Type: application/json'
        ];       

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$fcmUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
        $result = curl_exec($ch);
        curl_close($ch);
    }

I had seen the code that is able to send to all devices, but I need to send to specific devices not device.
I looking for a way to send an array of tokens to FCM.

like image 905
MensinBM Avatar asked Dec 21 '25 22:12

MensinBM


1 Answers

From the Firebase documentation on sending messages to multiple devices

Important: The send methods described in this section were deprecated on June 21, 2023, and will be removed in June 2024. For protocol, instead use the standard HTTP v1 API send method, implementing your own batch send by iterating through the list of recipients and sending to each recipient's token. For Admin SDK methods, make sure to update to the next major version. See the Firebase FAQ for more information.

And from that FAQ, this is the required action:

Migrate to the standard HTTP v1 API send method, which supports HTTP/2 for multiplexing.

So you'll have to call the regular send method for each recipient, and ensure HTTP/2 multiplexing to optimize resource usage across those calls.

Alternatively, you can use a topic to reach multiple recipients with one API call in a publish/subscribe pattern - although that is not a direct replacement.

like image 95
Frank van Puffelen Avatar answered Dec 23 '25 11:12

Frank van Puffelen