如何从 Web 向应用发送 FCM 通知

我正在开发基于Firebase数据库和存储的聊天应用程序。一切正常,但现在我需要实现FCM,以便在应用程序处于后台或前台时在应用程序上接收通知。我找不到一种在PHP中实现的方法,该方法可以监听firebase数据库中的任何更改,如果有任何更改,则向应用程序发送推送通知。

有很多代码从PHP发送通知,但没有一个是基于Firebase数据库的,甚至官方文档都有Node.js指南,我的共享主机不支持。

我已经在我的应用端实现了FCM代码,该代码已从Firebase控制台进行了测试。

这是我的Firebase数据库结构Firebase Database Structure


答案 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"
    ]
]

答案 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);
?>

推荐