$timeout ]; switch ($type) { case FormType::urlencoded: $params['form_params'] = $param; $type = 'POST'; break; case FormType::json: $params['json'] = $param; $type = 'POST'; break; case FormType::formData: $params['multipart'] = $param; $type = 'POST'; break; default: $params['query'] = $param; $type = 'GET'; break; } if ($extern) { $params = array_merge($params, $extern); } $r = $client->request($type, $url, $params); $res = $r->getBody()->getContents(); if ($isJson) { $data = json_decode($res, true); if ($data === false) { throw new Exception($res, 0); } } else { $data = $res; } return $data; } /** * @throws GuzzleException * @throws Exception */ public static function GetToken(): string { $token = Cache::get('token'); if ($token) { return $token; } $url = rtrim(env('API_DOMAIN'), '/') . '/Index/getToken'; $now = date('Y-m-d H:i:s'); $appId = env('APP_ID'); $appKey = env('APP_KEYX'); $sign = sprintf("app_id=%s:app_key=%s:tamptimes=%s", $appId, $appKey, $now); $sign = strtoupper(md5($sign)); $form = [ 'app_id' => $appId, 'app_key' => $appKey, 'tamptimes' => $now, 'sign' => $sign ]; $res = self::request($url, $form, FormType::json); if (!$res['data']['token']) { throw new Exception('获取token失败:' . $res['desc'] ?? ''); } $token = $res['data']['token']; Cache::set('token', $token, strtotime($res['data']['deadline']) - time() - 300); return $token; } /** * @throws GuzzleException */ public static function api($path, mixed $param = [], int $timeout = 5, array $extern = []): mixed { return self::apis($path, self::getClient(), $param, $timeout, $extern); } /** * @throws GuzzleException */ public static function apis($path, Client $client, mixed $param = [], int $timeout = 5, array $extern = []): mixed { $url = rtrim(env('API_DOMAIN'), '/') . $path; $token = self::GetToken(); $param['token'] = $token; return self::requests($client, $url, $param, FormType::json, true, $timeout, $extern); } }