问题描述
我正在开发基于 Firebase 数据库和存储的聊天应用程序.一切正常,但现在我需要实现 FCM 以在应用程序处于后台或前台时接收应用程序的通知.我找不到一种在 PHP 中实现的方法,它监听 firebase 数据库中的任何更改,如果有任何更改,则向应用程序发送推送通知.
I am developing chat app which is based on Firebase Database and Storage. Everything is working fine, but now I need implementation of FCM to receive notification on app when app is in background or foreground. I can't find a way to implement in PHP which listen any changes in firebase database and if there is any change then send push notification to app.
有很多代码从 PHP 发送通知,但没有一个是基于 Firebase 数据库的,甚至官方文档也有我的共享主机不支持的 Node.js 指南.
There is so many code which send notification from PHP, but none is based on Firebase database and even official documentation has Node.js guide which my shared hosting doesn't support.
我已经在我的应用端实现了 FCM 代码,并通过 Firebase 控制台进行了测试.
I already implemented FCM code on my app side which is tested from Firebase Console.
这是我的 Firebase 数据库结构
Here is my Firebase database structure
推荐答案
发送推送通知只是向 FCM 服务器发送 post 请求的问题.
Sending a push notification is only a matter of sending a post request to FCM servers.
这是工作示例:
$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"
]
]
这篇关于如何从网络向应用发送 FCM 通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!