iOS推送通知上的服务器错误

时间:2016-11-24 11:20:13

标签: php ios

我正在尝试使用 php 来使用针对iOS的推送通知。

在调用 stream_socket_client 方法时,导致以下代码抛出内部服务器错误的原因是什么?

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

1 个答案:

答案 0 :(得分:3)

这是一个演示,请检查一下:

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