Send PUSH notification using Google FCM and PHP

How often do you receive the notifications ‘your friend tagged in you a post’, ‘your friend is live’ ?. It makes sure you never miss a thing no matter how busy you are. and as a developer how often you wish your app had the same ability to lure users back time after time into your app?

Today I’m gonna talk about how to send Cross Platform (Android/iOS) Push Notification using Firebase Cloud messaging (Google FCM) with PHP. first things first,

What actually is a Push Notification?

A Push Notification basically is a message that pops up on the user’s smartphone. It may be sent by the app publishers at any time; users don’t have to be in the app or be using their devices to receive them. A push notification can be about anything for example, they can show the latest sports scores, get a user to take an action, such as downloading a coupon, or let a user know about an event, such as a flash sale. It helps the user to lure back into the app and increase engagement.

Google Cloud Messaging

A while ago google announced (Google Cloud Messaging):  a free service that enables developers to send messages between servers and client apps which consisted downstream messaging from servers to client apps and upstream messages from client apps to servers (according to Google Documentation). Which helped publishers to send notifications to a set of users or a mass audience.

Here’s how GCM worked:

  1. An Android device sends sender id, application id to GCM server for registration.
  2. Upon successful registration, GCM server issues registration id to the device.
  3. After receiving registration id, the device will send registration id to our server.
  4. Our server will store registration id in the database for further use.
  5. Whenever push notification is needed, our server sends a message to GCM server along with device registration id (which is stored earlier in the database).
  6. GCM server delivers that message to the respective mobile device using device registration id.

Google FCM

But then not long ago, after acquiring Firebase in 2014, Google announced Firebase Cloud Messaging (FCM) to send various notifications and messages over various mobiles OS (even iOS) and the web. So why upgrade to FCM?

Even though FCM uses the core infrastructure of the GCM, there are various reasons to upgrade to FCM.

  • TOPIC BASED MESSAGING: Unlike GCM there wasn’t need to run the notification publish logic under a massive loop of devices tokens which we had previously stored to send notifications. now devices were registered under a specific topic for eg (ESPN_SPORTS) and we just needed to mention the topic and it did the rest from routing to delivering messaging to all the devices stored under the topic.
  • There wasn’t any need to write our own registration or subscription retry logic.

To upgrade from GCM SDKs to FCM SDKs, see the guides for migrating Android and iOS apps.

So after thihigh-levelel overview of GCM and the new FCM lets use FCM’s API with PHP to send push notifications to our devices.

Coding it

Before, coding we will need a server key, which we can obtain by doing the following:

  1. Login/sign-up to your firebase account.
  2. Then click on the gear icon on the left top and then click ‘project settings.’
  3. Also, register the APN certificates in the ‘ios app configuration’ to send the notifications to iOS devices.

We will develop a web GUI to send Push Notification to both Android and iOS devices. Before that, we will need to have a stable app installed on the phone.

So basically we will have 2 PHP files that subscribe devices to a given topic :

  1. A file that subscribes the devices. SDK’s should be set up to call the URL pointing the file upon opening of the app providing Firebase styled DEVICE_TOKEN. Devices will be registered with their device tokens.
  2. Another file to actually send the notification.
<?php
    if(!isset($_GET['device_token'])){
      echo "device token needed!!!";
      exit;
    }

      $server_key = 'AAAATl2-Vzw:APA91bFIi_TgoBmJEVJXrowhvMq0-uRurX977-XZ9Cl3yOsAGweMSpVfUJsSnAq5c5kmbe7V6hUrFkejXyAlbv32F92WGZzJ_u-vyO1Pw4wUm7ww4Izf21eZ4G0qxXpX37O6CaERwQ0T';

    
      $url = 'https://iid.googleapis.com/iid/v1:batchAdd';
      //$url = "https://iid.googleapis.com/iid/v1:batchRemove";
      $fields['registration_tokens'] = array($_GET['device_token']);
      $fields['to'] = '/topics/my-app';
      $headers = array(
      'Content-Type:application/json',
          'Authorization:key='.$server_key
      );
      
      $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);
      curl_close($ch);
      var_dump($result);exit;
?>

 

An example of the device subscription file (device_registration.php).

POST request is recommended while setting up the SDK’s to this URL. Make sure you have the desired topic set up as the topic has to MATCH the topic you define in the page where you send notifications.

Setting up the SDK’s

 iOS

First of all, we need to define the device Register URL as follows:

An example of the SDK setup.

 Android

Similarly as iOS setup, we need to define Registration URL for android as follows:

Example of the SDK setup.

Apps will now begin register or subscribe to topic defined in every open. Ok so lets move to
sending part now. we have a simple form to set up where we can send the notification.

At the backend, this form runs the following code upon submission.

<?php
$payload = array(
          'to'=>'/topics/my-app',
          'priority'=>'high',
          "mutable_content"=>true,
          "notification"=>array(
                      "title"=> $_POST['title'],
                      "body"=> $_POST['summary']
          ),
          'data'=>array(
                'action'=>'models',
                'model_id'=>'2701',
              )
        );
    $headers = array(
      'Authorization:key='AAAATl2-Vzw:APA91bFIi_TgoBmJEVJXrowhvMq0-uRurX977-XZ9Cl3yOsAGweMSpVfUJsSnAq5c5kmbe7V6hUrFkejXyAlbv32F92WGZzJ_u-vyO1Pw4wUm7ww4Izf21eZ4G0qxXpX37O6CaERwQ0T,
      'Content-Type: application/json'
    );
    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/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( $payload ) );
    $result = curl_exec($ch );
    curl_close( $ch );
    var_dump($result);exit;
?>

and that’s it.

Just like that, I received the notification with the desired title and summary.The title and body defines what users see in the actual notifications. You can send the data array accordingly to deep link the app to a certain page. As an example, here I am sending the model id so when the user’s clicks the notification it redirects you to the models page.

 

Moreover, you can filter your notifications audience for eg, device wise, geographically, etc simply just register their device accordingly to the respective topic. Make use of the flexibility of the topic, you will be able to get the desired result. as you can see Google FCM has made it really easy to send Push Notifications  across various platforms.

 

7 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.