appKey = $appKey; $this->appSecret = $appSecret; $this->accessToken = $accessToken; } /** * 拉取订单列表(taobao.trades.sold.get) * * @param string $startTime 起始时间,格式:Y-m-d H:i:s * @param string $endTime 结束时间 * @return array * @throws \Exception */ public function fetchOrders($startTime, $endTime) { $params = [ 'method' => 'taobao.trades.sold.get', 'app_key' => $this->appKey, 'session' => $this->accessToken, 'timestamp' => date('Y-m-d H:i:s'), 'format' => 'json', 'v' => '2.0', 'sign_method' => 'hmac-sha256', 'fields' => 'tid,status,payment,receiver_name,receiver_city,receiver_district,receiver_address,orders', 'start_created' => $startTime, 'end_created' => $endTime, ]; $params['sign'] = $this->generateSign($params); try { $client = new Client(); $response = $client->post($this->gateway, [ 'form_params' => $params, 'timeout' => 30, ]); $result = json_decode($response->getBody(), true); // 检查淘宝API返回的错误 if (isset($result['error_response'])) { throw new \Exception('淘宝API错误: ' . $result['error_response']['msg']); } return $result; } catch (\Exception $e) { Log::error('淘宝订单拉取失败', ['error' => $e->getMessage()]); throw $e; } } /** * 生成签名 * * @param array $params * @return string */ protected function generateSign($params) { ksort($params); $stringToSign = $this->appSecret; foreach ($params as $key => $value) { if ($key != 'sign' && $value !== '') { $stringToSign .= $key . $value; } } $stringToSign .= $this->appSecret; return strtoupper(hash_hmac('sha256', $stringToSign, $this->appSecret)); } }