<?php
namespace onlogin;

class Onlogin
{
    private $secretid;
    private $secretkey;
    private $businessid;
    private $api_url = "https://ye.dun.163yun.com/v1/oneclick/check";
    private $version = "v1";
    private $api_timeout = 5;
    private $internal_string_charset = "auto";

    /**
     * 构造函数
     * @param $sessionKey string 用户在小程序登录后获取的会话密钥
     * @param $appid string 小程序的appid
     */
    public function __construct($secretid, $secretkey, $businessid)
    {
        $this->secretid = $secretid;
        $this->secretkey = $secretkey;
        $this->businessid = $businessid;
        $this->api_url = "https://ye.dun.163yun.com/v1/oneclick/check";
        $this->version = "v1";
        $this->api_timeout = 5;
        $this->internal_string_charset = "auto";
    }

    /**
     * 计算参数签名
     * $params 请求参数
     * $secretKey secretKey
     */

    function gen_signature($secretKey, $params)
    {
        ksort($params);
        $buff = "";
        foreach ($params as $key => $value) {
            if ($value !== null) {
                $buff .= $key;
                $buff .= $value;
            }
        }
        $buff .= $secretKey;
        return md5($buff);
    }
    /**
     * 将输入数据的编码统一转换成utf8
     * @params 输入的参数
     */
    function toUtf8($params)
    {
        $utf8s = array();
        foreach ($params as $key => $value) {
            $utf8s[$key] = is_string($value) ? mb_convert_encoding($value, "utf8", $this->internal_string_charset) : $value;
        }
        return $utf8s;
    }
    /**
     * 易盾本机验证在线检测请求接口简单封装
     * $params 请求参数
     */
    function check($params)
    {
        $params["secretId"] = $this->secretid;
        $params["businessId"] = $this->businessid;
        $params["version"] = $this->version;
        $params["timestamp"] = sprintf("%d", round(microtime(true) * 1000));
        // time in milliseconds
        $params["nonce"] = substr(md5(time()), 0, 32);
        // random int
        $params = $this->toUtf8($params);
        $params["signature"] = $this->gen_signature($this->secretkey, $params);
        $options = array('http' => array(
            'header' => "Content-type: application/x-www-form-urlencoded\r\n",
            'method' => 'POST',
            'timeout' => $this->api_timeout,
            // read timeout in seconds
            'content' => http_build_query($params)
        ));
        $context = stream_context_create($options);
        $result = file_get_contents($this->api_url, false, $context);
        if ($result === FALSE) {
            return array("code" => 500, "msg" => "file_get_contents failed.");
        } else {
            return json_decode($result, true);
        }
    }

}

