Skip to content

Instantly share code, notes, and snippets.

@trbsi
Forked from joashp/PushNotifications.php
Last active March 11, 2018 04:18
Show Gist options
  • Save trbsi/44a52a7208661359bf35 to your computer and use it in GitHub Desktop.
Save trbsi/44a52a7208661359bf35 to your computer and use it in GitHub Desktop.
Simple PHP script to send Android Push Notification, iOS Push Notification and Windows Phone 8 Push Notification
<?php
// Server file
class PushNotifications
{
// (Android)API access key from Google API's Console.
private static $API_ACCESS_KEY = 'AIzaSyDG3fYAXXXXX-XXXXXJyJXiO5JagAsYI';
// (iOS) Private key's passphrase.
private static $passphrase = 'joashp';
// (Windows Phone 8) The name of our push channel.
private static $channelName = "joashp";
// Change the above three vriables as per your app.
public function __construct() {
exit('Init function is not allowed');
}
// Sends Push notification for Android users
public static function android($data, $reg_id) {
$url = 'https://android.googleapis.com/gcm/send';
$message = array(
'title' => $data['mtitle'],
'message' => $data['mdesc'],
'subtitle' => '',
'tickerText' => '',
'msgcnt' => 1,
'vibrate' => 1
);
$headers = array(
'Authorization: key=' .self::$API_ACCESS_KEY,
'Content-Type: application/json'
);
$fields = array(
'registration_ids' => $reg_id,
'data' => $message,
);
return self::useCurl($url, $headers, json_encode($fields));
}
// Sends Push's toast notification for Windows Phone 8 users
public static function WP($data, $uri) {
$delay = 2;
$msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
"<wp:Notification xmlns:wp=\"WPNotification\">" .
"<wp:Toast>" .
"<wp:Text1>".htmlspecialchars($data['mtitle'])."</wp:Text1>" .
"<wp:Text2>".htmlspecialchars($data['mdesc'])."</wp:Text2>" .
"</wp:Toast>" .
"</wp:Notification>";
$sendedheaders = array(
'Content-Type: text/xml',
'Accept: application/*',
'X-WindowsPhone-Target: toast',
"X-NotificationClass: $delay"
);
$response = self::useCurl($uri, $sendedheaders, $msg);
$result = array();
foreach(explode("\n", $response) as $line) {
$tab = explode(":", $line, 2);
if (count($tab) == 2)
$result[$tab[0]] = trim($tab[1]);
}
return $result;
}
public static function iOS($data, $deviceTokens)
{
if(Api::SANDBOX==true)
{
$applePushGateway="ssl://gateway.sandbox.push.apple.com:2195";
$ckpem="ck_sandbox.pem";
}
else
{
$applePushGateway="ssl://gateway.push.apple.com:2195";
$ckpem="ck_production.pem";
}
$ctx = stream_context_create();
// ck.pem is your certificate file
stream_context_set_option($ctx, 'ssl', 'local_cert', $ckpem); //PUT THIS .pem file IN A DIRECTORY WHERE YOU EXECUTE TestNotifications.php
stream_context_set_option($ctx, 'ssl', 'passphrase', self::$passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
$applePushGateway, $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
{
return false;
exit("Failed to connect: $err $errstr" . PHP_EOL);
}
// Create the payload body
$body['aps'] =
[
'alert' =>
[
'title' => $data['title'],
'body' => $data['body'],
],
'sound' => $data['sound'],
];
//only if badge is set, send it
if(isset($data['badge']))
$body['aps']['badge']=(int)$data['badge'];
// Encode the payload as JSON
$payload = json_encode($body);
//if you have multiple tokens for one user or if you want to send notifications to more user take all the tokens you need and put in array and use foreach to send notification, this way is faster because connection to apple server is opened during sending
foreach($deviceTokens as $deviceToken)
{
// Build the binary notification
$msg = chr(0).pack('n', 32).pack('H*', $deviceToken).pack('n', strlen($payload)).$payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
}
// Close the connection to the server
fclose($fp);
if (!$result)
return false; //return 'Message not delivered' . PHP_EOL;
else
return true; //return 'Message successfully delivered' . PHP_EOL;
}
// Curl
private static function useCurl($url, $headers, $fields = null) {
// Open connection
$ch = curl_init();
if ($url) {
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ($fields) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
}
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
return $result;
}
}
}
?>
<?php
require_once('PushNotifications.php');
// Message payload
$msg_payload = array (
'mtitle' => 'Test push notification title',
'mdesc' => 'Test push notification body',
);
// For Android
// get this from android, inside code
$regId[] = 'APA91bHdOmMHiRo5jJRM1jvxmGqhComcpVFDqBcPfLVvaieHeFI9WVrwoDeVVD1nPZ82rV2DxcyVv-oMMl5CJPhVXnLrzKiacR99eQ_irrYogy7typHQDb5sg4NB8zn6rFpiBuikNuwDQzr-2abV6Gl_VWDZlJOf4w';
$regId[] = 'ADS546JRM1jvxmGqhComcpVFDqBcPfFGHGFjH68D1nPZ82rV2DxcyVv-oMMl5CJPhVXnLrzKiacR99eQ_irrYogy7typHQDb5sg4NB8zn6rFpiBuikNuwDQzrjJhvHJJHU7787';
// For iOS
//get this from iOS, inside code
$deviceToken[] = 'FE66489F304DC75B8D6E8200DFF8A456E8DAEACEC428B427E9518741C92C6660';
$deviceToken[] = 'FEdd56g4DC75B8D6E8200DFF8A456E8DAfdgfdjhfhhC428B45hddf5df92C6660';
$deviceToken[] = 'dfgggt5677456E8DAfdgfdjhfhhCffndjjiweplk47snn444999sjjgnnmqww6660';
// For WP8
$uri = 'http://s.notify.live.net/u/1/sin/HmQAAAD1XJMXfQ8SR0b580NcxIoD6G7hIYP9oHvjjpMC2etA7U_xy_xtSAh8tWx7Dul2AZlHqoYzsSQ8jQRQ-pQLAtKW/d2luZG93c3Bob25lZGVmYXVsdA/EKTs2gmt5BG_GB8lKdN_Rg/WuhpYBv02fAmB7tjUfF7DG9aUL4';
// Replace the above variable values
PushNotifications::android($msg_payload, $regId);
PushNotifications::WP8($msg_payload, $uri);
PushNotifications::iOS($msg_payload, $deviceToken);
?>
@trbsi
Copy link
Author

trbsi commented Dec 4, 2015

Little tutorial for Android Notifications
https://trinitytuts.com/android-push-notification-using-gcm/
In this tutorial you will be asked for GOOGLE_PROJECT_ID:
5231ab8e-9a9d-11e5-8d49-4fa8a4aec74c

for iOS
http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1

@trbsi
Copy link
Author

trbsi commented Dec 4, 2015

Put ".pem" file in a folder where you execute TestNotifications.php

@emincer
Copy link

emincer commented Feb 19, 2016

When I use your fork I get the following PHP error... any suggestions?

PHP Strict Standards: Non-static method PushNotifications::useCurl() should not be called statically

@trbsi
Copy link
Author

trbsi commented Jun 8, 2016

It should work, since useCurl is static method private static function useCurl()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment