如何向多个主题发送FCM推送通知

14

我正在使用PHP服务器发送FCM推送通知。我想知道如何同时向多个主题发送推送通知。

这是我的代码。

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);
}
1个回答

18
你可以使用condition键将消息发送到多个主题。
例如:
{
  "condition": "'dogs' in topics || 'cats' in topics",
  "priority" : "high",
  "notification" : {
    "body" : "This is a Firebase Cloud Messaging Topic Message!",
    "title" : "FCM Message",
  }
}

这将把消息发送到订阅了主题"dogs"或"cats"的设备。

来自FCM文档的相关引用:

  

要发送到多个主题的组合,应用服务器将条件键设置为指定目标主题的布尔条件。

请注意,您仅限于2个布尔条件,这意味着您最多可以向3个主题发送单个消息。

更新:现在您可以包含5个主题。

  

您可以在条件表达式中包括最多五个主题,并且支持括号。支持的运算符:&&、||、!。注意!的使用方式:

阅读文档:https://firebase.google.com/docs/cloud-messaging/send-message


谢谢您的回复。我应该在“to”字段中使用什么?('to' => '/topics/foo')。难道没有直接的方法,例如'/topics/foo/bar/etc'吗? - user934820
@user934820 没有任何内容。在这种情况下,您不需要包含该字段。 - Eran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接