FCM Push Notifications: PHP Server Side Integration

A step-by-step guide to implement FCM notifications in back-end PHP application.


Firebase Tool Suite

In my last post, I wrote about Android Push Notifications setup using Firebase — a step-by-step guide to implement Firebase Cloud Messaging (FCM) service in Android application. In this post, I’ll discuss server side implementation using PHP to send FCM notification from the app server to the Android device.

FCM Push Notifications: Java Server Side Integration
A step-by-step guide to implement FCM notifications in back-end Java application.

About FCM Server

The server side of FCM consists of two main components:

  • FCM connection servers provided by Google. These servers take messages from an app server and send them to a client app running on a device. Google provides connection servers for HTTP and XMPP.
  • An app server that you must implement in your environment. This app server sends data to a client app via the chosen FCM connection server, using the appropriate XMPP or HTTP protocol.

A full FCM implementation requires both a client implementation and a server implementation to work perfectly.

App Server Implementation in PHP

We can send FCM push notification from our PHP app server to Android users by using Firbase Cloud Messaging HTTP Protocol. It provides following HTTP end-point that can be used to route all notifications requests:

https://fcm.googleapis.com/fcm/send

Here are some of the important parameters used to send downstream FCM messages.

  • to – Type String – (Optional) [Recipient of the message]
    The value must be a single registration token, notification key, or topic. Do not set this field when sending to multiple topics
  • registration_ids – Type String array – (Optional) [Recipients of the message]
    Multiple registration tokens, min 1 max 1000.
  • priority– Type String – (Optional) [ default normal]
    Allowed values normal and high.Normal priority optimizes the client app’s battery consumption and the app may receive the message with unspecified delay.High priority sends the message immediately, and the app can wake a sleeping device and open a network connection to the server.
  • delay_while_idle – Type boolean – (Optional) [default value false]
    True indicates that the message should not be sent until the device becomes active.
  • time_to_live – Type JSON number – (Optional) [default value 4 week maximum 4 week]
    This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline.
  • data – Type JSON Object
    Specifies the custom key-value pairs of the message’s payload.
    For example, with data: {“from”:”Lhe.io″,”title”:”FCM Notifications”}

For a complete list of targets,options and payloads available to send message from server visit this link.

OK let’s start the actual work, PHP coding to send FCM notification. Here is a code snippet that you can add into your PHP project to route push notification to intended user or a group of users.

<?php 

/* Example Parameter $data = array('from'=>'Lhe.io','title'=>'FCM Push Notifications');
	$target = 'single token id or topic name';
	or
	$target = array('token1','token2','...'); // up to 1000 in one request for group sending
*/
public function sendFCMMessage($data,$target){
   //FCM API end-point
   $url = 'https://fcm.googleapis.com/fcm/send';
   //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
   $server_key = 'PASTE_YOUR_SERVER_KEY_HERE';
			
   $fields = array();
   $fields['data'] = $data;
   if(is_array($target)){
	$fields['registration_ids'] = $target;
   }else{
	$fields['to'] = $target;
   }
   //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, json_encode($fields));
   $result = curl_exec($ch);
   if ($result === FALSE) {
	die('Oops! FCM Send Error: ' . curl_error($ch));
   }
   curl_close($ch);
   return $result;
}

You should pass all your custom attributes in data parameter as an array. If you’re sending to single user, pass user id or topic id in target parameter as string. For group notification, pass all user ids as an array in target parameter. Don’t forget to replace PASTE_YOUR_SERVER_KEY_HERE with your actual Secret Server Key that can be found in Firebase Console.

Continue Reading: FCM Push Notifications: Receive Messages in an Andriod App

Need further help? If you’re confused or facing any issue while completing first step, let’s know in comments.

Love What You're Reading?
Subscribe to our top stories
Subscribe
Give it a try, you can unsubscribe anytime.

Disclosure: This page may contain external affiliate links, endorsement, recommendation, and/or testimonial to any products and services that may result in us receiving a small commission if you choose to purchase said product or service.

FCM Push Notifications: PHP Server Side Integration

log in

Become a part of our community!

reset password

Back to
log in
DON’T MISS OUT!
Subscribe To Our Newsletter
Be the first to get latest updates and exclusive content straight to your email inbox.
STAY UPDATED
Give it a try, you can unsubscribe anytime.
Love What You're Reading?
Subscribe to our top stories
Subscribe
Give it a try, you can unsubscribe anytime.
50% Off on all advertisement packages. Limited time only!
ORDER NOW