Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Sending Push Notifications Failed to connect: 111 Connection refused

I am trying to setup push notifications, I got my certificates from apple developer, unabled pushed notifications on my ios app and I have a PHP script that is suppose to send a push notification. My hosting provider whitelisted the port 2195 outbound for my account. But push notifications are still not working, I get this error

Failed to connect: 111 Connection refused

I am using Development Certificates and they are enabled in my apple developer account.

<?php 

class PushNotifications {

    private static $passphrase = 'PASSPHRASE';

    public function iOS($data, $devicetoken) {

        $deviceToken = $devicetoken;

        $ctx = stream_context_create();

        stream_context_set_option($ctx, 'ssl', 'local_cert', 'Certificates.pem');
        stream_context_set_option($ctx, 'ssl', 'passphrase', self::$passphrase);

        $fp = stream_socket_client(
            'ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

        if (!$fp)
        {
            exit("Failed to connect: $err $errstr" . PHP_EOL);
        }

        $body['aps'] = array('alert' => array('title' => $data['mtitle'], 'body' => $data['mdesc'],),'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));

        fclose($fp);

        if (!$result)
            return 'Message not delivered' . PHP_EOL;
        else
            return 'Message successfully delivered' . PHP_EOL;

    }

    private function useCurl(&$model, $url, $headers, $fields = null) {

        $ch = curl_init();
        if ($url) {
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            if ($fields) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
            }
            $result = curl_exec($ch);
            if ($result === FALSE) {
                die('Curl failed: ' . curl_error($ch));
            }

            curl_close($ch);

            return $result;
        }
    }

}
?>

Can anyone help?

like image 866
user979331 Avatar asked Aug 25 '18 07:08

user979331


1 Answers

Make sure you're not still getting blocked (run this from your php host):

telnet gateway.sandbox.push.apple.com 2195

If that gets a connection refused, then the problem is still with your hosting provider or someone between you and APNS.

Or this, if you don't have shell access:

fsockopen('gateway.sandbox.push-apple.com.akadns.net', 2195);
like image 194
Brett Avatar answered Nov 05 '22 08:11

Brett