如何从网页向应用程序发送 FCM 通知

23
我正在开发一个基于Firebase数据库和存储的聊天应用程序。一切都运行良好,但现在我需要实现FCM以在应用程序在后台或前台时接收通知。我找不到一种在PHP中监听Firebase数据库中任何更改并发送推送通知到应用程序的方法。
有很多代码可以从PHP发送通知,但没有一个是基于Firebase数据库的,即使官方文档也有一个使用Node.js的指南,而我的共享主机不支持。
我已经在我的应用程序端实现了FCM代码,并从Firebase控制台进行了测试。
这是我的Firebase数据库结构 Firebase Database Structure

1
使用Postman。 :) - Manoj Perumarath
1
你应该看一下Cloud Functions for Firebase。特别是Realtime Database Triggers部分。 - AL.
@AL,我的服务器不支持Npm。 - Ritu
一个详细的博客: http://sforsuresh.in/sending-push-notifications-to-android-mobile-using-firebase-php - Suresh Kamrushi
也许这个链接会很有帮助:使用Firebase云消息传递发送推送通知 - Fefar Ravi
6个回答

52

发送推送通知只需要向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"
    ]
]

1
从您的数据库中获取数据,并构建有效载荷消息,就这些。 - meda
1
@meda 我有一个问题...在这种情况下,如果我想向iOS设备发送通知,服务器密钥将是什么?或者如何使用pem文件向iOS设备发送通知? - AmarjaPatil4
1
显示“错误=缺少注册”。 - Vishnu T Asok
2
你好,我已经参考了很多像你这样的例子,但我没有收到任何通知,也没有在Firebase控制台上列出通知,即使CURL响应是积极的。 状态:200 字符串(143)“ {”multicast_id“:8573812091209374332,”success“:1,”failure“:0,”canonical_ids“:0,”results“:[{”message_id“:“0:1550852694105682%0762e9f8f9fd7ecd”}]}”当我通过Firebase控制台将它发送到同一设备令牌时,它可以工作,你有什么想法吗?设备令牌来自Firebase云Firestore。 - andrea.somovigo
1
@VishnuTasok 我也遇到了这个错误。原来是由于头部没有正确设置,如果你使用POSTMAN,你必须在body中选择raw,并从原始单选按钮旁边的下拉菜单中选择JSON(application/json)。它将覆盖你的头部。因此,即使你在头部选项卡中输入了头部信息,在body选项卡中错误的设置也会导致POSTMAN覆盖你的头部信息。 - Lawrence Cheuk
显示剩余4条评论

32

尝试这个代码,它在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);
?>

1
如何将多个设备ID或注册ID添加到 - Shawkat Alam
1
创建一个设备令牌数组 $token = ["device_token_1", "device_token_2"] 或者 $token = array("device_token_1", "device_token_2")。 - Riajul Islam
2
谢谢您的回复,我们需要将参数更改为“registration_ids”,否则会显示错误。 - Shawkat Alam
1
我认为变量名没有问题,但“registration_ids”是FCM的标准。谢谢@ShawkatAlam - Riajul Islam
@RiajulIslam 我们遇到了无效的注册ID错误。 - Nishant Saini
显示剩余5条评论

9
您可以发送POST请求而不使用curl(我的服务器上没有curl)。
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;
}

5

应用端通知正常工作,我通过 FCM 控制台进行了检查。 - Ritu

2
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;
}

1
出现错误: {"multicast_id":132596829075065854,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidParameters: 请求中的数据字段不能包含重复的键。"}]} - Aman Deep

2
<?php  
 function sendFCM($title, $urduTitle, $pathimg, $tokens) {
  $url1 = 'https://fcm.googleapis.com/fcm/send';
  $apiKey = "AAAA4zDorrw:APA91bHgehYGI5QWyvUv47FWizkjybMK36hdZQH4PHwdGBQcKCBpdCFUSqNSNGZWcO-l07YfIBuXv_lK9rMEr5y0Ms9CvrwCUmuSn8M0aqj3oGg10bpCyxvm0PYrrrvCF-R4zHqSYyqR";
  $headers = array (
    'Authorization:key=' . $apiKey,
    'Content-Type:application/json'
  );
    // Add notification content to a variable for easy reference
  $notifData = [
    'title' => "".$urduTitle,
    'body' => "".$title,
     'priority' => "high",
    'image'=> "".$pathimg//,//Optional
   // 'click_action' => "activities.SinglePostActivity" //Action/Activity - Optional
  ];
  $dataPayload = [
   'to'=> $_SESSION['lastinsertedid'], 
   'title'=>"".$urduTitle, 
   'title1' =>"".$title,
   'channel'=>'Posts',
   'icon' =>"".$pathimg.""
  ];
 // echo $tokens;
  $apiBody = array(
    'notification' => $notifData,
    'data' => $dataPayload,
    'time_to_live' => 600,
    'to' => ''.$tokens
    //'to' => '/topics/all'
  );
  $ch = curl_init();
  curl_setopt ($ch, CURLOPT_URL, $url1);
  curl_setopt ($ch, CURLOPT_POST, true);
  curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode($apiBody));
  $result = curl_exec($ch);
  return $result;
}
?>

欢迎来到SO!请不要发布仅包含代码的答案,而是添加一些文字说明您的方法如何运作以及它与其他给出答案的不同之处。您可以在我们的“如何撰写好答案”页面了解更多信息。 - ahuemmer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接