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0+t3AAzpKPO7wZEGP8ppLLpPbXUdFjlbwKUaKqAZUrEH1GwSezTdLI2Ylz/uqeCQKBgQCGmtuaw0ZgS6rIFvWM88mRyExWuzZrQDKmIMskBmTS1Vp+dpRtoOoSX7K7rMQPA46sGsu1l31iX1Zl9YTfNdYz9HrlkdKBwvJwd0VYiXtS2qZVEQUwWEoubJqm7RpUjJCXByeH2akzsjrrRl2PM36QMLYG5u9Fb5ipaA2mxlBcrQKBgEnfUOXly8Awa5Jq/ZRs2nbWDyJGkPH+ARo+U/QQh4uz66Omr6yJUbRxRyjIkpdJ7sIN6MB9v/PQ1NZVn5Z1vyNwn/yblv4Y8gjx7sDtgDgKw0PiMvIWMoae12/Vc+BeHXDFskN+qiYYQnoNem10m2NnDTiQN8qXZcOIpFkrAyHJAoGATpY+pqYamwN0NXYbrB9b1HvNGqRp8uptc2agf7AA0FPeH/M620uVx02mL70ypC9b3iGozQM+YS913JQGISeOHot9auqtaYoX15p8BqK9yP15v0bn1EdLebF0YZ04oC39nx8siEnwRHvfynogUAIMeZR/16YiIoGQKazaaH0H0Qk=';
    protected $url = 'https://gss-cn.game.hicloud.com/gameservice/api/gbClientApi';
    private $_appid = 100440289;
    private $_cpid = '890086000102155510';

    /**
     * 验证该用户信息的合法性
     * @param $data
     * @return string
     */
	public function validateHW($data)
    {
        if(empty($data)) {
            return [];
        }

        $param['method'] = 'external.hms.gs.checkPlayerSign';
        $param['appId'] = $this->_appid;
        $param['cpId'] = $this->_cpid;
        $param['ts'] = $data['ts'];
        $param['playerId'] = $data['playerId'];
        $param['playerLevel'] = $data['playerLevel'];
        $playerSSign = $data['playerSSign'];
        $playerSSign = str_replace('\\', '', $playerSSign);
        $playerSSign = str_replace(' ', '+', $playerSSign);
        $param['playerSSign'] = $playerSSign;

        $urlParam = $this->dealUrlParam($param);
        $signature = $this->sign($urlParam);

        if(empty($signature)) {
            oo::logs()->debug3('生成签名 signature:'.$signature.'  urlParam:'.$urlParam, 'hwosVerifyFail.php');
            return [];
        }
        $param['cpSign'] = $signature;
        $res = oo::functions()->curl($this->url, $param);
        $rtnCode = $res['rtnCode'] ?? -1;
        if($rtnCode !== 0){
            oo::logs()->debug3('登录验证不通过：'.json_encode($res).' data:'.json_encode($param), 'hwosVerifyFail.php');
            return [];
        }
        //验签
        $paramRet = $res;
        $rtnSign = $res['rtnSign'];
        unset($paramRet['rtnSign']);
        $retParam = $this->dealUrlParam($paramRet);
        $retSignature = $this->sign($retParam);
        if($retSignature != $rtnSign){
            oo::logs()->debug3('登录验证不通过：retSign:'.json_encode($retSignature).' rtnSign:'.json_encode($rtnSign), 'hwosVerifyFail.php');
            return [];
        }

        return $data;
    }




    public function hwcurl($url, $postData)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        $data = curl_exec($curl);
        curl_close($curl);
        return json_decode($data, 1);
    }

    private function sign($sign, $algo = 'SHA256')
    {
        $key = "-----BEGIN PRIVATE KEY-----\n".chunk_split( $this->_privateKey, 64, "\n" ).'-----END PRIVATE KEY-----';
        $key = openssl_pkey_get_private( $key );

        if ( empty( $key ) )
        {
            return 'Please pass a Base64-encoded private key from the Market portal';
        }
        $signature = '';
        openssl_sign($sign, $signature, $key, $algo);
        $sign = base64_encode($signature);
        return $sign;
    }


    /**
     * 对参数进行处理
     * @param $data
     * @return string
     */
    private function dealUrlParam($data)
    {
        $urlParam = '';
        //按ascii码升序排列
        ksort($data);
        foreach ($data as $key => $v) {
//            if(empty($v)) {
//                continue;
//            }
            $v = urlencode($v);
            $urlParam .= '&'.$key .'='.$v;
        }
        $urlParam = ltrim($urlParam, '&');
        return $urlParam;
    }

    /**
     * 使用RSA算法  SHA1WithRSA进行签名  --取消（SHA256WithRSA）
     * @param $data
     * @return string
     */
	protected function verify($data, $signature)
    {
        $key = "-----BEGIN PUBLIC KEY-----\n".chunk_split( $this->_publicKey, 64, "\n" ).'-----END PUBLIC KEY-----';
        $key = openssl_get_publickey( $key );

        if ( empty( $key ) )
        {
            return 'Please pass a Base64-encoded public key from the Market portal';
        }
        $signature = str_replace('\\', '', $signature);
        $signature = str_replace(' ', '+', $signature);
        $result = openssl_verify( $data, base64_decode( $signature ), $key, OPENSSL_ALGO_SHA1 );

        if ( 0 === $result )
        {
            oo::logs()->debug3('openssl error string:'.openssl_error_string()."\n".' 验签的参数:'.$data."\n".'  验签的signature:'.$signature, 'hw_verify.php');
            return 'fail to verify';
        }
        else if ( 1 !== $result )
        {
            return 'Unknown error verifying the signature in openssl_verify '.$result;
        }

        return '';
    }




}