Skip to content

Instantly share code, notes, and snippets.

@TheFox
Last active December 22, 2015 08:39
Show Gist options
  • Save TheFox/6446917 to your computer and use it in GitHub Desktop.
Save TheFox/6446917 to your computer and use it in GitHub Desktop.
Google Android Cloud to Device Messaging
<?php
/*
Role of the Third-Party Application Server
https://developers.google.com/android/c2dm/#server
*/
function gc2dmAuth($username, $password = null, $source = 'First-PushApp-1.0', $service = 'ac2dm'){
if($password === null || !$password){
print "GC2DM ERROR: no password set\n";
return null;
}
$ch = curl_init();
if(!$ch){
print "GC2DM ERROR: can not init curl\n";
return null;
}
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);
$response = curl_exec($ch);
curl_close($ch);
if(strpos($response, '200 OK') === false){
print "GC2DM ERROR: Google response failed\n";
return null;
}
preg_match('/(Auth=)([\w|-]+)/', $response, $matches);
if(!isset($matches[2])){
print "GC2DM ERROR: No auth found in Google response\n";
return null;
}
return $matches[2];
}
function gc2dmMsgSend($authCode, $deviceRegistrationId, $msgId, $messageText, $dataCustomPayload = null){
$headers = array('Authorization: GoogleLogin auth='.$authCode, 'application/x-www-form-urlencoded', 'charset=UTF-8');
$data = array(
'registration_id' => urlencode($deviceRegistrationId),
'collapse_key' => urlencode($msgId),
'data.payload' => urlencode($messageText),
);
if($dataCustomPayload){
foreach($dataCustomPayload as $key => $val){
$data['data.'.$key] = $val;
}
}
$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);
//curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment