wechat = new Wechat('wxMiniProgram'); } public function getAccessToken() { $token = $this->wechat->getAccessToken(); if (is_array($token) && !empty($token['access_token'])) { return $token['access_token']; } if (is_string($token)) { return $token; } throw new \RuntimeException('无法获取小程序 access_token'); } public function postJson($path, array $body) { $token = $this->getAccessToken(); $url = 'https://api.weixin.qq.com' . $path . '?access_token=' . urlencode($token); $headers = ['Content-Type: application/json']; $options = [CURLOPT_HTTPHEADER => $headers]; $result = Http::sendRequest($url, json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'POST', $options); if (!isset($result['ret']) || !$result['ret']) { throw new \RuntimeException('微信 API 请求失败: ' . ($result['msg'] ?? 'unknown')); } $decoded = json_decode($result['msg'], true); if (!is_array($decoded)) { throw new \RuntimeException('微信 API 响应解析失败'); } return $decoded; } public function getJson($path, array $query = []) { $token = $this->getAccessToken(); $query['access_token'] = $token; $url = 'https://api.weixin.qq.com' . $path . '?' . http_build_query($query); $result = Http::sendRequest($url, [], 'GET'); if (!isset($result['ret']) || !$result['ret']) { throw new \RuntimeException('微信 API 请求失败: ' . ($result['msg'] ?? 'unknown')); } $decoded = json_decode($result['msg'], true); if (!is_array($decoded)) { throw new \RuntimeException('微信 API 响应解析失败'); } return $decoded; } public function callOrThrow(array $response, $action = '微信接口') { $errcode = intval($response['errcode'] ?? 0); if ($errcode !== 0) { $msg = ($response['errmsg'] ?? 'unknown') . ' (' . $errcode . ')'; Log::write('[shopro_wechat_trade] ' . $action . ' fail: ' . $msg); throw new \RuntimeException($action . '失败: ' . $msg); } return $response; } }