Getting started with GCM

How GCM works:-
1> App is registered with  GCM (App registration). To register with GCM

>  The client app obtains a registration token using the Instance ID API. The call to this API must have the authorized entity set to your app server’s sender ID, and the scope set to the appropriate value for GCM (depending on your platform). Refer to the API reference for full detail on this API.

>  The client app passes the registration token to the app server

> The app server saves the registration token and acknowledges to the client app that the process completed successfully.

2> Send this Registration id to local server and save it in db or file system.

3> Then for broadcasting message make an API call to GCM by sending json data. (APP KEY and Registration id as an array)

Registering:-

1> open https://console.cloud.google.com/home/dashboard

2> Create a project (say GcmTest)

3> Under project tab (Project: GcmTest), you can find Project number. This will be your sender id.
Which will be send by an app to you GCM server and registration id will be generated.

4> Then click on “Enable and Manage API” link under “Use Google Api section”

cloud1

5> Then select “Google Cloud Messaging” and enable it.

6> Go to credential tab and click on “create credential” button.

cloud3

7> Copy API key.
Create Registration id:-
For this you have to develop App. (android, ios, chrome app)

Better use existing project (https://github.com/googlesamples/gcm-playground) rather than building from scratch.

Download this project, Follow the instruction described over there for setting up app.

Form there you will get registration id.
Now For Broadcasting message:-

Make a POST request to url:-https://android.googleapis.com/gcm/send
by sending Post data (Registration Ids(array) and App key (in header)

https://gcm-http.googleapis.com/gcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{ 
  notification' : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark"
   }
  "data": {
      "score": "5x1",
      "time": "15:10"
  },
  "registration_ids" : [
      "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
      "ffffffff3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
  ]
}

Payload:-

For downstream messaging, GCM provides two types of payload: notification and data. > Notification is the more lightweight option, with a 2KB limit and a predefined set of user-visible keys.  When notification is passed with post data, GCM to handle displaying a notification on client app’s behalf.

> Data payload lets developers send up to 4KB of custom key/value pairs. Use data messages when you want app to handle the display or process the messages on Android client app, or if you want to send messages to iOS devices when there is a direct GCM connection.

Check the Server Reference for a list of all the message parameters and which connection server(s) supports them.

Example Server side code (PHP):-

Replace API key and registration ID form code

create a php file

 gcm.php

<?php
function sendMessageThroughGCM($regestration_id, $message, $app_key)
{
     $url = 'https://android.googleapis.com/gcm/send';
     $fields = array(
        'registration_ids' => $regestration_id,
        'data' => array( "message" => $message ),
     );
     $headers = array(
        'Authorization: key=' . $app_key,
        'Content-Type: application/json'
     );
     // Open connection
     $ch = curl_init();
    // Set the url, number of POST vars, POST data
    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, json_encode( $fields ) );
    // Avoids problem with https certificate
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
    // Execute post
    $result = curl_exec($ch);
    // Close connection
    curl_close($ch);
    return $result;
 }
 
 //Post message to GCM when submitted
 $pushStatus = "GCM Status Message will appear here";
 if(!empty($_GET["push"])) {
    $pushMessage = $_POST["message"];
    if (isset($pushMessage)) {
      // initialize gcmRegIds with all registration token
      //example
      $gcmRegIds = array(
          'APA91bHjPt-9-Ix501Zx.......................OK4Dam0zg',
          'APAlkjiuyg91bHjPt-9-Ix501Zx...................0zg'
      );
      $message = array("m" => $pushMessage);
      $api_key = "AIzaSy........................ur3ADE"; // replace with your API key
      $pushStatus = sendMessageThroughGCM($gcmRegIds, $message, $api_key);
    }
 }
?>

<html>
  <head>
     <title>Google Cloud Messaging (GCM) in PHP</title>
  </head>
 <body>
    <form method="post" action="gcm.php/?push=true">
       <textarea rows="5" name="message" cols="45" placeholder="Message to send via GCM"></textarea> <br/>
       <input type="submit" value="Send Push Notification through GCM" />
    </form>
    <p id="status">
        <?php echo $pushStatus; ?>
    </p>
  </body>
</html>
 You will get response something like this:-
{
   "multicast_id":5506519224470981550,
   "success":1,
   "failure":1,
   "canonical_ids":0,
   "results":[
       {"message_id":"0:1461096681643130%a8dca0a9f9fd7ecd"}
   ]
}
 Check here for downstream message response meaning.
 Suppose response is (reference) :-
Here are JSON results for 6 recipients (IDs 4, 8, 15, 16, 23, and 42 respectively) with 3 messages successfully processed, 1 canonical registration token returned, and 3 errors:
{ "multicast_id": 216,
  "success": 3,
  "failure": 3,
  "canonical_ids": 1,
  "results": [
    { "message_id": "1:0408" },
    { "error": "Unavailable" },
    { "error": "InvalidRegistration" },
    { "message_id": "1:1516" },
    { "message_id": "1:2342", "registration_id": "32" },
    { "error": "NotRegistered"}
  ]
}

In this example:

  • First message: success, not required.
  • Second message: should be resent (to registration token 8).
  • Third message: had an unrecoverable error (maybe the value got corrupted in the database).
  • Fourth message: success, nothing required.
  • Fifth message: success, but the registration token should be updated in the server database (from 23 to 32).
  • Sixth message: registration token (42) should be removed from the server database because the application was uninstalled from the device.
NOTE:-
– In response, success only specify how many “registration id” GCM server accepted and added in queue and failure specify how many “registration id” is rejected by GCM.
– For use cases such as instant messaging, a GCM message can transfer up to 4kb of payload to the client app
It does not confirm whether notification is sent to app or not.
 For further details refer link https://developers.google.com/cloud-messaging/gcm

Leave a comment