appkey = (string)$appkey; $this->secret = (string)$secret; $this->baseUrl = rtrim((string)$baseUrl, '/'); $this->timeout = (int)$timeout; $this->verifySsl = (bool)$verifySsl; } public function categories() { return $this->request('GET', 'categories'); } public function goodsList($page = 1, $perPage = 20, $categoryId = 0, $keyword = '') { $query = ['page' => (int)$page, 'per_page' => (int)$perPage]; if ((int)$categoryId > 0) { $query['category_id'] = (int)$categoryId; } if ((string)$keyword !== '') { $query['keyword'] = (string)$keyword; } return $this->request('GET', 'goods', null, $query); } public function goodsDetail($goodsId) { return $this->request('GET', 'goods/' . (int)$goodsId); } public function stock(array $goodsIds) { return $this->request('GET', 'stock', null, ['goods_ids' => implode(',', array_map('intval', $goodsIds))]); } public function createOrder(array $params) { return $this->request('POST', 'order', $params); } public function queryOrder($orderNo) { return $this->request('GET', 'order/' . rawurlencode((string)$orderNo)); } public function summary() { return $this->request('GET', 'summary'); } public function refund($orderNo, $reason = '') { return $this->request('POST', 'order/refund', [ 'order_no' => (string)$orderNo, 'reason' => (string)$reason, ]); } public function request($method, $route, $body = null, array $query = []) { $method = strtoupper((string)$method); $bodyRaw = $body === null ? '' : json_encode($body, JSON_UNESCAPED_UNICODE); $ts = (string)time(); $nonce = bin2hex(random_bytes(8)); $canonical = $method . "\n" . $route . "\n" . $ts . "\n" . $nonce . "\n" . hash('sha256', $bodyRaw); $signature = hash_hmac('sha256', $canonical, $this->secret); $url = $this->baseUrl . '/openapi.php?route=' . rawurlencode($route); if (!empty($query)) { $url .= '&' . http_build_query($query); } $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'appkey: ' . $this->appkey, 'timestamp: ' . $ts, 'nonce: ' . $nonce, 'signature: ' . $signature, ], CURLOPT_POSTFIELDS => $bodyRaw, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_SSL_VERIFYPEER => $this->verifySsl, CURLOPT_SSL_VERIFYHOST => $this->verifySsl ? 2 : 0, ]); $resp = curl_exec($ch); $err = curl_error($ch); $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($resp === false) { throw new RuntimeException('网络请求失败: ' . $err); } $data = json_decode($resp, true); if (!is_array($data) || !array_key_exists('code', $data)) { throw new RuntimeException('响应解析失败(HTTP ' . $http . '): ' . mb_substr((string)$resp, 0, 200)); } return $data; } }