php - 带有 PHP 的 FCM 未在控制台中显示附加数据
问题描述
我正在使用 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
当您的应用程序在后台时如何处理消息!
推荐阅读
- javascript - Ruby on Rails - Leaflet-rails 'ReferenceError: L is not defined'
- android - setTitleColor 在drawerlayout android studio内的backpress上不起作用
- shell - 使用 Windows 机器在 Mobaxterm 上编译 cpp 函数的 sh 文件
- r - 抽样随机行
- javascript - 无法在 Expo React 本机应用程序中清除间隔
- github - 我粘贴了用于克隆的 Github git URL,但得到:无法解析主机:github.com
- reactjs - 使用 useEffect 在页面加载时从上下文中获取数据
- visual-studio - 重置视觉工作室按钮
- vue.js - 无法在 Vuejs 中验证道具
- javascript - Mongoose/Mongodb 通过与另一个数组比较查找嵌套数组