public function send_fcm()
{
$project="some-project";
require_once 'vendor/autoload.php';
$client = new GoogleClient();
$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 am trying to send multiple Selected Devices via FCM,
Below are my codes, currently I could only send to one device.
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
2
Answers
As i understood your question you want to send notification to multiple devices. To send FCM messages to multiple devices using specific tokens, you need to modify the structure of your
$fcmNotification
array. Instead of having a singlemessage
key with a single token, you can create an array of messages, each with its own token. Here’s an example of how you can modify your code:In this example, the
$deviceTokens
array contains the FCM tokens of the devices you want to send messages to. Theforeach
loop then constructs an array of$fcmNotifications
, each with its own token. This array is then sent to FCM using thecurl
request.Make sure to replace
"some-token-device1"
,"some-token-device2"
, etc., with the actual FCM tokens of the devices you want to target.From the Firebase documentation on sending messages to multiple devices
And from that FAQ, this is the required action:
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.