Sending Push Notifications on iOS using APNS & PHP

pradeep's Avatar author of Sending Push Notifications on iOS using APNS & PHP
This is an article on Sending Push Notifications on iOS using APNS & PHP in Engineering Concepts.
APNS or Apple Push Notification Service, is service for Apple devices like iPhone, iPad & iPod to send 3rd party notifications to devices. It was launched with iOS version 3.0, it's very helpful for the app developers as they do not have to frequently poll for updates, instead they can submit the notification to APNS and device when online will fetch the notification and alert the user. This removes the need for the app to run on the device all the time to receive updates, and the user can also control what app's notifications they would like to receive and what they do not want.

In this article we will look at sending a notification to the APNS using PHP. You'll need the certificate from your Apple Developer console for your app. And EnTrust CA file which can be fetched from https://www.entrust.net/downloads/bi...st_2048_ca.cer

Send Notification Using PHP



The APNS has it's own binary protocol which is quite simple, the structure of a tuple/record/message is like this:

Code:
Command -> 1 byte
Notification Id -> 32-bit unsigned int
Expiry -> 32-bit unsigned int (timestamp)
Length of device token -> 16-bit unsigned int
Device token binary -> binary data
Length of the payload (notification in JSON format) -> 16-bit unsigned int
Payload -> payload in JSON format

Sample JSON payload for notification:
Code: JSON
{
   "aps":{
      "alert":{
         "body":"hello new notification"
      },
      "badge":5
   },
   "extra_param":"XSDA"
}

Now, here's how we are going to send the notification using PHP:

Code: PHP
$options = array('ssl' => array(
    'local_cert' => 'apns-cert.pem',
    'passphrase' => '',
    'cafile' => 'entrust_2048_ca.cer'
));

$streamContext = stream_context_create();
stream_context_set_option($streamContext, $options);
$apns = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

$id = rand(9,999);
$time = time()+3600;
$payload = '{"aps":{"alert":{"body":"hello new notification"},"badge":5},"extra_param":"XSDA"}';
$device_token = 'da728f07f19ddf323e61ce52c32d4d80ec1385fdaa2041eddea2c4f492f6b7e6';

$apnsMessage = pack('CNNnana',1,$id,$time,32,pack('H*',$device_token),strlen($payload),$payload);

fwrite($apns, $apnsMessage);   
fclose($apns);
?>

I hope the article was helpful.
shabbir like this