Skip to content

Instantly share code, notes, and snippets.

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 ashokdhaduk/57605bc1a4fad2761823e3d5cb35d0a9 to your computer and use it in GitHub Desktop.
Save ashokdhaduk/57605bc1a4fad2761823e3d5cb35d0a9 to your computer and use it in GitHub Desktop.
Apple Push Notifications Service (APNS) in PHP
//$vHost = 'gateway.sandbox.push.apple.com';
$vHost = 'gateway.push.apple.com';
$vPort = 2195;
$vCert = APPPATH.'../assets/certificates/Certificates-Production.pem';
$vPassphrase = 'password to your pem file';
$vToken = $data['token'];
$vAlert = array(
"title" => $data['title'],
"body" => $data['body'],
"action-loc-key" => $data['action-loc-key']
);
unset($data['title']);
unset($data['body']);
unset($data['action-loc-key']);
unset($data['token']);
/*$vBadge = 1;*/ /* You can un-comment this & see the magic */
$vSound = 'default';
// Create the message content that is to be sent to the device.
$vBody = $data;
$vBody['aps'] = array (
'alert' => $vAlert,
'sound' => $vSound,
);
/*$vBody['aps']['badge'] = $vBadge;*/ /* You can un-comment this & see the magic */
foreach ($customData as $key => $value)
{
$vBody['aps'][$key] = $value;
}
// Encode the body to JSON.
$vBody = json_encode ($vBody);
// Create the Socket Stream.
$vContext = stream_context_create ();
stream_context_set_option ($vContext, 'ssl', 'local_cert', $vCert);
// Remove this line if you would like to enter the Private Key Passphrase manually.
stream_context_set_option ($vContext, 'ssl', 'passphrase', $vPassphrase);
try
{
// Open the Connection to the APNS Server.
$vSocket = stream_socket_client ('ssl://'.$vHost.':'.$vPort, $error, $errstr, 30, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $vContext);
// Check if we were able to open a socket.
if (!$vSocket)
{
return array("status" => false, "msg" => "APNS Connection Failed: $error $errstr");
}
// Build the Binary Notification.
$vMsg = chr (0) . chr (0) . chr (32) . pack ('H*', $vToken) . pack ('n', strlen ($vBody)) . $vBody;
// Send the Notification to the Server.
$vResult = fwrite ($vSocket, $vMsg, strlen ($vMsg));
// Close the Connection to the Server.
fclose ($vSocket);
if ($vResult)
{
return array("status" => true, "msg" => "Delivered Message to APNS");
}
else
{
return array("status" => false, "msg" => "Could not Deliver Message to APNS");
}
}
catch (Exception $e)
{
return array("status" => false, "msg" => "Caught exception: ".$e->getMessage());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment