Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send FCM Push Notifications to multiple topics

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);
}
like image 541
user934820 Avatar asked Jun 07 '17 12:06

user934820


1 Answers

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

like image 92
Eran Avatar answered Sep 18 '22 23:09

Eran