Skip to content

Instantly share code, notes, and snippets.

@afiqiqmal
Last active August 11, 2019 04:10
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 afiqiqmal/c305c9ef3a97f975ec63aa13ee2216a5 to your computer and use it in GitHub Desktop.
Save afiqiqmal/c305c9ef3a97f975ec63aa13ee2216a5 to your computer and use it in GitHub Desktop.
Sample of APNS

Push notification iOS

Make sure to add .pem cert in storage/apns_certs/ with file name development.pem and production.pem

<?php
namespace App\PushNotification;
class Apns
{
static function sendPush($deviceToken, $message, $type = '', $contentId = -1) {
// check if is not empty string
if (!isset($deviceToken) || strlen($deviceToken) == 0) {
return;
}
$passphrase = env('IOS_PASSPHRASE');
$enviroment = env('IOS_ENV', 'development');
$certLocation = storage_path('apns_certs/'. $enviroment .'.pem');
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $certLocation);
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
$gateway = $enviroment == 'development' ? 'ssl://gateway.sandbox.push.apple.com:2195' : 'ssl://gateway.push.apple.com:2195';
$fp = stream_socket_client(
$gateway,
$err,
$errstr,
60,
STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT,
$ctx
);
if (!$fp)
{
\Log::error('Failed to connect: ' . $err . $errstr);
}
else {
\Log::info('Connected to APNS');
// Create the payload body with custom data
$body = [
'aps' => [
'alert' => $message,
],
'type' => $type,
'id' => $contentId
];
// proceed to send
try {
// Encode the payload as JSON
$payload = json_encode($body);
// 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));
if (!$result) {
\Log::info('APNS message not delivered');
}
else {
\Log::info('APNS message successfully sent at '. date('Y-m-d h:i A') . ' for token ' . $deviceToken);
}
} catch (\Exception $ex) {
\Log::error($ex->getMessage() . ' for token ' . $deviceToken);
}
}
// Close the connection to the server
fclose($fp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment