'application/json']) { $config = [ 'connect_timeout' => 3, 'timeout' => 30, 'http_errors' => true, //抛出异常 true是 false否 'verify' => false, 'headers' => [ 'charset' => 'utf-8' ], ]; if ($base_uri) { $config['base_uri'] = $base_uri; } if ($header) { $config['headers'] = array_merge($config['headers'], $header); } $this->client = new Client($config); return $this->getReturn(); } /** * 发送API请求 * @param $uri * @param $data * @return ReturnObject|ApiService */ public function post($uri, $data) { try { $result = $this->client->request('POST', (string)$uri, [ 'body' => json_encode($data) ]); LogService::info('uri:'.$uri); LogService::info('body:'.json_encode($data)); if ($result->getStatusCode() == 200) { $content = $result->getBody()->getContents(); } else { $content = ''; } return $this->setData($content)->getReturn(); } catch (GuzzleException $e) { return $this->setCode($e->getCode())->setMsg($e->getMessage())->getReturn(); } catch (\Exception $e) { return $this->setCode($e->getCode())->setMsg($e->getMessage())->getReturn(); } } /** * @param $code * @param $params * @return ReturnObject|ApiService */ public function getCollectFromApi($code, $params) { ApiService::instance()->jsonRequest(Config::get('api.external_uri')); $result = ApiService::instance()->post($code, $params); $data = []; if ($result->code == ErrorCodeConstants::SUCCESS) { if ($result->data) { $decode = json_decode($result->data, true); if ($decode && array_key_exists('retCode', $decode) && $decode['retCode'] == 0) { $data = $decode['data']; } } } return $this->setData($data)->getReturn(); } /** * @param $code * @param $params * @return ReturnObject|ApiService */ public function getDataFromApi($code, $params) { ApiService::instance()->jsonRequest(Config::get('api.service_uri')); $result = ApiService::instance()->post($code, $params); $data = []; if ($result->code == ErrorCodeConstants::SUCCESS) { if ($result->data) { $decode = json_decode($result->data, true); if ($decode && array_key_exists('status', $decode) && in_array($decode['status'], [0, 104])) { if (array_key_exists('data', $decode)) { $data = $decode['data']; } } else { LogService::error($result->data); } } } return $this->setData($data)->getReturn(); } public function checkApiOn() { return Config::get('api.service_on'); } }