Search code examples
phpiosapple-push-notificationsapns-php

PHP iOS push notifications (APNS)


I am using PHP to try to send a push notification to my iOS app. My push code looks like this:

<?php
 
 $title="Notification";
 $message=array();
 $message['text']="Message";
 $message['id']=1;
 $to='695D55573361DB9948D09AB43EA1548A9AAECB4D23F7D836BD7F88FA94ABBE5E';
 echo $to.PHP_EOL;
 sendPushAPN($to,$title,$message);

 function sendPushAPN($to,$title,$message)
 {
     $to=str_replace(" ","",$to);
     // Put your device token here (without spaces):
     $deviceToken=$to;

     // Put your private key's passphrase here:
     $passphrase = 'abc';

     $ctx = stream_context_create();
     stream_context_set_option($ctx, 'ssl', 'local_cert', 'aps.pem');

     stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
     // Open a connection to the APNS server
     
     $fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $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
     // codi existent //$body['aps'] = array('alert' => "ole.. alex",'sound'=> 'default','push_type' => 'alert');
     $body['aps']=array('alert' => array('title' => 'Notificacion','body' => 'Ok Alex'),'sound' => 'default');
     $payload = json_encode($body);
     // Build the binary notification
     $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
     // $msg = pack("C", 1) . pack("N","alert") . pack("N",$deviceToken) . pack("N", $apple_expiry) . pack("n", 32) . pack('H*', str_replace(' ', '', $deviceToken'])) . pack("n", strlen($payload)) . $payload;


     // Send it to the server
     $result = fwrite($fp, $msg, strlen($msg));
     // Close the connection to the server
     fclose($fp);
     echo 'Result:' . $result . PHP_EOL;
 }
?>

But my output always looks the same:

Connected to APNS Result:114

and the push notification never arrives. What does 114 code mean? Is there any way to get more information about what is going on? Or perhaps I'm just using a wrong way of sending push notifications?


Solution

  • Your code is using the legacy binary API for APNS.

    This is no longer supported.

    You need to use the HTTP/2 API.

    A quick web search seems to indicate that there are a few different PHP libraries that can provide this as well as sample code.