IOS APNS推送php接口

<?php
if(strtoupper($_SERVER['REQUEST_METHOD']) != 'GET'){
    exit(json_encode([
        'code' => 0,
        'msg' => '错误请求'
    ]));
}

if(!isset($_GET['device_token'])){
    exit(json_encode([
        'code' => 0,
        'msg' => '设备信息缺失'
    ]));
}

if(!isset($_GET['message'])){
    exit(json_encode([
        'code' => 0,
        'msg' => '推送信息缺失'
    ]));
}

if(strlen($_GET['message']) > 256){
    exit(json_encode([
        'code' => 0,
        'msg' => '推送信息长度超过256个字符'
    ]));
}

if(!isset($_GET['app_id'])){
    exit(json_encode([
        'code' => 0,
        'msg' => 'appId缺失'
    ]));
}

$apps = [
    '101' => [
        'cert' => './cert/1.pem',//ios生成的pem,
        'password' => '1',//pem密码
        'debug' => '1',//开发模式 1  生产模式0
    ]
];

if(!array_key_exists($_GET['app_id'], $apps)){
    exit(json_encode([
        'code' => 0,
        'msg' => 'appId错误'
    ]));
}


$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $apps[$_GET['app_id']]['cert']);
stream_context_set_option($ctx, 'ssl', 'passphrase', $apps[$_GET['app_id']]['password']);

// Open a connection to the APNS server
if($apps[$_GET['app_id']]['debug']){
    $fp = stream_socket_client(
        'ssl://gateway.sandbox.push.apple.com:2195', $err,
        $err_str, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
}else{
    $fp = stream_socket_client(
        'ssl://gateway.push.apple.com:2195', $err,
        $err_str, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
}

if (!$fp){
    exit(json_encode([
        'code' => 0,
        'msg' => '连接APN服务器失败,错误码:'.$err.',错误信息:'.$err_str
    ]));
}

$body['aps'] = array(
    'alert' => $_GET['message'],
    'sound' => 'default'
);
$payload = json_encode($body);

// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $_GET['device_token']) . pack('n', strlen($payload)) . $payload;

// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
fclose($fp);
if(!$result){
    exit(json_encode([
        'code' => 0,
        'msg' => '推送消息发送失败,信息:'.$result
    ]));
}else{
    exit(json_encode([
        'code' => 1,
        'msg' => '推送消息发送成功,信息:'.$result
    ]));
}

pem生成策略见: http://my.oschina.net/u/2340880/blog/413584

转载于:https://my.oschina.net/u/232595/blog/604192

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值