推送通知没有失败但没有被发送

时间:2014-06-26 13:44:25

标签: php ios arrays apple-push-notifications

我已经设置了一个脚本来发送多个推送通知。我从应用程序中使用POST方法调用以下PHP,目的是让它为每个deviceToken发送一次消息,因此我将deviceTokens全部放在脚本的数组中。我让它打印deviceToken所以我可以确认它是正确的(它是)和运行脚本时的反馈说成功连接到APNS,但我从来没有收到它。这里看错了吗?

    <?php

 $deviceToken = $_POST['iostoken'];
 $deviceToken2 = $_POST['iostoken2'];
 $devices = Array();
 $devices[0] = Array();
$devices[0]["deviceToken"] = $deviceToken;
$devices[1] = Array();
$devices[1]["deviceToken"] = $deviceToken2;

$passphrase = 'passphrase';

// Put your alert message here:
$message = 'Test message';

////////////////////////////////////////////////////////////////////////////////
foreach($devices as $device){
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

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

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

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

// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $devices["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);
}
?>

1 个答案:

答案 0 :(得分:1)

您可以简化以下行

$deviceToken = $_POST['iostoken'];
$deviceToken2 = $_POST['iostoken2'];
$devices = Array();
$devices[0] = Array();
$devices[0]["deviceToken"] = $deviceToken;
$devices[1] = Array();
$devices[1]["deviceToken"] = $deviceToken2;

$devices = array($_POST['iostoken'], $_POST['iostoken2']);

然后你的循环中出现错误,在播放加载时,你应该使用device而不是devices

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