How to send push notification to android using php code?

Vinil Lakkavatri picture Vinil Lakkavatri · Nov 30, 2017 · Viewed 7.7k times · Source

I am integrating android push notification is working fine on the client side. Do I want to make server push notification using PHP? Please suggest if you know about the same.

Answer

Amad Yus picture Amad Yus · Nov 30, 2017

This is the source code that I have been referring to for my development. You can try it on phpfiddle. Reference: Push notification (PHP). You can check payload notification for firebase here.

<?php

define( 'API_ACCESS_KEY', 'AIza......Xhdsnkf' ); // get API access 
key from Google/Firebase API's Console

$registrationIds = array( 'cyMSGTKBzwU:APA91...xMKgjgN32WfoJY6mI' ); //Replace this with your device token


// Modify custom payload here
$msg = array
(
        'mesgTitle'     => 'SMART TESTING',
        'alert'         => 'This is sample notification'

);
$fields = array
(
    'registration_ids'      => $registrationIds,
    'data'                  => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' ); //For firebase, use https://fcm.googleapis.com/fcm/send

curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;

?>