我正在使用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);
?>
您正在尝试将自定义数据字段添加到Notification
消息中。Notification
消息仅允许某些字段。如果要发送自定义数据,则需要使消息成为具有数据有效负载的Data
消息或Notification
消息。
从FCM文档中,Notification
消息与Android数据有效负载的组合可能如下所示:
{
"to":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"New Message",
"body":"Hello there"
},
"data" : {
"notId" : 201801,
"id" : 33,
"page" : "news",
}
}
对消息结构进行以下更改:
$notification = array('title' =>$title , 'message' => $body);
$data = array('notId'=>''.time(), 'id' => '33','page' => 'news');
$arrayToSend = array('to' => $token, 'notification' => $notification, 'data' => $data);
您需要更改您的 android 代码以适应data
字段并相应地解析数据。
请仔细阅读 FCM 文档,了解此更改可能对您的项目产生哪些后果。最重要的是,当您的应用程序在后台运行时如何处理data
消息!