config = $config; } /** * @return $this */ public function get() { $this->method = 'get'; return $this; } /** * @return $this */ public function post() { $this->method = 'post'; return $this; } /** * @param ModelInterface|null $model * @return $this * @throws GuzzleException */ public function send(ModelInterface $model = null) { $client = new Client([ 'base_uri' => 'https://api.weixin.qq.com', 'headers' => $this->headers, 'timeout' => 30 ]); if (!empty($model)) { $this->paramsModel = $model; if (in_array($this->params_key, ['multipart'])) { foreach ($model->toArray() as $name => $value) { $this->request_option[$this->params_key][] = [ "name" => $name, "contents" => file_get_contents($value), "filename" => md5($value . time()), ]; } } else { $this->request_option[$this->params_key] = empty($model->toArray()) && $this->params_key == 'json' ? new \stdClass() : $model->toArray(); } // $this->request_option['debug'] = true; } if (!empty($this->query)) { $this->request_option['query'] = array_merge($this->request_option['query'] ?? [], $this->query); } try { $this->response = $client->request($this->method, $this->route, $this->request_option); } catch (ClientException $e) { $ret = Json::decode($e->getResponse()->getBody()->getContents()); $this->error = $ret['msg'] ?? $e->getMessage(); } return $this; } /** * @return $this * @throws GuzzleException */ public function accessToken() { $this->request_option = [ 'query' => [ 'access_token' => WechatAccessTokenHelper::getAccessToken($this->config), // 这里需要取获取token ] ]; return $this; } /** * @return ResponseInterface */ public function getResponse() { return $this->response; } /** * @return array */ public function toArray() { if (empty($this->responseData)) { mb_internal_encoding("UTF-8"); $this->rawContent = $this->response->getBody()->getContents(); $this->rawContent = mb_convert_encoding($this->rawContent, "UTF-8"); $this->responseData = Json::decode($this->rawContent); } return $this->responseData; } /** * @return mixed|string */ public function getRawContent() { return $this->rawContent; } /** * @return mixed|string */ public function getError() { return $this->error; } /** * 响应错误 * @return string */ public function respError() { if (empty($this->respError)) { if (empty($this->paramsModel)) { $this->respError = 'params model is empty!'; } else { $this->respError = $this->paramsModel->valid($this->toArray()); } } return $this->respError; } /** * @param array $headers * @return $this */ public function withHeaders(array $headers) { $this->headers = $headers; return $this; } /** * @param array $params * @return $this */ public function withQuery(array $params) { $this->query = $params; return $this; } }