I am using php server to send FCM push notifications. I want to know how I can send push notifications to multiple topics at the same time.
Here is my code.
function sendPush($topic,$msg){
$API_ACCESS_KEY = '...';
$msg = array
(
'msg' => $msg
);
$fields = array('to' => '/topics/' . $topic, 'priority' => 'high', 'data' => $msg);
$headers = array
(
'Authorization: key=' . $API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
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($fields));
$pushResult = curl_exec($ch);
curl_close($ch);
}
You use the condition
key to send to multiple topics.
For example:
{
"condition": "'dogs' in topics || 'cats' in topics",
"priority" : "high",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message",
}
}
This would send the message to devices subscribed to topics "dogs" or "cats".
Relevant quote from FCM docs:
To send to combinations of multiple topics, the app server sets the condition key to a boolean condition that specifies the target topics.
Note that you are limited to 2 boolean conditions, which means you can send a single message to at most 3 topics.
Update: Now you can include 5 topics.
You can include up to five topics in your conditional expression, and parentheses are supported. Supported operators: &&, ||, !. Note the usage for !:
Read the documentation at: https://firebase.google.com/docs/cloud-messaging/send-message
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With