Skip to content

Instantly share code, notes, and snippets.

@schmiddim
Last active December 18, 2015 08:39
Show Gist options
  • Save schmiddim/5755352 to your computer and use it in GitHub Desktop.
Save schmiddim/5755352 to your computer and use it in GitHub Desktop.
Google Cloud Messaging(GCM) Serverside example
<?php
class GoogleCloudMessagingHandler{
protected $apiKey;
protected $ids=array();
protected $url= 'https://android.googleapis.com/gcm/send';
public function __construct($apiKey){
$this->apiKey = $apiKey;
$this->fetchIds();
}
protected function fetchIds(){
$sql ='SELECT registrationID FROM android_registered_ids';
$result =DB::getInstance()->getAll($sql, null);
foreach($result as $v){
$this->ids[] = $v['registrationID'];
}
}
public function sendMessage($message){
##echo $message;
#print_r($this->ids);
//setup fields + headers
$fields = array(
'registration_ids' => $this->ids,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $this->apiKey,
'Content-Type: application/json'
);
//lets curl
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $this->url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result ."\n";
}
public function registerForMulticast($id){
if(empty($id))
return false;
$sql ='SELECT registrationID
FROM android_registered_ids
WHERE registrationID = :ID ';
$data = array(':ID' =>$id);
$result =DB::getInstance()->getAll($sql,$data);
if(empty($result) ){
$sql ='INSERT INTO
android_registered_ids
(registrationID)
VALUES ( :ID )';
$result =DB::getInstance()->insert($sql, $data );
return true;
} else {
return false;
}
return false;
}
}
define('GCM_API_KEY', 'DEIN API KEY');
$message = "Guten Morgen aus M&uuml;nchen";
$gcmHandler = new GoogleCloudMessagingHandler(GCM_API_KEY);
$gcmHandler->sendMessage($message);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment