如何从网络向应用发送FCM通知 [英] How to send FCM notification to app from web

本文介绍了如何从网络向应用发送FCM通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发基于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服务器发送发布请求的问题.

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有效负载示例:

Example of the JSON pay load:

[
    "to" => 'DEVICE_TOKEN',
    "notification" => [
        "body" => "SOMETHING",
        "title" => "SOMETHING",
        "icon" => "ic_launcher"
    ],
    "data" => [
        "ANYTHING EXTRA HERE"
    ]
]

这篇关于如何从网络向应用发送FCM通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆