request('GET', $url, [ 'query' => $query, ]); } /** * 发起 POST 请求 * * @param string $url * @param array $data * @return array */ public function post(string $url, array $data = []): array { return $this->request('POST', $url, [ 'json' => $data, // 'form_params' => $data, ]); } /** * 发起 HTTP 请求 * * @param string $method * @param string $url * @param array $options * @return array */ protected function request(string $method, string $url, array $options = []): array { // 随机字符串 $nonce = $this->nonce(); // 毫秒时间戳 $timestamp = now()->getTimestampMs(); $options['headers'] = array_merge([ 'Content-Type' => 'application/json', 'api-key' => $this->apiKey, 'Nonce' => $nonce, 'Timestamp' => $timestamp, 'Signature' => $this->sign($nonce, $timestamp), ], $options['headers'] ?? []); $response = Http::baseUrl(static::BASE_URL)->send($method, $url, $options); // HTTP request returned status code 500: {"msg":"系统异常,接口调用失败","code":"default","success":false} $response->throw(); return $response->json(); } /** * 生成签名 * * @param string $nonce * @param int $timestamp * @return string */ public function sign(string $nonce, int $timestamp): string { return sha1($nonce.$timestamp.$this->apiSecret); } /** * @param int $length * @param string $charset * @return string */ protected function nonce(int $length = 8, string $charset = '0123456789'): string { $max = strlen($charset) - 1; $nonce = ''; for ($i = 0; $i < $length; $i++) { $nonce .= $charset[mt_rand(0, $max)]; } return $nonce; } }