ping(); */ abstract class Base { /** @var WmsSign */ protected $signer; /** @var string */ protected $appKey; /** @var string */ protected $baseUrl; /** @var string */ protected $version; /** @var int */ protected $timeout; /** @var int */ protected $connectTimeout = 5; public function __construct() { $wms = config('wms') ?: []; $this->appKey = $wms['app_key'] ?? ''; $this->signer = new WmsSign($wms['app_secret'] ?? ''); $this->baseUrl = rtrim($wms['base_url'] ?? '', '/'); $this->version = $wms['version'] ?? '1.0'; $this->timeout = (int) ($wms['timeout'] ?? 10); } // ==================== 子类需覆盖 ==================== /** * 返回当前模块名(如 'index'、'store'、'inbox') * @return string */ abstract protected function moduleName(); // ==================== 公共调用方法 ==================== /** * 调用 WMS 开放接口 * * @param string $methodName 方法名(如 'ping'、'list'、'push') * @param array $body 请求体(关联数组),空 body 传 [] * @param array $extraQuery 额外的 query 参数 * @return array 解析后的响应数组,包含 code / msg / data */ protected function call($methodName, array $body = [], array $extraQuery = []) { $method = $this->moduleName() . '.' . $methodName; $body = !empty($body) ? $body : new \stdClass(); // 空 body → {} // ---- 构建 query 参数 ---- $timestamp = time(); $nonce = $this->generateNonce(16); $queryParams = array_merge([ 'app_key' => $this->appKey, 'method' => $method, 'timestamp' => $timestamp, 'v' => $this->version, 'nonce' => $nonce, ], $extraQuery); // ---- 签名 ---- $sign = $this->signer->make($queryParams, $body); // ---- 发起请求 ---- $queryStr = http_build_query(array_merge($queryParams, ['sign' => $sign])); $url = $this->baseUrl . '/warehouse?' . $queryStr; $bodyJson = json_encode($body, JSON_UNESCAPED_UNICODE); // ---- 调试:打印完整请求 ---- \think\Log::error("[WmsFunc] {$method} 请求\nURL: {$url}\nBody: {$bodyJson}"); try { $response = Http::post($url, $bodyJson, [ CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', ], CURLOPT_TIMEOUT => $this->timeout, CURLOPT_CONNECTTIMEOUT => $this->connectTimeout, ]); $result = json_decode($response, true); if ($result === null && json_last_error() !== JSON_ERROR_NONE) { \think\Log::error("[WmsFunc] {$method} 响应解析失败\nResponse: {$response}"); return ['code' => -1, 'msg' => '响应解析失败', 'data' => null]; } \think\Log::error("[WmsFunc] {$method} 响应: " . json_encode($result, JSON_UNESCAPED_UNICODE)); return $result; } catch (\Exception $e) { \think\Log::error("[WmsFunc] {$method} 请求异常: " . $e->getMessage()); return ['code' => -1, 'msg' => '请求异常: ' . $e->getMessage(), 'data' => null]; } } // ==================== 工具方法 ==================== /** * 生成随机 nonce * @param int $length * @return string */ protected function generateNonce($length = 16) { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $nonce = ''; for ($i = 0; $i < $length; $i++) { $nonce .= $chars[random_int(0, strlen($chars) - 1)]; } return $nonce; } }