如何从网络向应用发送 FCM 通知
Posted
技术标签:
【中文标题】如何从网络向应用发送 FCM 通知【英文标题】:How to send FCM notification to app from web 【发布时间】:2017-08-16 18:32:24 【问题描述】:我正在开发基于 Firebase 数据库和存储的聊天应用程序。一切正常,但现在我需要实现 FCM 以在应用程序处于后台或前台时接收应用程序的通知。我找不到一种在 php 中实现的方法,它监听 firebase 数据库中的任何更改,如果有任何更改,则向应用程序发送推送通知。
有很多代码从 PHP 发送通知,但没有一个是基于 Firebase 数据库的,甚至官方文档也有我的共享主机不支持的 Node.js 指南。
我已经在我的应用端实现了 FCM 代码,并通过 Firebase 控制台进行了测试。
这是我的 Firebase 数据库结构
【问题讨论】:
使用邮递员。 :) 你应该看看Cloud Functions for Firebase。特别是Realtime Database Triggers。 @AL.my 服务器不支持 Npm 详细博客:sforsuresh.in/… 【参考方案1】:发送推送通知只是向 FCM 服务器发送发布请求的问题。
这是工作示例:
$data = json_encode($json_data);
//FCM API end-point
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'YOUR_KEY';
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_key
);
//CURL request to route notification to FCM connection server (provided by Google)
$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, $data);
$result = curl_exec($ch);
if ($result === FALSE)
die('Oops! FCM Send Error: ' . curl_error($ch));
curl_close($ch);
JSON 负载示例:
[
"to" => 'DEVICE_TOKEN',
"notification" => [
"body" => "SOMETHING",
"title" => "SOMETHING",
"icon" => "ic_launcher"
],
"data" => [
"ANYTHING EXTRA HERE"
]
]
【讨论】:
从您的数据库中获取数据,然后构建播放负载消息,仅此而已 @meda 我有一个问题......在这种情况下,如果我想向 ios 设备发送通知,服务器密钥将是什么?或者如何使用 pem 文件向 ios 设备发送通知? 显示“Error=MissingRegistration”。 你好,我已经关注了很多像你这样的例子,但我没有收到任何通知,即使 CURL 响应是肯定的,通知也没有在 firebase 控制台中列出。状态:200 字符串(143) ""multicast_id":8573812091209374332,"success":1,"failure":0,"canonical_ids":0,"results":["message_id":"0:1550852694105682%0762e9f8f9fd7ecd"]"当我通过firebase控制台将它发送到它工作的同一个设备令牌时,知道吗?从 firebase cloud firestore 获取的设备令牌 @VishnuTasok 我也遇到了这个错误。原来是标题设置不正确,如果您使用 POSTMAN,您必须在正文中选择 raw 并从 raw 单选按钮旁边的下拉菜单中选择 JSON(application/json)。然后它将覆盖您的标题。因此,即使您在标题选项卡中输入了标题,正文选项卡中的错误设置也会在 POSTMAN 中覆盖您的标题。【参考方案2】:试试这个代码,它适用于我的 android 和 iOS
<?php
$url = "https://fcm.googleapis.com/fcm/send";
$token = "your device token";
$serverKey = 'your server token of FCM project';
$title = "Notification title";
$body = "Hello I am from Your php server";
$notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$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);
?>
【讨论】:
如何添加多个设备ID或注册ID 创建一个设备令牌数组 $token = ["device_token_1", "device_token_2"] 或 $token = array("device_token_1", "device_token_2") 感谢回复,需要把参数改成“registration_ids”,否则会报错 我认为变量名没有问题,但“registration_ids”是 FCM 的标准。谢谢@ShawkatAlam @RiajulIslam iam 收到无效的注册 ID 错误【参考方案3】:您可以在没有 curl 的情况下发送 post 请求(在我的服务器上不可用)
sendNotification("New post!", "How to send a simple FCM notification in php", ["new_post_id" => "605"], "YOUR_SERVER_KEY");
function sendNotification($title = "", $body = "", $customData = [], $serverKey = "")
if($serverKey != "")
ini_set("allow_url_fopen", "On");
$data =
[
"to" => '/topics/new_post',
"notification" => [
"body" => $body,
"title" => $title,
],
"data" => $customData
];
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n" .
"Authorization:key=".$serverKey
)
);
$context = stream_context_create( $options );
$result = file_get_contents( "https://fcm.googleapis.com/fcm/send", false, $context );
return json_decode( $result );
return false;
【讨论】:
【参考方案4】:您可以改用 Postman。 在 chrome 中打开 Postman 扩展并使用 POST url https://fcm.googleapis.com/fcm/send。
【讨论】:
应用程序端通知工作正常,我通过 FCM 控制台检查【参考方案5】:function MultiandroidNotification($deviceToken, $message,$type,$title=null,$sub_title=null,$device_type=null,$data = null,$content_available = null)
if($content_available == 1)
$content_available = false;
else
$content_available = true;
if($type == 12 || $type == 13)
$priority = '';
else
$priority = 'high';
$deviceToken = array_values($deviceToken);
$no = null;
$apiKey = 'XXXXXXXXXXXXXXXXXXXXXX';
$notification = array("text" => "test",'badge' => "1",'sound' => 'shutter.wav','body'=>$message,'icon'=>'notif_icn','title'=>$title,'priority'=>'high','tag'=>'test','vibrate'=> 1,'alert'=> $message);
$msg = array('message'=> $message,'title'=> $title,'sub_title'=> $sub_title,'type'=>$type,'activitydata' => $data);
if($device_type == 'android')
$fields = array("content_available" => true,"priority" => "high",'registration_ids'=> $deviceToken,'data'=> $msg);
else
$fields = array('notification' => $notification,"content_available" => $content_available,"priority" => $priority,'registration_ids'=> $deviceToken,'data'=> $msg);
$headers = array('Authorization: key=' . $apiKey,'Content-Type: application/json');
if ($headers)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch))
return false; //probably you want to return false
if ($httpCode != 200)
return false; //probably you want to return false
curl_close($ch);
return $response;
【讨论】:
出现错误:"multicast_id":132596829075065854,"success":0,"failure":1,"canonical_ids":0,"results":["error":"InvalidParameters: The请求中的数据字段不能包含重复的键。"]以上是关于如何从网络向应用发送 FCM 通知的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 fcm 和 j2ee 向 android 发送通知 [关闭]