PHP实现IOS的推送
php做服务端实现IOS推送,没有想象的那么困难,因为苹果实在是太NB了,很多事情它都替开发者已经想到。相比较安卓而言,苹果的推送要简单的多。这里我不会讲具体的实现思路,直接贴可以用的代码好了,因为比较懒。如果以后有空我会将这块补上来。
// Put your device token here (without spaces):
$deviceToken = 'bcf0e0ef9fd812b762347142cee74fb46b797e4972ab1936dd6d17e6bdca75f1';
// Put your private key's passphrase here:
$passphrase = '*****************************';
// Put your alert message here:
$message = '你好啊苹!!';
////////////////////////////////////////////////////////////////////////////////
$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= iconv('GBK','UTF-8',$message),
'sound' => 'default'
);
// 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);
上面有用到一个ck.pem的文件,这是IOS开发者需要申请的一个证书,这个证书很关键,因为针对于不同的语言,适用的证书不一样。所以去申请的时候记得弄正确。然后,将生成好的证书,放在和这个PHP文件同目录下。你就可以测试了,我上面的$deviceToken,$passphrase需要根据你的实际情况修改, deviceToken是对应的发送到哪一台手机上面,passphrase是你开发者的密码。嗯,差不多就是上面这些内容,只要这几个地方不出错,那么你的推送就会完全OK。。
浙公网安备 33010602011771号