Skip to content

Instantly share code, notes, and snippets.

@takimo
Created June 19, 2011 11:01
Show Gist options
  • Save takimo/1034068 to your computer and use it in GitHub Desktop.
Save takimo/1034068 to your computer and use it in GitHub Desktop.
c2dm for php
<?
class c2dm
{
private $google_auth_url = 'https://www.google.com/accounts/ClientLogin';
private $auth = '';
public function __construct($google_id, $google_pwd)
{
$this->authorize($google_id, $google_pwd);
}
public function authorize($google_id, $google_pwd)
{
$header = array(
'Content-type: application/x-www-form-urlencoded',
);
$post_list = array(
'accountType' => 'GOOGLE',
'Email' => $google_id,
'Passwd' => $google_pwd,
'source' => 'sample-sample',
'service' => 'ac2dm',
);
$post = http_build_query($post_list, '&');
$ch = curl_init($this->google_auth_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$ret = curl_exec($ch);
preg_match('/Auth=(.*)/', $ret, $matches);
$this->auth = $matches[1];
}
public function send($registration_id, $data)
{
$url = 'https://android.apis.google.com/c2dm/send';
$header = array(
'Content-type: application/x-www-form-urlencoded',
'Authorization: GoogleLogin auth='.$this->auth,
);
$post_list = array(
'registration_id' => $registration_id,
'collapse_key' => 1,
);
foreach ($data as $key => $value){
$post_list["data.".$key] = $value;
}
$post = http_build_query($post_list, '&');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$ret = curl_exec($ch);
return $ret;
}
}
?>
<?php
require_once('./c2dm.class.php');
$google_id = 'hogehoge@gmail.com';
$google_pwd = 'hogehoge';
$registration_id = 'samplesamplesample';
$data = array(
'message' => "hogehogehoge"
);
$c2dm = new c2dm($google_id, $google_pwd);
print_r($c2dm->send($registration_id, $data));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment