getConfig(); $apiUrl = $config['api_url'] ?? ''; $appKey = $config['app_key'] ?? ''; $ecologyId = $config['ecology_id'] ?? 1; if (empty($apiUrl) || empty($appKey)) { throw new \Exception('URS配置不完整,缺少api_url或app_key'); } // 构建请求数据 $requestData = [ 'userId' => (int)$params['userId'], 'level' => (int)$params['level'] ]; // 使用URS加密服务加密请求数据 $cryptoService = new CryptoService($appKey); $encryptedData = $cryptoService->encrypt($requestData); // 构建完整的API URL $fullUrl = rtrim($apiUrl, '/') . "/api/ecology/{$ecologyId}/userLevelCount"; // 发送HTTP请求到URS $response = $this->sendHttpRequest($fullUrl, $encryptedData); // 解密响应数据 if (isset($response['data'], $response['iv'], $response['timestamp'], $response['sign'])) { $decryptedResponse = $cryptoService->decrypt($response); return [ 'success' => true, 'message' => '获取用户下级统计成功', 'data' => $decryptedResponse, ]; } // 如果响应格式不正确,直接返回原始响应 return [ 'success' => false, 'message' => '响应格式错误', 'data' => $response, ]; } /** * 发送HTTP请求 * * @param string $url 请求URL * @param array $data 请求数据 * @return array * @throws \Exception */ protected function sendHttpRequest(string $url, array $data): array { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $url, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'User-Agent: KKU-ThirdParty-URS/1.0', ], ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $error = curl_error($ch); curl_close($ch); if ($error) { throw new \Exception("HTTP请求失败: {$error}"); } if ($httpCode !== 200) { throw new \Exception("HTTP请求失败,状态码: {$httpCode}"); } $decodedResponse = json_decode($response, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new \Exception("响应JSON解析失败: " . json_last_error_msg()); } return $decodedResponse; } }