如何一次将FCM多个通知消息发送到不同主题

时间:2019-08-21 19:52:56

标签: php android firebase notifications firebase-cloud-messaging

我检查了很多答案,它们都是关于将通知发送到不同主题的,但是我想一次将不同消息发送到不同主题。

我有100多个主题要发送通知,一一发送会花费太多时间。

我没有找到任何API文档,所以我尝试了不同的技术,例如$ fields发送多维数组,但是它返回错误。

我的代码一次只发送1条通知。

如何在单个请求中发送所有邮件?

 // Sending through PHP Curl request
 $url = 'https://fcm.googleapis.com/fcm/send';

 $msgs = array();
 $msgs["topic_1"] = array("title"=>"title 1","body"=>"topic 1 message");
 $msgs["topic_2"] = array("title"=>"title 2","body"=>"topic 2 message");
 $msgs["topic_3"] = array("title"=>"title 3","body"=>"topic 3 message");
 ...
 $msgs["topic_100"] = array("title"=>"title 100","body"=>"topic 100 message");


 foreach ($msgs as $topic => $message) {
    $fields = array(
         'to' => "/topics/$topic",
         "priority"=> "high",
         'data' => $message,
         "time_to_live" => 7200
    );

    $headers = array('Authorization:key=API_KEY',
        'Content-Type: application/json'
    );


    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);  
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);           
    curl_close($ch);
 } // loop end

 //above code only send 1 message at once..

1 个答案:

答案 0 :(得分:0)

请参阅此doc

您可以使用按摩中的 condition 参数将通知发送到多个主题

例如,以下情况将向订阅了TopicA以及TopicB或TopicC的设备发送消息:

  

“主题&&中的'TopicA'(主题中的'TopicB'||主题中的'TopicC')“

完整示例:

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See documentation on defining a message payload.
var message = {
  notification: {
    title: '$GOOG up 1.43% on the day',
    body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  condition: condition
};

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

  

注意:您可以在条件中最多包含五个主题   表达。