php 苹果推送消息推送,苹果消息推送 PHP 代码备忘

define("SYSDEBUG",true);

define("APPPATH","/pathto/appdir/");

class m_ios_notification {

private $_connection = array();

private $_connection_i = array();

private static $int = null;

private static $timeout = 60;

private static $maxtips = 100;

private function __construct() {

}

function __destruct() {

foreach ($this->_connection as $conn){

if($conn){

fclose($conn);

}

}

}

static function i() {

if(self::$int === null){

self::$int = new m_ios_notification();

}

return self::$int;

return new m_ios_notification();

}

private function get_conn($bid,$feedback=false) {

$SYSDEBUG = SYSDEBUG;

$k = md5("{$bid}|{$feedback}");

if($this->_connection_i[$k]++ >= self::$maxtips){

$this->_connection_i[$k] = 0;

fclose($this->_connection[$k]);

$this->_connection[$k] = null;

}

if(!$this->_connection[$k]){

$pempath = !$SYSDEBUG ? $bid : "{$bid}_debug";

$pempath = APPPATH ."pem/" .$pempath . ".pem";

if(!is_file($pempath)){

return false;

}

$ctx = stream_context_create();

stream_context_set_option($ctx, 'ssl', 'local_cert', $pempath);

if($feedback){

stream_context_set_option($ctx, 'ssl', 'verify_peer', false);

$url = !$SYSDEBUG ? 'ssl://feedback.push.apple.com:2196' : 'ssl://feedback.sandbox.push.apple.com:2196';

} else {

$url = !$SYSDEBUG ? 'ssl://gateway.push.apple.com:2195' : 'ssl://gateway.sandbox.push.apple.com:2195';

}

$this->_connection[$k] = stream_socket_client($url, $err, $errstr, self::$timeout, STREAM_CLIENT_CONNECT, $ctx);

if(!$this->_connection[$k]){

throw new Exception("Failed to connect |$err |$errstr |$url |$pempath");

}

}

return $this->_connection[$k];

}

function send_msg($token,$message,$bundleid) {

if(!$token || !$message || !$bundleid){

return -1;

}

$body = array();

$body['aps'] = array(

'alert' => $message,

'badge' => 1,

'sound' => 'b'

);

$body = json_encode($body);

$bodylen = strlen($body);

if($bodylen > 256){

return -2;

}

$msg = chr(0) . pack("n", 32) . pack('H*', $token) . pack("n", $bodylen) . $body;

try {

$conn = $this->get_conn($bundleid);

if(!$conn) {

return -3;

}

} catch (Exception $exc) {

return "-3 -> ".$exc->getMessage();

}

return fwrite($conn, $msg);

}

function get_feedback($bundleid) {

if(!$bundleid || !($conn = $this->get_conn($bundleid, true))){

return false;

}

$list = array();

while(($con = fread($conn,38))){

if(strlen($con)!=38){

continue;

}

$list[] = bin2hex(substr($con, 6,32));

}

return $list;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值