Skip to content

Instantly share code, notes, and snippets.

@A35G
Created September 21, 2017 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A35G/0ff0733aebc210f0762cdc3bf1a73afe to your computer and use it in GitHub Desktop.
Save A35G/0ff0733aebc210f0762cdc3bf1a73afe to your computer and use it in GitHub Desktop.
Is your device's Token for Push Notifications valid yet? Check it out now!
<?php
class PushMessage {
private $url = 'https://fcm.googleapis.com/fcm/send';
private $serverApiKey = "";
private $devices = array();
function __construct($apiKeyIn){
$this->serverApiKey = $apiKeyIn;
}
public function setDevices($deviceIds){
$this->devices = (is_array($deviceIds)) ? $deviceIds : array($deviceIds);
}
public function testToken() {
$device_test = array();
if (!is_array($this->devices) || count($this->devices) == 0)
$this->error("No devices set");
if (strlen($this->serverApiKey) < 8)
$this->error("Server API Key not set");
$fields = array(
'registration_ids' => $this->devices,
'dry_run' => true
);
$headers = array(
'Authorization: key='.$this->serverApiKey,
'Content-Type: application/json'
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $this->url,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($fields),
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false
));
$http_body = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$device_test = array(
"http_body" => $http_body,
"http_code" => $http_code
);
return $device_test;
}
private function error($msg){
echo "FCM send notification failed with error:";
echo "\t".$msg;
exit(1);
}
}
define("API_KEY", ""); // Your API Key
$devices = array();
if (!($fcm_push instanceof PushMessage)) {
if (class_exists("PushMessage"))
$fcm_push = new PushMessage(API_KEY);
}
$devices[] = ""; // Token of Device/Devices
$show_response = true;
$content_full = "";
if (!empty($devices)) {
$fcm_push->setDevices($devices);
$response_server = $fcm_push->testToken();
if (!empty($response_server)) {
$info_resp = $response_server;
$status_code = json_decode($info_resp['http_code']);
if ($status_code == 200) {
$content = json_decode($info_resp['http_body']);
//$content_full = print_r($content, 1); // As Object
$content_full = print_r(json_decode($info_resp['http_body'], 1), 1); // As Array
$tot_devices = count($devices);
$devices_with_success = $content->success;
$devices_with_error = $content->failure;
if (!empty($content->failure)) {
for ($i = 0; $i < $tot_devices; $i++) {
if (isset($content->results[$i]->error)) {
echo "Error with Token: ".$devices[$i]." - Error: ".$content->results[$i]->error."\r\n";
}
}
}
}
}
}
if ($show_response)
echo $content_full;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment