<?php
/**
 * 极光推送
 * @param https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/ 相关文档参考
 */
 namespace Common\Vendor\Push;
class Jpush{
    private $app_key;
    private $master_secret;
    private $url = "https://api.jpush.cn/v3/push";      //推送的地址
    /**
     * 初始化
     * @param $app_id 极光配置ID
     * @param $app_key 推送配置
     * @param $master_secret 推送配置
     * @param $url 推送的地址
     */
    public function __construct($config=array()) {
        $app_id=$config['app_id'];
        $app_key=$config['app_key'];
        $master_secret=$config['master_secret'];
        if(empty($app_key) || empty($master_secret)){
            if(empty($app_id))$app_id=1;
            $pushset = M('PushSet')->where('id='.$app_id)->field('appkey,master_secret')->cache(true)->find();
		    $app_key = $pushset['appkey'];
		    $master_secret = $pushset['master_secret'];
        }
        if ($app_key) $this->app_key = $app_key; //待发送的应用程序(appKey)，只能填一个。
        if ($master_secret) $this->master_secret = $master_secret;//主密码
        if ($url) $this->url = $url;
    }
    /**
     * 推送主体方法
     * @param $receiver='all' 目标用户 all 或具体id
     * @param $content='' 推送内容
     * @param $sendtype='all' 发送通知或消息 all 全部 notify 通知  message消息
     * @param array $platform='all' 目标用户终端手机的平台类型 all 全部 android,ios,winphone
     * @param $param=array() 推送参数
     * @param $m_time 离线时间
     */
    public function push($receiver='all',$content='',$param=array(),$sendtype='all',$platform='all',$m_time=86400){
        $return =array('status'=>0,'info'=>'');
        $m_time=intval($m_time);if(empty($m_time))$m_time = 86400;//离线保留时间
        $message="";//存储推送状态
        $base64=base64_encode("$this->app_key:$this->master_secret");
        $header=array("Authorization:Basic $base64","Content-Type:application/json");
        if(!is_array($receiver)){
            $receiver_arr=array();
            $receiver_arr["registration_id"]=explode(',',$receiver);
            $receiver=$receiver_arr;
        }
        $data = array();
        $data['platform'] = $platform;
        $data['audience'] = $receiver;      //目标用户
        if($sendtype=='all' || $sendtype=='notify'){//通知
            $data['notification'] = array("alert"=>$content,//通知内容体。是被推送到客户端的内容                    
                "android"=>array("alert"=>$content,"title"=>"","builder_id"=>1,"extras"=>$param),//安卓自定义
                "ios"    =>array("alert"=>$content,"badge"=>"1","sound"=>"default","extras"=>$param));//ios 自定义
        }
        if($sendtype=='all' || $sendtype=='message'){//消息
            $data['message'] = array("msg_content"=>$content,"extras"=>$param);
        }
        //附加选项
        $data['options'] = array("sendno"=>NOW_TIME,"time_to_live"=>$m_time, //保存离线时间的秒数默认为一天
             "apns_production"=>true,); //布尔类型   指定 APNS 通知发送环境：0开发环境，1生产环境。或者传递false和true        
        $param = json_encode($data);
        $result = $this->push_curl($param,$header);
        if($result){
            $res_arr = json_decode($result, true);
            if(isset($res_arr['error'])){                       //如果返回了error则证明失败
                if($res_arr['error']['message']){$return['info'] = $res_arr['error']['message']; return $return;}//错误信息
                $message=$this->errorcode($res_arr['error']['code']);//错误码
            }else{
                $message="发送成功！";
				$return['status'] = 1;
            }
        }else{      
            $message='接口调用失败或无响应';
        }
        $return['info']= '推送信息'.$message;
		return $return;
    }
    private function errorcode($code){
        $message='';
        $error=array(
            '200'=>'发送成功！',
            '1000'=>'失败(系统内部错误',
            '1001'=>'失败(只支持 HTTP Post 方法，不支持 Get 方法',
            '1002'=>'失败(缺少了必须的参数)',
            '1003'=>'失败(参数值不合法)',
            '1004'=>'失败(验证失败)',
            '1005'=>'失败(消息体太大)',
            '1008'=>'失败(appkey参数非法)',
            '1020'=>'失败(只支持 HTTPS 请求)',
            '1030'=>'失败(内部服务超时)',
        );
        if($code){
            $message=$error[$code];
        }
        if(empty($message))$message='失败(返回其他状态，目前不清楚额，请联系开发人员！)';
        return $message;
    }
    //推送的Curl方法
    public function push_curl($param="",$header="") {
        if (empty($param)) { return false; }
        $postUrl = $this->url;
        $curlPost = $param;
        $ch = curl_init();                                      //初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);                 //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);                    //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);                      //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);           // 增加 HTTP Header（头）里的字段
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);        // 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);                                 //运行curl
        curl_close($ch);
        return $data;
    }
}
?>