web-dev-qa-db-ja.com

WebからFCM通知をアプリに送信する方法

Firebase DatabaseとStorageに基づいたチャットアプリを開発しています。すべて正常に動作していますが、アプリがバックグラウンドまたはフォアグラウンドにあるときにアプリで通知を受信するには、FCMの実装が必要です。 firebaseデータベースの変更をリッスンし、変更があればアプリにプッシュ通知を送信するPHPで実装する方法が見つかりません。

PHPから通知を送信するコードは非常に多くありますが、Firebaseデータベースに基づくものはなく、公式のドキュメントでさえ、共有ホスティングがサポートしていないNode.jsガイドを持っています。

Firebase ConsoleからテストされたFCMコードをアプリ側に既に実装しています。

Firebaseデータベースの構造は次のとおりです Firebase Database Structure

9
Ritu

プッシュ通知の送信は、投稿要求を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"
    ]
]
15
meda

私のために動作するこのコードを試してください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);
?>
8
Riajul Islam

代わりにPostmanを使用できます。 chromeでPostman拡張機能を開き、POST url https://fcm.googleapis.com/fcm/send を使用します。

enter image description here

enter image description here

2
Ruthwik

あなたはカールなしで投稿リクエストを送信できます(私のサーバーでは利用できませんでした)

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;
}
2
Ambrus Tóth
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;
}
0
satyandera