Saturday, October 22, 2016

Send FireBase Push notifications from PHP Application

Hello,

Recently in one of my project we have mobile applications with PHP web services. In this we have a requirement to send Firebase Push notifications from PHP to mobile app. Here in this blog I am going to explain how to do this.

First all login to your Firebase console and get the Web Api key. Go to https://console.firebase.google.com/ and login with your user name and password.

Select your project



Click on gear icons on left and select project settings and above screen will be displayed. Here Web Api Key is the key which you need. copy it. Now let see code one by one.

$url = 'https://fcm.googleapis.com/fcm/send';

This is the URL we will use to send push notification.

Now lets build the payload.

$fields = array (
'to' => 'REGISTRATION_KEY',
"notification" => array(
"title"=> "Welcome To App",
"body"=> "App Description"
),
"data"=>array(
"key_1"=>"value_1",
                        "key_2"=>"value_2"
)
);

Here to is the filed which contains registration id for the device. This is the id which you get when you register device for push notification.

notification contains title and text to be displayed in notification area. This is a standard format and should not be changed.

data contains all the user defined data you want to send with notification, you can add any number of key value pairs here.

If you don't want to pass any data, remove the data field from payload. So now payload is read now lets encode it to send.

$fields = json_encode ( $fields );

Now send headers with API key.

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

Now we will use PHP cURL to send HTTP request.

$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_POSTFIELDS, $fields );

$result = curl_exec ( $ch );
echo $result;
curl_close ( $ch );

That's it and Push notification is sent to particular device.

No comments:

Post a Comment