繁体   English   中英

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

[英]How to send FCM notification to app from web

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

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

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

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

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

尝试这个代码它适用于我的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);
?>

你可以发送没有卷曲的帖子请求(我的服务器上没有)

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

你可以改用邮差。 在Chrome中打开Postman扩展程序并使用POST网址https://fcm.googleapis.com/fcm/send

在此输入图像描述

在此输入图像描述

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM