Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何从web向应用程序发送FCM通知_Php_Firebase_Firebase Realtime Database_Firebase Cloud Messaging_Firebase Storage - Fatal编程技术网

Php 如何从web向应用程序发送FCM通知

Php 如何从web向应用程序发送FCM通知,php,firebase,firebase-realtime-database,firebase-cloud-messaging,firebase-storage,Php,Firebase,Firebase Realtime Database,Firebase Cloud Messaging,Firebase Storage,我正在开发基于Firebase数据库和存储的聊天应用程序。一切正常,但现在我需要实现FCM,以便在应用程序处于后台或前台时在应用程序上接收通知。我找不到在PHP中实现的方法,PHP会监听firebase数据库中的任何更改,如果有任何更改,则向应用程序发送推送通知 有太多的代码从PHP发送通知,但没有一个是基于Firebase数据库的,甚至官方文档也有我的共享主机不支持的Node.js指南 我已经在我的应用程序端实现了FCM代码,这是从Firebase控制台测试的 这是我的Firebase数据库结

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

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

我已经在我的应用程序端实现了FCM代码,这是从Firebase控制台测试的

这是我的Firebase数据库结构
发送推送通知只需向FCM服务器发送post请求即可

下面是一个工作示例:

$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"
    ]
]

你可以用邮递员代替。 在chrome中打开Postman扩展并使用POST url


试试这段代码,它对我来说既适用于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);
?>

您可以不使用curl发送post请求(在我的服务器上不可用)


使用邮递员。:)你应该看看。特别是在.@AL.my服务器上,不支持从您的数据库中提取数据,并生成all@meda我有个问题。。。在这种情况下,如果要向ios设备发送通知,服务器密钥是什么?或者如何使用pem文件向ios设备发送通知?显示“Error=MissingRegistration”。您好,我已经学习了很多类似于您的示例,但我没有收到任何通知,即使CURL响应为肯定,也没有在firebase控制台中列出通知。。状态:200字符串(143)“{“multicast_id”:8573812091209374332,“success”:1,“failure”:0,“canonical_id”:0,“results”:[{“message_id:“0:1550852694105682%0762e9f8f9fd7ecd”}”,当我通过firebase控制台将它发送到它工作的相同设备令牌时,你知道吗?从firebase云获取设备令牌firestore@VishnuTasok我也犯了这个错误。如果你使用POSTMAN,你必须在正文中选择raw,然后从raw单选按钮旁边的下拉菜单中选择JSON(application/JSON)。然后它将覆盖您的标题。因此,即使您在header选项卡中输入了header,body选项卡中的错误设置也会在POSTMAN中覆盖您的header。应用程序端通知工作正常我通过FCM控制台检查了如何添加多个设备id或注册id以创建设备令牌数组$token=[“设备令牌\ 1”,“设备令牌\ 2”]或$token=array(“device_token_1”、“device_token_2”)感谢您的回复,我们需要将参数更改为“registration_ID”,否则将显示错误我认为变量名没有问题,但“registration_ID”是FCM的标准。谢谢@ShawkatAlam@RiajulIslamiam获取无效注册id错误获取错误:{“多播_id”:132596829075065854success“:0,“failure“:1,“canonical_id”:0,“results:[{”error:“InvalidParameters:请求中的数据字段不能包含重复的键。”}]}
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;
}
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;
}