privateKey; } public function setPrivateKey(string $privateKey): void { $this->privateKey = $privateKey; } public function getType(): string { return $this->type; } public function setType(string $type): void { $this->type = $type; } public function getAppId(): string { return $this->appId; } public function setAppId(string $appId): void { $this->appId = $appId; } public function getApi(): string { return $this->api; } public function setApi(string $api): void { $this->api = $api; } public function isDebug(): bool { return $this->debug; } public function setDebug(bool $debug): void { $this->debug = $debug; } private ?Client $client = null; private function getHttpClient(): Client { if ($this->client == null) { $this->client = new Client([ 'base_uri' => $this->api, 'allow_redirects' => [ 'max' => 2 ], 'debug' => $this->debug, 'headers' => [ 'user-agent' => 'MaiYouLeMQTTClientAuthor/' . self::VERSION, 'Accept' => 'application/json' ] ]); } return $this->client; } private function sign(string $str) { $prikey = RSA::loadPrivateKey($this->privateKey); $result = $prikey->sign($str); return base64_encode($result); } /** * @param IRequest $request * @return BizResponse * @throws ApiException * @throws \GuzzleHttp\Exception\GuzzleException */ public function exec(IRequest $request): BizResponse { //生成签名 $url = sprintf('%s%s', $this->api, $request->path()); $urls = parse_url($url); $path = $urls['path']; $body = $request->body(); $body['appid'] = $this->getAppId(); $body['type'] = $this->getType(); ksort($body, SORT_NATURAL); $waitItem = []; foreach ($body as $key => $value) { $waitItem[] = $key . '=' . urlencode($value); } $waitItem[] = urlencode($path); $str = join('&', $waitItem); $sign = $this->sign($str); $body['sign'] = $sign; $http = $this->getHttpClient(); try { $result = $http->request('POST', $path, [ 'form_params' => $body ]); $content = $result->getBody()->getContents(); if (empty($content)) { //没有反馈内容 return new BizResponse(); } $data = json_decode($content, true); return new BizResponse($data['code'] ?? 0, $data['message'] ?? '', $data['data'] ?? [], $data['err'] ?? ''); } catch (ClientException $e) { $body = $e->getResponse()->getBody()->getContents(); $message = ''; if (!empty($body)) { $data = json_decode($body, true); $message = $data['message'] ?? ''; } throw new ApiException($message, $e->getResponse()->getStatusCode()); } } }