Make sure to add .pem cert in storage/apns_certs/ with file name development.pem and production.pem
Last active
August 11, 2019 04:10
-
-
Save afiqiqmal/c305c9ef3a97f975ec63aa13ee2216a5 to your computer and use it in GitHub Desktop.
Sample of APNS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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