<?php
namespace OPush;
class Application
{
    private $appid;
    private $appkey;
    private $appsecret;
    private $appserversecret;
    private $url = "https://api.push.oppomobile.com/";

    public function __construct()
    {
        $this->appid = \pushConfig::OP_APP_ID;
        $this->appkey = \pushConfig::OP_APP_KEY;
        $this->appsecret = \pushConfig::OP_APP_SECRET;
        $this->appserversecret = \pushConfig::OP_APP_SERVER_SECRET;
    }

    public function get_access_token(){

         $cacheauth = unserialize(file_get_contents(  (dirname(__FILE__)).'/config.txt'));
         if(empty($cacheauth) || ( time() >$cacheauth['expire_time'] )){
             //重新拉取
             $url = $this->url."server/v1/auth";
             $headerArray=array('Content-Type : application/x-www-form-urlencoded');
             $data['app_key'] = $this->appkey;
             $data['timestamp'] = $this->msectime();
             $data['sign'] = hash("sha256",$this->appkey.$data['timestamp'].$this->appserversecret);
             $res = $this->curl_https_post($url,$data,$headerArray);
             $resarr =json_decode($res,true);
             if($resarr['code'] ==0){
                 $in['auth_token'] = $resarr['data']['auth_token'];
                 $in['expire_time'] = time()+86400;
                 file_put_contents(dirname(__FILE__).'/config.txt', serialize($in));
                 return $resarr['data']['auth_token'];

             }else {
                 return false;
             }

         } else {
            return $cacheauth['auth_token'];
         }

    }

    //获取毫秒时间戳
    function msectime(){
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }

    private function curl_https_post($url, $data = array(), $header = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // check verify
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//使返回的字符串不输出到页面中,而是直接返回
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);//尝试连接时等待的秒数
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_POST, 1); // regular post request;这时候Content-type : application/x-www-form-urlencoded;所以header不用设置
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Post submit data,$data其实是string类型的,所以不同的Content-type 要把参数利用json_encode转化或者是http_build_query转化

        $ret = @curl_exec($ch);
        if ($ret === false) {
            return null;
        }
        curl_close($ch);
        return $ret;
    }

    function curl_https__get($url,$headerArray){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output = json_decode($output, true);
    }

    /**
     * 别名推送,单推
     */
    public function pushAlias($content,$title,$alias){
        $url = $this->url."server/v1/message/notification/unicast";
        $header[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
        $header[] = "auth_token: ".$this->get_access_token();

        $data['message'] = json_encode([
            'target_type' =>5,
            'target_value' =>$alias,
            'notification' =>[
                'title' =>$title,
                'content' =>$content
            ]
        ]);

        return  $res = $this->curl_https_post($url,http_build_query($data),$header);

    }



    /**
     * 标签推送
     * @param $title
     * @param $content
     * @param $tag
     * @return bool|string|null
     */

    public function pushTag($title,$content,$tag){
        $url = $this->url."server/v1/message/notification/unicast";
        $header[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
        $header[] = "auth_token: ".$this->get_access_token();
        $data['message'] = json_encode([
            'target_type' =>2,
            'target_value' => $tag,
            'notification' =>[
                'title' =>$title,
                'content'=>$content
            ]
        ]);

       return  $res = $this->curl_https_post($url,http_build_query($data),$header);

    }


    //查询当天的app发送量
    public function getSendNum(){
        $url = "https://feedback.push.oppomobile.com/server/v1/feedback/fetch_push_permit";
        $header[] = "Content-type : application/x-www-form-urlencoded;charset=UFT-8";
        $header[] = "auth_token: ".$this->get_access_token();
        return  $res = $this->curl_https__get($url,$header);

    }





}