Last active
May 24, 2023 22:56
-
-
Save manjeshpv/d5b8e271af94824836d9 to your computer and use it in GitHub Desktop.
Apple Push Notification APNS PHP Snippet - Server Side Implementation
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 | |
$deviceToken = '6e1326c0e4758b54332fab3b3cb2f9ed92e2cd332e9ba8182f49027054b64d29'; // iPad 5s Gold prod | |
$passphrase = ''; | |
$message = 'Hello Push Notification'; | |
$ctx = stream_context_create(); | |
stream_context_set_option($ctx, 'ssl', 'local_cert', 'pushcert.pem'); // Pem file to generated // openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts // .p12 private key generated from Apple Developer Account | |
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); | |
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); // production | |
// $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); // developement | |
echo "<p>Connection Open</p>"; | |
if(!$fp){ | |
echo "<p>Failed to connect!<br />Error Number: " . $err . " <br />Code: " . $errstrn . "</p>"; | |
return; | |
} else { | |
echo "<p>Sending notification!</p>"; | |
} | |
$body['aps'] = array('alert' => $message,'sound' => 'default','extra1'=>'10','extra2'=>'value'); | |
$payload = json_encode($body); | |
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; | |
//var_dump($msg) | |
$result = fwrite($fp, $msg, strlen($msg)); | |
if (!$result) | |
echo '<p>Message not delivered ' . PHP_EOL . '!</p>'; | |
else | |
echo '<p>Message successfully delivered ' . PHP_EOL . '!</p>'; | |
fclose($fp); | |
?> |
Note that this will not work after March 31 2021 ... https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns
Here's a good article ... https://dev.to/samauto/connect-to-apns-via-http-2-with-php-57oj
gateway.push.apple.com:2195 won't work anymore
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you. Simple, concise and works!