<?php

declare (strict_types=1);
namespace library\lib;
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  秒验API  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-11-10 13:21
// +----------------------------------------------------------------------
class mobService {

    private $config ;

    private $host = "http://identify.verify.mob.com";

    private  $res;

    public function __construct()
    {
        $this->config = config('mob');
    }


    public function getResult(){
        return $this->res;
    }


    /**
     * run 数据
     * @param $token 服务器token
     * @param $opToken 运营商token
     * @param $operator 运营商类型,[CMCC:中国移动,CUCC:中国联通,CTCC:中国电信]
     */
    public function run($token,$opToken,$operator){
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $this->host."/auth/auth/sdkClientFreeLogin");
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回,而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 0);
        //设置post数据
        $post_data = array(
            "appkey" => $this->config['appkey'],
            "token" => $token,
            "opToken" => $opToken,
            'operator'=> $operator,
            'timestamp'=> $this->getUnixTimestamp()
        );
        if ($this->config['md5'] != '') {
            $post_data['md5'] = $this->config['md5'];
        }
        $post_data['sign'] = $this->getSign($post_data, $this->config['appSecret']);
        $jsonStr = json_encode($post_data);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        $json = json_decode($data);
        if ($json->status == 200) {
            $d = openssl_decrypt($json->res, "DES-CBC", $this->config['appSecret'], 0, "00000000");
            $this->res = json_decode($d, true);
        }
    }



    function getSign($data, $secret) {
        ksort($data);
        $str = '';
        foreach ($data as $k => $v ) {
            $str .= "$k=$v&";
        }
        $str = substr($str, 0, -1);
        return md5($str.$secret);
    }

    function getUnixTimestamp ()
    {
        list($s1, $s2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($s1) + floatval($s2)) * 1000);
    }

}