PART I: How to implement GCM PhP Push Server for android

In my previous post, GCM replaces C2DM, I was just expressing my happiness of what I think is the best of the new Google Cloud Messaging.

Now this is a small guide for those who would like to add push notifications to their applications:
This part will explain how to prepare your server to send push messages. In another post, preparing the android app will be discussed.


STEP 1: Get an access token to issue push requests to the android GCM server

First of all, go to the google APIs console page and create a new project by pressing the Create project button. If you already have a project created, just create a new one for our purpose.

You will probably be directed to the services page, just search for "Google Cloud Messaging for Android" and press the button next to it (turn it on). Once you accept the license, you are good to go. Btw, if you were not redirected to the services page, just search for it, its somewhere on the page you are in.

Just before leaving, open your favorite text editor and save the id of your project: This can be found upstairs in the url (address bar), it will probably contain something like "project:5664646216546". Yeah! save the green number.

We are almost done, we need the token: search for API Access and press it. At the time of this writing, it was somewhere in the left menu on the page. Ok, once your there, you will find some sort of button saying "Create new Server key...". press it and you will get small form with bla bla bla and downstairs a "Create" button which you have to press. PS do not press the "Cancel" button.

Refresh the page to get the API key: here is a small illustration just to make sure you got it all right:

Make sure this is there

Congratulations, you have your TOKEN :D

STEP 2: Use the access token to issue push messages to devices

Now we have an access token: Lets send the message (I will edit this code to handle errors asap)

Just to clarify $yourKey is the token that we have been working to get in STEP 1. $deviceToken is the token of the device which this message will be sent to. $collapseKey is a key used to override any previous messages with the same $collapseKey. I will post on getting this $deviceToken soon.

$yourKey = 'PUT_YOUR_KEY_HERE';
function sendMessageToPhone($deviceToken, $collapseKey, $messageText, $yourKey)  
{  
    $headers = array('Authorization:key=' . $yourKey);  
    $data = array(  
        'registration_id' => $deviceToken,  
        'collapse_key' => $collapseKey,  
        'data.message' => $messageText);
  
    $ch = curl_init();  
  
    curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");  
    if ($headers)  
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);  
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  
    curl_setopt($ch, CURLOPT_POST, true);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  
  
    $response = curl_exec($ch);  
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
    if (curl_errno($ch)) {  
        //request failed  
        return false;//probably you want to return false  
    }  
    if ($httpCode != 200) {  
        //request failed  
        return false;//probably you want to return false  
    }  
    curl_close($ch);  
    return $response;  
}
This is tested and working! If you have any suggestions, leave a comment.

Advice: For all those who did not watch Ace Ventura Pet Detective, watch it!

12 comments:

  1. I cant run this example directly, I'm new in php and if i put a button i dont see anything. Could you send an example, please.

    thanks

    ReplyDelete
  2. The variable names in line 7 and 8 are incorrect, they must be as follows:
    'registration_id' => $deviceToken,
    'collapse_key' => $collapseKey,

    Also, the url has a couple of extra "<b>" that shouldn't be there. The correct url must be:
    curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");

    Did you actually tried this before posting it?

    ReplyDelete
    Replies
    1. I am sorry that happened because of some backup I did for the post. I actually have not tried it, but if you did, it should work

      Delete
  3. plz post the link for corresponding android app
    and how to get device id plz explain

    ReplyDelete
  4. Replies
    1. Not blank, but you can not declare the field at all.
      Example:
      $data = array(
      'registration_id' => $deviceToken,
      'collapse_key' => "",
      'data.message' => $messageText);
      ////NOT CORRECT
      $data = array(
      'registration_id' => $deviceToken,
      'data.message' => $messageText);
      ////YEAH

      In this case you send all messages to device instead of overwrite the old ones not sent yet. Read here for the docs:
      http://developer.android.com/guide/google/gcm/gcm.html (just a bit under the half page)

      "collapse_key An arbitrary string (such as "Updates Available") that is used to collapse a group of like messages when the device is offline, so that only the last message gets sent to the client. This is intended to avoid sending too many messages to the phone when it comes back online. Note that since there is no guarantee of the order in which messages get sent, the "last" message may not actually be the last message sent by the application server. See Advanced Topics for more discussion of this topic. Optional."

      Delete
  5. I am unable to get the device token in the success method of gcm.registerC2dm instead i am getting null or '' value of device token please help me regarding this if some one has idea.

    ReplyDelete
  6. Can someone please heeelp me . I am stuck . I am using iamyellow's GCM thing & we do not know shiz about php and HTTP I NEED LIKE A DUMMMIES BUT I AM still easy grasping on learning.. learners guide on how to even setup the SERVR side to receive push notifications.
    We need the easiest method even if one does not use GCM but another android/iPhone method .
    When you set it up.. how do you even send a message to your user/devices out there? Is it by going on the site? an APP on your device that pushes it out? or in the emulator? I am confused PLEASE HELP!

    ReplyDelete
  7. Is there any method to send Big Notifications (http://developer.android.com/guide/topics/ui/notifiers/notifications.html#BigNotify)? I tried to send the same "collapse_key" without success. Thanks.

    ReplyDelete
  8. What is $deviceToken exactly and how can obtain it?

    ReplyDelete
  9. Hello, I have a problem, i have tried the code but the $httpCode is different to 200, is it a problem of api_key or token or id proyect? thanks

    ReplyDelete