当前位置:首页 > 操作系统 > Ios

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

解决方法:

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

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

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!