I am trying to implement Apple Push Notification using php code. Here's my code
$deviceToken = 'My device token';
$passphrase = '';
$message = 'My first push notification!';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'apns-dev-cert.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 120, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
fclose($fp);
The certificate .pem file is in the same directory as the file is. This code is running fine on my local machine. I am using MAMP. I am getting notification on my devices.
But when I am trying it on the server, it is not working and giving an error.
Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection refused) in /home/nextgen/public_html/ApplicationGenerator/appointmentportal/iosapp/SimplePush/simplepush.php on line 14 Failed to connect: 111 Connection refused
If the certificate file is wrong, how would it work on my local server?
I am not getting any way out of this. Can you guys help me?
Assuming your server has the right ports open, "Connection Refused" usually hints at an invalid .PEM file or an incorrect passphrase. Make sure that when you open the .PEM file, the header looks something like this :
subject=/UID=com.yourapp.app/CN=Apple Development IOS Push Services: com.yourapp.app/C=FR issuer=/C=US/O=Apple Inc./OU=Apple Worldwide Developer Relations/CN=Apple Worldwide Developer Relations Certification Authority
followed by a key which should then be followed by a header that looks like this for your private key :
I suggest you also remove the passphrase to reduce the potential error sources.