简体   繁体   中英

Server error on iOS push notification

I am trying to use Push Notification for iOS using php .

What can cause the code below to throw an Internal Server Error while calling stream_socket_client method?

public function actionTest()
{
    $deviceToken = '5e9f48100d1584e5f6d9dd4b68f4007d862f2fab6586a4886ab9a213db8d6462';

    // Passphrase for the private key (ck.pem file)
    $passphrase = 'pass1234';
    // Get the parameters from http get or from command line
    $message = 'Notification text';
    $badge = 1;
    $sound = 'default';

    // Construct the notification payload
    $body = array();
    $body['aps'] = array('alert' => $message);

    if ($badge)
        $body['aps']['badge'] = $badge;
    if ($sound)
        $body['aps']['sound'] = $sound;

    // End of Configurable Items 
    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl','local_cert', 'ck.pem');

    // assume the private key passphase was removed.
    stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

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

    $payload = json_encode($body);
    $msg = chr(0).pack('n',32).pack('H*', str_replace(' ', '',
               $deviceToken)).pack('n',strlen($payload)).$payload;
    print "" . $payload . "\n";
    fwrite($fp, $msg);
    fclose($fp);  
}

Here is an demo, please check it:

<?php

// Put your device token here (without spaces):
$deviceToken = '36987fdsf797sdf9797dsf979df7979dsf7';

$message = 'My new push notification 555! Titans';

////////////////////////////////////////////////////////////////////////////////

$ctx = stream_context_create();

    stream_context_set_option($ctx, 'ssl', 'local_cert', 'YourPemFileName.pem');


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

    echo $fp . "\n";
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',
    'type' => 'ReceivedMessage',
    );

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM