从PHP发送iOS推送通知

时间:2014-01-20 15:11:40

标签: php ios notifications

我正在使用iOS推送通知的iOS应用。我想从我的服务器上的PHP脚本发送通知。我的应用程序中的代码非常适合注册远程通知并接收它们。我使用这个PHP脚本发送通知,它也运行良好:

<?php

// My device token here (without spaces):
$deviceToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

// My private key's passphrase here:
$passphrase = 'myPrivateKey';

// My alert message here:
$message = 'New Push Notification!';

//badge
$badge = 1;

$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.sandbox.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,
    'badge' => $badge,
    'sound' => 'newMessage.wav'
);

// 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 'Error, notification not sent' . PHP_EOL;
else
    echo 'notification sent!' . PHP_EOL;

// Close the connection to the server
fclose($fp);

我的问题是,如果我在我的imac上通过终端运行这个脚本,一切正常并发送通知,但如果我在我的服务器上传它不起作用。我的证书有效,并且位于脚本的同一文件夹中。当我尝试在服务器上运行脚本时,我添加此行以包含证书文件并使用变量$ cerificate:

$certificate = file_get_contents('ck.pem');

这是php服务器端的错误:

Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out) in script.php on line 29
Failed to connect: 110 Connection timed out

为什么会这样?我是否必须在服务器上添加一些内容才能启用平板电脑连接?

-----更新问题-----

我的第一个问题是我没有权限在端口2195上发送连接并在端口2196上接收响应。现在,我的服务器管理员启用了这些连接,我有不同的错误:

Warning: stream_socket_client() [function.stream-socket-client]: SSL operation failed with code 1. OpenSSL Error messages: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure in script.php on line 28

Warning: stream_socket_client() [function.stream-socket-client]: Failed to enable crypto in script.php on line 28

Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Unknown error) in script.php on line 28

无法连接:0

1 个答案:

答案 0 :(得分:6)

当您使用共享主机时,会发生这种情况,主机提供商不会授予您在端口2195和2196上使用出站连接的权限。您应该使用VPS或使用其他提供商,例如urbanAirship和parse.com。甚至你可以运行自己的本地服务器......为此