• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • About
  • Projects
    • GStaticMap WP Plugin
  • Contact
  • Privacy Policy

Lorenz Blog

All About Web & Mobile Application Development

  • Featured Articles
  • Gadgets
    • Android
    • Blackberry
  • Programming
    • Android
    • PHP
    • Java Script
    • MySQL
    • Postgresql
    • Flex
    • Web
  • Software
    • Mac OS
    • Windows
    • Linux
  • Web
You are Here » Home >> Information Technology >> Programming >> Android >> How to Send Message to Google Cloud Messaging (GCM) Server Using JSON and PHP

How to Send Message to Google Cloud Messaging (GCM) Server Using JSON and PHP

August 25, 2012 by Lorensius Londa 8 Comments

Google Cloud Messaging (GCM) is a free service from Google that helps Android developers to send data from their servers to Android applications on Android devices. GCM is the next generation of Android Cloud to Device Messaging (C2DM) which is currently deprecated but still in service without accepting new users and granting new quotas.

GCM architecture consists of three main components, Android application on mobile device, 3rd-party application server and GCM servers. To send message to Android applications on android devices, 3rd-party application server must send the message to GCM servers and let the GCM servers process and send the message to mobile devices. To learn more on how to setup the project and client application, please refer to GCM documentation that well documented and easy to undersand. GCM accepts two data format, JSON and plain text, but it is recommended to use JSON type for flexibility and easy of use.

To send a message, the application server must issue a POST request to the following url:

https://android.googleapis.com/gcm/send

The request is made up of two parts:

HTTP header, that must contain the following headers:

  • Authorization:key=your_api_key
  • Content-Type:application/json for JSON data type

HTTP body, which is for JSON data type must contain a string representing  a JSON object with the following fields:

  • registration_ids, is a string array of registration IDs. Registration IDs  are sent from android applications on mobile devices and saved in application server database.
  • data, is the payload data in array of key-value pair.
  • collapse_key (optional), is an arbitrary string 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.
  • time_to_live (optional), time in seconds where the message should be kept on GCM storage if the device is offline
  • delay_while_iddle (optional), a flag to indicate the message should not be sent immediately if the device is idle (true or false)

Example request:

Content-Type:application/json
Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA{"registration_ids":["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."],"data":{"score" : "1-0", "scorer" : "Ronaldo", "time: "44"},}

To send the above message using PHP, define your api key (line 6), the string array of registration IDs (line 9), the payload data in array of key-value pair (line 12), the HTTP headers which contains api key  (line 18) and the HTTP body content in JSON format, use json_encode function to transform the array into JSON object (line 29). The HTTP request type is POST and we use CURL to send the message to GCM server.

Every request will return a response, which might be success (the message is processed successfully) or rejected by GCM server. More detail on how to process the response can be read on this documention.

PHP code
[ad]

<?php
//request url
$url    = 'https://android.googleapis.com/gcm/send';

//your api key
$apiKey = 'AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA';

//registration ids
$registrationIDs = array('APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...');

//payload data
$data   = array('score' => '1-0', 'scorer' => 'Ronaldo', 'time' => '44');

$fields = array('registration_ids' => $registrationIDs,
                'data' => $data);

//http header
$headers = array('Authorization: key=' . $apiKey,
                 'Content-Type: application/json');

//curl connection
$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_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

$result = curl_exec($ch);

curl_close($ch);

echo $result;
?>
Facebooktwitterredditpinterestlinkedinmailby feather

Related posts:

  1. Solution to Make an Android App Visible to All Devices in Google Play When Using Specific Feature
  2. How to Setup MQTT Server Using Mosquitto and Libwebsocket on Freebsd
  3. Simple JSON RPC Client for Android
  4. How to Send Image to Twitpic from Android

Filed Under: Android, Featured Articles, PHP Tagged With: Android, C2DM, GCM, Google Cloud Messaging, json, PHP

About Lorensius Londa

Passionate web and mobile application developer. Co-founder of TRUSTUDIO, loves programming, Android, aviation, travelling, photography, coffee and gym mania.

Reader Interactions

Comments

  1. himanshu says

    October 11, 2012 at 1:16 pm

    Hello, I am using wamp local server to run this but i got this error on php output : {“multicast_id”:5754693764770083005,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”MismatchSenderId”}]}

    Please help me to acheive this…

    Reply
  2. Susan Flores says

    October 26, 2012 at 4:08 pm

    Actually we are using XAMPP and WAMP server for PHP.but using GCM server that i have heard from your site that we will try on that.

    Reply
  3. amazon coupon codes says

    February 13, 2013 at 10:36 am

    I’m really impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you customize it yourself? Anyway keep up the nice quality writing, it’s rare to see a nice blog like this one today.

    Reply
  4. sonu says

    April 26, 2013 at 1:22 pm

    Very Helpful
    BUt i have a problem with blank notifications
    How can we solve it

    Reply
  5. cmiklos says

    May 28, 2013 at 4:02 pm

    Hi!

    I only get “null” messages in the device using your code or others.. can´t find the problem.

    Can you help me?

    Reply
  6. macio.Jun says

    October 2, 2013 at 9:19 pm

    Hi PO,

    Can I use
    header(‘Content-Type: application/json’);
    $outputData = array(“name” => “John”);
    echo $outputData;

    // But what should I do next to send $outputData to https://android.googleapis.com/gcm/send
    // And how can I get response from gcm server?
    // Do I have to use curl to send data to gcm server?

    Thank you

    Reply
  7. David Cobas says

    April 9, 2015 at 8:19 pm

    Hi, im using you PHP code to send a gcm message but i get this response…
    {“multicast_id”:8317240779864738176,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}
    Why i get a invalidRegistration error? pls i need help

    Reply
  8. DeBukkIt says

    October 18, 2016 at 8:03 pm

    Good day! I’d like so send a message the way you described and it arrived, great!
    But: All the payload strings are missing unicode characters, e. g. the German Umlaute ö, ä, ü or the letter ß. Is there a way to proper encode and decode the transferred content of the JSON-String? UTF-8 would be great!

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About Me

A husband, father of two, passionate software developer, diy lover and home baker who loves to learn new things. Read More…

  • Facebook
  • GitHub
  • Google+
  • Instagram
  • Twitter
  • YouTube

Featured Articles

How to Setup MQTT Server Using Mosquitto and Libwebsocket on Freebsd

Blue Bamboo P25 Printer Android Demo Application With Source Code

Simple JSON RPC Client for Android

How to Send Message to Google Cloud Messaging (GCM) Server Using JSON and PHP

Footer

Recent Comments

  • Aditya Dabas on About
  • Ayten Göksenin Barutçu on How to Make Android Map Scrollable Inside a ScrollView Layout
  • mang jojot on About
  • Hussain on How to Programmatically Scan or Discover Android Bluetooth Devices

Recent Posts

  • How to Fix Blank Screen on WordPress Add/Edit Post Page
  • How to Programmatically Restart the ESP32 Board
  • How to Get Hardware Info of ESP32
  • How to Setup MQTT Server Using Mosquitto and Libwebsocket on Freebsd

Latest Tweets

  • @tricahyono_bowo @infobandung @infobdg Wah kejauhan om 355 days ago
  • Wilujeng enjing sadayana..Mohon info tempat powder coating dan sandblasting yg recommended di Bandung dunk @infobandung @infobdg359 days ago

Copyright © 2023 · Magazine Pro on Genesis Framework · WordPress · Log in