C2Dm Implementation PHP Code

C2DM implementation PHP code

To register your own server system and obtain the Authorise Tokens (this is what Cpt. Ohlund proposed):

function googleAuthenticate($username, $password, $source="Company-AppName-Version", $service="ac2dm") {    

session_start();
if( isset($_SESSION['google_auth_id']) && $_SESSION['google_auth_id'] != null)
return $_SESSION['google_auth_id'];

// get an authorization token
$ch = curl_init();
if(!ch){
return false;
}

curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
$post_fields = "accountType=" . urlencode('HOSTED_OR_GOOGLE')
. "&Email=" . urlencode($username)
. "&Passwd=" . urlencode($password)
. "&source=" . urlencode($source)
. "&service=" . urlencode($service);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// for debugging the request
//curl_setopt($ch, CURLINFO_HEADER_OUT, true); // for debugging the request

$response = curl_exec($ch);

//var_dump(curl_getinfo($ch)); //for debugging the request
//var_dump($response);

curl_close($ch);

if (strpos($response, '200 OK') === false) {
return false;
}

// find the auth code
preg_match("/(Auth=)([\w|-]+)/", $response, $matches);

if (!$matches[2]) {
return false;
}

$_SESSION['google_auth_id'] = $matches[2];
return $matches[2];
}

To send a message to a phone:

// $msgType: all messages with same type may be "collapsed": if multiple are sent,
// only the last will be received by phone.
function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText) {

$headers = array('Authorization: GoogleLogin auth=' . $authCode);
$data = array(
'registration_id' => $deviceRegistrationId,
'collapse_key' => $msgType,
'data.message' => $messageText //TODO Add more params with just simple data instead
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/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);

curl_close($ch);

return $response;
}

PHP - C2DM Application Server Implementation

Try using below sample code, It is working fine.

<?php
define("C2DM_ACCOUNT_EMAIL","[C2DM_EMAIL]");
define("C2DM_ACCOUNT_PASSWORD","[C2DM_PASSWORD]");
define("C2DM_CLIENT_LOGIN_URL","https://www.google.com/accounts/ClientLogin");
define("C2DM_MSG_SEND_URL","https://android.apis.google.com/c2dm/send");

function sendPushNotification($device_reg_id,$msg){

$auth_id=get_auth_id(); // To get Auth ID

$post_fields=array(
'collapse_key=ck_1',
'registration_id='. trim($device_reg_id),
'data.payload='. trim($msg),
);

$data_str=implode('&', $post_fields);

$headers = array(
'Authorization: GoogleLogin auth='.trim($auth_id),
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.trim(strlen($data_str)),
'Connection: close'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,C2DM_MSG_SEND_URL);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// print_r($server_output);
}

function get_auth_id(){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,C2DM_CLIENT_LOGIN_URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Email=".C2DM_ACCOUNT_EMAIL."&Passwd=".C2DM_ACCOUNT_PASSWORD."&accountType=GOOGLE&source=Google-cURL-Example&service=ac2dm");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// print_r($server_output);
$parts=explode("Auth=",$server_output);
$auth_id=$parts[1];
// echo $auth_id;
return $auth_id;
}

$reg_id = "[DEVICE_REG_ID]";
sendPushNotification($reg_id,"Hello World...!! Jay is testing C2DM...");

FYI! No need to call get_auth_id() every time you send notification, You can call once and store auth_id somewhere in config file also.

How to call the C2DM PHP Function from the Android APP

First off, C2DM is dead. Long live GCM!

Secondly, here's an example.

C2DM Application Server solution

The server part of C2DM is a piece of cake compare to the client (in my opinion). You can find below some tutorials about the server part :

One for JAVA very easy to understand even if your are not JAVA developper.

One for PHP and Zend framework.

A basic example for C# on stackoverflow

A common mistake to avoid if you want some performance : Don't connect for each message to send.
You just have to auth one time to the google server and then you can send multiple notification message.

Also don't forget that Google will periodically refresh the token in an Update-Client-Auth header. You should handle this header to keep your tokens up to date. Have look to this discussion about it

C2DM with PHP using OAuth2.0 (ClientLogin is deprecated!)

That does not apply with C2DM since is a hosted accountif you see the https://developers.google.com/accounts/docs/AuthForInstalledApps it saids

ClientLogin can be used to authorize access to both Google regular and
hosted accounts. A hosted account is a user account that is part of
the Google Apps service.

Also, if you see the graphic is a clear interaction between User as a UI interface since a CAPTCHA is involved.

Sample Image

Edit

BTW you can see from this post C2DM mechanism still will be using ClientLogin nevertheless the key before October 2011 were going to expired, so you need to recreate them. This is a pretty recent post from 8 days before the ClientLogin was deprecated. C2DM Client Login Key

Some Queries on C2DM in Android

My solution has just been to mark records as deleted in my database if Google gives me a response indicating that it's an invalid registration or no longer registered. Then it only fails once for a given registration.

Some Queries on C2DM in Android

My solution has just been to mark records as deleted in my database if Google gives me a response indicating that it's an invalid registration or no longer registered. Then it only fails once for a given registration.

Android : c2md implementation

Firewall issue, probably? Try when the device is on 3G, as opposed to WiFi.

Push Notification in android c2dm

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: GoogleLogin auth=$token", "Content-Length: $len", "Content-Type: application/x-www-form-urlencoded"));

echo curl_exec($ch);

curl_close($ch);

This is the php code that my app uses to send C2DM messages where $data is your data array. Please note that the Content-Length is necessary and is is the length of your data.

EDIT: Something you may also find useful a class for php that makes sending messages a little nicer.



Related Topics



Leave a reply



Submit