I need to send FCM push notifications to multiple devices. I cannot use "topics" for that because I need to send it to specific and multiple tokens.
In the legacy method, I used "register_ids" for this purpose, but Google announced on June 20, 2023, that the legacy method will end on June 20, 2024. In the new v1 API, "register_ids" is no longer supported.
What I need is a solution to send push notifications to multiple tokens using cURL and PHP.
On this website, someone asked a similar question to mine:
@Frank van Puffelen said:
"In this new, versioned API, you can send multiple messages by sending a multi-part request to the regular endpoint. This process is fully documented in the section on sending a batch of messages and is also supported by most of the available Admin SDKs."
Frank von Puffelen provided a link:
https://firebase.google.com/docs/cloud-messaging/send-message#send-a-batch-of-messages
However, there is now a note on this website stating:
"The batch send methods described in this section were deprecated on June 21, 2023, and will be removed in June 2024. Instead, use the standard HTTP v1 API send method by implementing your own batch send logic, 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."
Further up on that website, there is a section titled "Send messages to multiple devices." However, this section only provides solutions for node.js, Java, Python, Go, C#, and REST. I need a solution for PHP and cURL.
What I have tried so far is as follows, but it is not working because of error with the schema:
$tokens = array(
"token 1",
"token 2"
);
foreach ($tokens as $token) {
$data = json_encode(array(
"message" => array(
"token" => $token,
"notification" => array(
"title" => "New Message",
"body" => "New Text",
"image" => "https://example.com/test.jpg"
),
"data" => array(
"website_link" => "https://example.com/",
"icon" => "https://example.com/test.jpg"
)
)
));
$accessToken = file_get_contents("access_token.txt");
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://fcm.googleapis.com/v1/projects/myapp/messages:send',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: Bearer ' . $accessToken
),
));
}
$response = curl_exec($curl);
I know I can loop the cURL code for each token, but I believe this is not a good practice because it would trigger the "https://fcm.googleapis.com/v1/projects/myapp/messages:send" multiple times in a row.
I would prefer to collect all the tokens and send them at once. Is there a solution?
Thank you very much.