mch = $mch; } } public function getApiUrl(): string { // TODO: Implement getApiUrl() method. return $this->api_url; } public function getMethod(string $method): string { // TODO: Implement getMethod() method. return $this->api_list[$method] ?? ''; } public function getFullUrl(string $method): string { // TODO: Implement getFullUrl() method. return $this->getApiUrl() . $this->getMethod($method); } public function getAppId(): string { // TODO: Implement getAppId() method. return $this->mch ? $this->mch->app_id : ''; } public function getAppSecret(): string { // TODO: Implement getAppSecret() method. return $this->mch ? $this->mch->app_secret : ''; } protected function createHeader($data) { return [ 'api-app-id' => $this->getAppId(), 'api-req-id' => uniqid(), 'api-time-stamp' => (string) time(), 'api-sign' => $this->sign($data), ]; } protected function sign($params) { // 2.以key做升序排序 ksort($params); // 3.将key和value按照顺序直接拼接到一起 $str = ''; foreach ($params as $key => $val) { $str .= $key . $val; } // 4.在上一步的结果后直接拼secretKey $str .= $this->getAppSecret(); // 5.对上一步结果进行sha1加密,得到16进制字符串,进行md5加密,结果转为大写 return strtoupper(md5(sha1($str))); } /** * 请求 * @param string $url * @param array $data * @param string $type * @param int $time */ protected function request(string $url, array $data, string $method = "get", array $header = []) { if ($this->mch) { $header = array_merge($header, $this->createHeader($data)); } $res = $this->curl($method, $url, $data, $header); if ($res['code'] != 200) { throw new MiddleException($res['error']); } if (method_exists($this, 'requestHandel')) { return $this->requestHandel($res['content']); } $content = Json::decode($res['content'], true); if ($content['code'] !== 200 || $content['success'] != true) { throw new MiddleException($content['message']); } return $content['data']; } protected function curl($method, $api, $params = [], $headers = []) { if (!$api) { return ['code' => 404, 'error' => 'api is null']; } $client = new Client([ 'timeout' => $headers['timeout'] ?? 5, ]); $method = strtoupper($method); $options = []; $headers['charset'] = $headers['charset'] ?? 'UTF-8'; $options['headers'] = $headers; if ($method == 'GET' && $params) { $options['query'] = $params; } if ($method == 'POST') { $options['headers']['Content-Type'] = $headers['Content-Type'] ?? 'application/json'; if ($options['headers']['Content-Type'] == 'application/json' && $params) { $options['body'] = \GuzzleHttp\json_encode($params ? $params : (object) []); } if ($options['headers']['Content-Type'] == 'application/x-www-form-urlencoded' && $params) { $options['form_params'] = $params; } } try { $request = $client->request($method, $api, $options); $code = $request->getStatusCode(); $content = $request->getBody()->getContents(); return compact('code', 'content'); } catch (\Throwable $e) { return ['code' => 500, 'error' => $e->getMessage()]; } } }