Demonick
Demonick

Reputation: 2126

Apple Push notification not being sent

I have generated the .cer file, provision file with the correct device ID, generated the .pem file by combining the .cer and private key files, uploaded it to the server. The app id matches. I have provided the passphrase too, which is correct.

I tested the port and connection using telnet from the server, it connects fine.

I have tested the certificate by openssl command, and it returned 0 - no errors.

The certificates and the application is in development/debug mode, the iPhone is set up to receive notifications, the token is received and is delivered to the server correctly and in the same length - 64.

When sending the message from the server, the error code is 0 - which means no errors.

Here is the code sample from the server:

$options = array('ssl' => array(
  'local_cert' => 'cert.pem',
  'passphrase' => 'pass'
));

$streamContext = stream_context_create();
stream_context_set_option($streamContext, $options);
$apns = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

if ($apns)
{
    $payload['aps'] = array('alert' => 'push test', 'badge' => 1, 'sound' => 'default');
    $payload = json_encode($payload);

    $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $token)) . chr(0) . chr(strlen($payload)) . $payload;
    fwrite($apns, $apnsMessage);

    fclose($apns);
} 
else 
{ 
    echo "Connection failed";
    echo $errorString."<br />";
    echo $error."<br />";
}

What else can I possibly try?

Upvotes: 1

Views: 1101

Answers (1)

Demonick
Demonick

Reputation: 2126

The code that worked in the end is the following:

    $ctx = stream_context_create();

    stream_context_set_option($ctx, 'ssl', 'local_cert', 'pushcert.pem');
    stream_context_set_option($ctx, 'ssl', 'passphrase', 'pass');

    // Create the payload body
    $body['aps'] = array(
    'alert' => array('body' => 'Message', 'action-loc-key' => 'Show'),
    'sound' => 'default'
    );

    // Encode the payload as JSON
    $payload = json_encode($body);

    // Open a connection to the APNS server
    $apns = stream_socket_client(
    'ssl://gateway.sandbox.push.apple.com:2195', $err,
    $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

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

    echo 'Connected to APNS' . PHP_EOL;

    $imsg = chr(0) . pack('n', 32) . pack('H*', $message) . pack('n', strlen($payload)) . $payload;

            // Send it to the server
    $res = fwrite($apns, $imsg, strlen($imsg));

    if (!$res)
    {
        echo 'Message not delivered' . PHP_EOL;
    }
    else
    {
        echo 'Message successfully delivered' . PHP_EOL;
    }
    fclose($apns);

Upvotes: 1

Related Questions