diff --git a/api/DtkClient.php b/api/DtkClient.php index 2abd8f09aa71ac7e8c148fe7bf724c05571c43a4..eee31982eeed23e97c205ad2d91c3d56ba1b8a85 100644 --- a/api/DtkClient.php +++ b/api/DtkClient.php @@ -101,6 +101,88 @@ class DtkClient return $this; } + /** + * 执行请求 + * @param $method string HTTP方法名 + * @param $url string 请求的URL + * @param $params array 参数 + * @return bool|string + */ + public function doRequest($method, $url, $params) + { + if ($url == '' || $this->appKey == '' || $this->appSecret == '' || $this->version == '') { + return json_encode(array('code'=>10001,'msg'=>"请完善参数")); + } + + $type = strtoupper($method); + if(!in_array($type, array("GET", "POST"))) { + return json_encode(array('code'=>10001,'msg'=>"只支持GET/POST请求")); + } + + //毫秒级时间戳 + list($msec, $sec) = explode(' ', microtime()); + $timer = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000); + + //6位随机数 + $nonce = rand(100000, 999999); + + //默认必传参数 + $data = [ + 'appKey' => $this->appKey, + 'version' => $this->version, + 'timer' => $timer, + 'nonce' => $nonce, + ]; + + //加密的参数 + if ($params) { + $data = array_merge($params, $data); + } + + $data['signRan'] = self::makeSign($timer, $nonce); + try { + if($type == 'POST') { + //执行请求获取数据 + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + $header = [ + 'Content-Type: application/json', + 'Client-Sdk-Type: php', + ]; + curl_setopt($ch, CURLOPT_HTTPHEADER, $header); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); + $output = curl_exec($ch); + $a = curl_error($ch); + if(!empty($a)){ + return json_encode(array('code'=>10003, 'msg'=>$a)); + } + curl_close($ch); + return $output; + }else{ + //拼接请求地址 + $url = $url . '?' . http_build_query($data); + //执行请求获取数据 + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); + curl_setopt($ch, CURLOPT_HEADER, 0); + $output = curl_exec($ch); + $a = curl_error($ch); + if(!empty($a)){ + return json_encode(array('code'=>10003, 'msg'=>$a)); + } + curl_close($ch); + return $output; + } + }catch (Exception $e){ + return json_encode(array('code'=>10002,'msg'=>"请求超时或异常,请重试")); + } + } + /** * 接口调用 * @return bool|string