Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send FCM notification to app from web

I am developing chat app which is based on Firebase Database and Storage. Everything is working fine, but now I need implementation of FCM to receive notification on app when app is in background or foreground. I can't find a way to implement in PHP which listen any changes in firebase database and if there is any change then send push notification to app.

There is so many code which send notification from PHP, but none is based on Firebase database and even official documentation has Node.js guide which my shared hosting doesn't support.

I already implemented FCM code on my app side which is tested from Firebase Console.

Here is my Firebase database structure Firebase Database Structure

like image 768
Ritu Avatar asked Mar 23 '17 23:03

Ritu


People also ask

How do I send FCM notifications to app?

Send a test notification messageOpen the Notifications composer and select New notification. Enter the message text. Select Send test message. In the field labeled Add an FCM registration token, enter the registration token you obtained in a previous section of this guide.


3 Answers

Sending a push notification is only a matter of sending a post request to FCM servers.

Here is working example:

$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); 

Example of the JSON pay load:

[     "to" => 'DEVICE_TOKEN',     "notification" => [         "body" => "SOMETHING",         "title" => "SOMETHING",         "icon" => "ic_launcher"     ],     "data" => [         "ANYTHING EXTRA HERE"     ] ] 
like image 199
meda Avatar answered Nov 01 '22 14:11

meda


Try this code it works for me android as well as 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); ?> 
like image 23
Riajul Islam Avatar answered Nov 01 '22 15:11

Riajul Islam


You can send the post request without curl (which was not available on my server)

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;
}
like image 43
Ambrus Tóth Avatar answered Nov 01 '22 13:11

Ambrus Tóth