This script used to send test push notifications to test devices before Apple made the switch to the new APNs Provider API, which I'm surprised more people aren't talking about.
Now when I run the script from the terminal typing and entering php simplepush.php
, the output says
Though no message is received.
//simplepush.php
<?php
// Put your device token here (without spaces):
$deviceToken = 'EXAMPLETOKEN';
// Put your private key's passphrase here:
$passphrase = 'pushchat';
// Put your alert message here:
$message = 'Hello!';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://api.sandbox.push.apple.com:443', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
// 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)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
Since Apple made the switch last March, I have:
- Created a new Certificate Signing Request
- Registered a new App ID
- Established a Certificate-Based Connection to APNs
- Obtained a new Provider Certificate from Apple
- Installed the Certificate and Private Key
- Established Trust with APNs
- Sent Push Notifications Using Command-Line Tools
And I am able to get a test notification when I follow Sending Push Notifications Using Command-Line Tools.
curl -v --header 'apns-topic: com.your.site' --header apns-push-type: alert --cert aps.cer --cert-type DER --key PushChatKey.pem --key-type PEM --data '{"aps":{"alert":"Test"}}' --http2 https://api.sandbox.push.apple.com/3/device/DEVICETOKEN
Is it possible to still use this php script to send test push notifications since apple made the change to the new APNs Provider API? I know that the Apple developer documentation mentions required header request fields but I honestly can't tell if those are to be implemented from the terminal or from directly within the script.