首页 > 解决方案 > 带有 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);

?>

标签: phpandroidfirebasefirebase-cloud-messaging

解决方案


您正在尝试将自定义数据字段添加到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当您的应用程序在后台时如何处理消息!


推荐阅读