注意:【保证生成证书有效】【开发和生产两个不同证书】【证书有效期1年】
<?php
header("Content-type:text/html;charset=utf-8");
$redis = new message_list('send_sms');
if ($redis -> connect() === TRUE){
$size = $redis -> size();
if ($size > 0){
//获取推送消息
//token1,token2....tokenN 对应用户
$message = $redis -> lpop();
$devices = explode(',',$message);
$news = send_news();
$passphrase = '123456';
$ctx = stream_context_create();
//生产
stream_context_set_option($ctx, 'ssl', 'local_cert', 'productionck.pem');//生产
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
//测试
//stream_context_set_option($ctx, 'ssl', 'local_cert', 'developmentck.pem');//测试
//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);
if (!$fp){
exit("Failed to connect: $err $errstr");
}
echo 'Connected to APNS<br/>';
$body = array('aps'=>array('alert'=>$news['title'], 'id'=>$news['id'], 'sound' => 'default'));
//$body = array('aps'=>array('alert'=>'斯柯达晶锐小改款谍照曝光 今年6月上市', 'id'=>804725, 'sound' => 'default'));
$payload = json_encode($body);
foreach($devices as $key=>$val){
$deviceToken = $val;
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$start1 = microtime();
$result = fwrite($fp, $msg, strlen($msg));
//通过$result判读推送是否成功
//echo '<br />'.$result;
}
fclose($fp);
}
$redis -> close();
}
//获取新闻
function send_news(){
return $news;
}