使用PHP的FCM在控制台中未显示additonalData

时间:2018-09-10 15:21:40

标签: php android firebase firebase-cloud-messaging

我正在使用php发送推送通知,我已经意识到推送通知是通过电话发送的,但是无法发送我添加到脚本(例如页面等)的其他数据。

<?php

$url = "https://fcm.googleapis.com/fcm/send";
$token = 'device_id here';
$serverKey = 'AIzaSxxxbAGLyxxxx';
$title = "New Message";
$body = 'Hello there';
$notification = array('title' =>$title , 'message' => $body,'priority'=>'high','badge'=>'1','notId'=>''.time(), 'id' => '33','page' => 'news');
$arrayToSend = array('to' => $token, 'notification' => $notification);
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);

?>

1 个答案:

答案 0 :(得分:1)

您正在尝试将自定义数据字段添加到pca2d消息中。 Notification条消息仅允许某些字段。如果要发送自定义数据,则需要将您的消息设置为Notification消息或带有数据有效载荷的Data消息。

在FCM文档中,带有Notification的组合消息和适用于Android的数据有效载荷可能看起来像这样:

Notification

对邮件结构进行以下更改:

{
  "to":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "notification":{
      "title":"New Message",
      "body":"Hello there"
    },
    "data" : {
      "notId" : 201801,
      "id" : 33,
      "page" : "news",
    }
}

您将需要更改android代码以适应$notification = array('title' =>$title , 'message' => $body); $data = array('notId'=>''.time(), 'id' => '33','page' => 'news'); $arrayToSend = array('to' => $token, 'notification' => $notification, 'data' => $data); 字段并相应地解析数据。

请仔细阅读FCM文档,以了解此更改可能对您的项目产生哪些影响。最重要的是,当您的应用程序处于后台时,如何处理data条消息!