Send Push notification with PHP and NodeJS

February 17, 2021

for nodejs

 Notifications.js

    var FCM = require('fcm-node');
    var serverKey = 'YOURSERVERKEYHERE'; // put your server key here
    var fcm = new FCM(serverKey);
 
    var message = { //this may vary according to the message type (single recipient, multicast, topic, et cetera)
        to: 'registration_token', 
        collapse_key: 'your_collapse_key',
        
        notification: {
            title: 'Title of your push notification', 
            body: 'Body of your push notification' 
        },
        
        data: {  //you can send only notification or only data(or include both)
            my_key: 'my value',
            my_another_key: 'my another value'
        }
    };
    
    fcm.send(message, function(err, response){
        if (err) {
            console.log("Something has gone wrong!");
        } else {
            console.log("Successfully sent with response: ", response);
        }
    });

for php

public function post_notification(){\
\
\
$url = "[https://fcm.googleapis.com/fcm/send](https://www.google.com/url?q=https://fcm.googleapis.com/fcm/send&sa=D&source=hangouts&ust=1613648270825000&usg=AFQjCNH8ayPxJO22VneE6Oe7uiqh-2lVbw)";\
$token = array("d-5F8dE0SUqK833jJEjsNk:APA91bFZxYRvhBzKvWcIUvcnh1NXJGoFtxjIyoSkFNiNKbFCo5GYlTFwTcwzaBvqEYquKx7yA_zbNoN8ER988-jkPrLdqhvfstv4nQ7PqbNhub42BEh-yoJVPLVI1sA1jHbJmosRAB6S","cZMQP2-IRG6DzgjrFtB_4Y:APA91bGyEG0jNNDTrhzf4CMdyJsUxrdWHw8wWHGBSQDGPZgpmPyPVMFiXu8WjfZtzHJ_UKGAwwG6PW9JJJAV-hMu0GhIcOBPO60kBqyw039j7eyz-rRT4MtZ25g0EOiPFEK2RKqbtWAq");\
$serverKey = 'xxxxxxxxxxx';\
$title = "Notification title";\
$msg = "Hello I am from Your php server";\
$notification = array('title' =>$title , 'body' => $msg, 'sound' => 'default', 'badge' => '1', 'image'=> '[https://toppng.com/uploads/preview/ush-notifications-icon-push-notification-ico-11562898236xgmpisn6xz.png](https://www.google.com/url?q=https://toppng.com/uploads/preview/ush-notifications-icon-push-notification-ico-11562898236xgmpisn6xz.png&sa=D&source=hangouts&ust=1613648270825000&usg=AFQjCNGWv-eXlnTR_-RK5piNqZmIytXc1Q)');\
$arrayToSend = array('registration_ids' => $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);\
}

Written by Manoj Bhardwaj who lives and works in Dharamshala Himachal Pradesh (India). My stackoverflow