Переглянути джерело

增加URS Request和Login4u Handler详细日志输出

- 为UrsGetUserInfoRequest添加详细的HTTP请求和响应日志
- 为Login4uHandler添加完整的登录流程日志
- 记录请求参数、配置信息、HTTP状态码、响应内容等关键信息
- 增强错误处理和异常日志记录
- 便于调试URS API调用问题和登录流程问题
notfff 6 місяців тому
батько
коміт
28432a105f

+ 137 - 40
ThirdParty/Urs/Request/UrsGetUserInfoRequest.php

@@ -3,6 +3,7 @@
 namespace ThirdParty\Urs\Request;
 
 use ThirdParty\Urs\Util\CryptoService;
+use Illuminate\Support\Facades\Log;
 
 /**
  * URS获取用户信息请求类
@@ -23,54 +24,114 @@ class UrsGetUserInfoRequest extends BaseRequest
      */
     protected function handler(array $params = []): array
     {
+        Log::info('URS获取用户信息请求开始', [
+            'params_keys' => array_keys($params),
+            'userKey_length' => isset($params['userKey']) ? strlen($params['userKey']) : 0
+        ]);
+
         // 验证必需参数
         if (empty($params['userKey'])) {
+            Log::error('URS获取用户信息请求参数验证失败', ['error' => 'userKey参数是必填的']);
             throw new \Exception('userKey参数是必填的');
         }
 
-        // 获取URS配置
-        $c = $this->getUrsCredential();
-
-        $apiUrl = $this->getService()->base_url; // 直接使用服务的base_url
-        $appKey = $c->getApiKey();
-        $ecologyId = $c->getEcologyId(); // 修复:应该获取ecologyId而不是apiKey
-
-        if (empty($apiUrl) || empty($appKey)) {
-            throw new \Exception('URS配置不完整,缺少api_url或app_key');
-        }
-
-        // 构建请求数据
-        $requestData = [
-            'userKey' => $params['userKey']
-        ];
-
-        // 使用URS加密服务加密请求数据
-        $cryptoService = new CryptoService($appKey);
-        $encryptedData = $cryptoService->encrypt($requestData);
-
-        // 构建完整的API URL
-        $fullUrl = rtrim($apiUrl, '/') . "/api/ecology/{$ecologyId}/userInfo";
-
-        // 发送HTTP请求到URS
-        $response = $this->sendHttpRequest($fullUrl, $encryptedData);
+        try {
+            // 获取URS配置
+            $c = $this->getUrsCredential();
+            $apiUrl = $this->getService()->base_url; // 直接使用服务的base_url
+            $appKey = $c->getApiKey();
+            $ecologyId = $c->getEcologyId(); // 修复:应该获取ecologyId而不是apiKey
+
+            Log::info('URS配置获取成功', [
+                'api_url' => $apiUrl,
+                'app_key_length' => strlen($appKey),
+                'ecology_id' => $ecologyId
+            ]);
+
+            if (empty($apiUrl) || empty($appKey)) {
+                Log::error('URS配置验证失败', [
+                    'api_url_empty' => empty($apiUrl),
+                    'app_key_empty' => empty($appKey),
+                    'api_url' => $apiUrl,
+                    'app_key_length' => strlen($appKey)
+                ]);
+                throw new \Exception('URS配置不完整,缺少api_url或app_key');
+            }
+
+            // 构建请求数据
+            $requestData = [
+                'userKey' => $params['userKey']
+            ];
 
-        // 解密响应数据
-        if (isset($response['data'], $response['iv'], $response['timestamp'], $response['sign'])) {
-            $decryptedResponse = $cryptoService->decrypt($response);
+            Log::info('开始加密请求数据', [
+                'request_data_keys' => array_keys($requestData)
+            ]);
+
+            // 使用URS加密服务加密请求数据
+            $cryptoService = new CryptoService($appKey);
+            $encryptedData = $cryptoService->encrypt($requestData);
+
+            Log::info('请求数据加密完成', [
+                'encrypted_data_keys' => array_keys($encryptedData)
+            ]);
+
+            // 构建完整的API URL
+            $fullUrl = rtrim($apiUrl, '/') . "/api/ecology/{$ecologyId}/userInfo";
+
+            Log::info('准备发送HTTP请求', [
+                'full_url' => $fullUrl
+            ]);
+
+            // 发送HTTP请求到URS
+            $response = $this->sendHttpRequest($fullUrl, $encryptedData);
+
+            Log::info('HTTP请求响应接收完成', [
+                'response_keys' => array_keys($response),
+                'has_encrypted_fields' => isset($response['data'], $response['iv'], $response['timestamp'], $response['sign'])
+            ]);
+
+            // 解密响应数据
+            if (isset($response['data'], $response['iv'], $response['timestamp'], $response['sign'])) {
+                Log::info('开始解密响应数据');
+                $decryptedResponse = $cryptoService->decrypt($response);
+
+                Log::info('URS获取用户信息成功', [
+                    'decrypted_response_keys' => array_keys($decryptedResponse)
+                ]);
+
+                return [
+                    'success' => true,
+                    'message' => '获取用户信息成功',
+                    'data' => $decryptedResponse,
+                ];
+            }
+
+            // 如果响应格式不正确,直接返回原始响应
+            Log::error('URS响应格式错误', [
+                'response' => $response,
+                'missing_fields' => [
+                    'data' => !isset($response['data']),
+                    'iv' => !isset($response['iv']),
+                    'timestamp' => !isset($response['timestamp']),
+                    'sign' => !isset($response['sign'])
+                ]
+            ]);
 
             return [
-                'success' => true,
-                'message' => '获取用户信息成功',
-                'data' => $decryptedResponse,
+                'success' => false,
+                'message' => '响应格式错误',
+                'data' => $response,
             ];
-        }
 
-        // 如果响应格式不正确,直接返回原始响应
-        return [
-            'success' => false,
-            'message' => '响应格式错误',
-            'data' => $response,
-        ];
+        } catch (\Exception $e) {
+            Log::error('URS获取用户信息处理异常', [
+                'error_message' => $e->getMessage(),
+                'error_file' => $e->getFile(),
+                'error_line' => $e->getLine(),
+                'userKey_length' => isset($params['userKey']) ? strlen($params['userKey']) : 0
+            ]);
+            throw $e;
+        }
     }
 
     /**
@@ -83,6 +144,14 @@ class UrsGetUserInfoRequest extends BaseRequest
      */
     protected function sendHttpRequest(string $url, array $data): array
     {
+        // 记录请求开始日志
+        Log::info('URS HTTP请求开始', [
+            'url' => $url,
+            'request_data_keys' => array_keys($data),
+            'request_data_size' => strlen(json_encode($data)),
+            'method' => 'POST'
+        ]);
+
         $ch = curl_init();
 
         curl_setopt_array($ch, [
@@ -100,20 +169,48 @@ class UrsGetUserInfoRequest extends BaseRequest
         $response = curl_exec($ch);
         $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
         $error = curl_error($ch);
+        $curlInfo = curl_getinfo($ch);
 
         curl_close($ch);
 
+        // 记录详细的响应信息
+        Log::info('URS HTTP请求完成', [
+            'url' => $url,
+            'http_code' => $httpCode,
+            'curl_error' => $error,
+            'response_size' => strlen($response),
+            'total_time' => $curlInfo['total_time'] ?? 0,
+            'connect_time' => $curlInfo['connect_time'] ?? 0,
+            'response_preview' => substr($response, 0, 500) // 只记录前500字符
+        ]);
+
         if ($error) {
+            Log::error('URS HTTP请求CURL错误', [
+                'url' => $url,
+                'curl_error' => $error,
+                'curl_info' => $curlInfo
+            ]);
             throw new \Exception("HTTP请求失败: {$error}");
         }
 
         if ($httpCode !== 200) {
-            throw new \Exception("HTTP请求失败,状态码: {$httpCode}");
+            Log::error('URS HTTP请求状态码错误', [
+                'url' => $url,
+                'http_code' => $httpCode,
+                'response_body' => $response,
+                'curl_info' => $curlInfo
+            ]);
+            throw new \Exception("HTTP请求失败,状态码: {$httpCode},响应内容: " . substr($response, 0, 200));
         }
 
         $decodedResponse = json_decode($response, true);
         if (json_last_error() !== JSON_ERROR_NONE) {
-            throw new \Exception("响应JSON解析失败: " . json_last_error_msg());
+            Log::error('URS HTTP响应JSON解析失败', [
+                'url' => $url,
+                'json_error' => json_last_error_msg(),
+                'response_body' => $response
+            ]);
+            throw new \Exception("响应JSON解析失败: " . json_last_error_msg() . ",响应内容: " . substr($response, 0, 200));
         }
 
         return $decodedResponse;

+ 76 - 19
app/Module/AppGame/Handler/Public/Login4uHandler.php

@@ -18,7 +18,7 @@ use Uraus\Kku\Response\LastLoginInfo;
 
 /**
  * 处理URS login4u登录请求
- * 
+ *
  * 使用URS的userKey进行登录,自动创建用户并同步推荐关系
  */
 class Login4uHandler extends BaseHandler
@@ -38,29 +38,64 @@ class Login4uHandler extends BaseHandler
      */
     public function handle(Message $data): Message
     {
+        $keylogin = '';
         try {
+            Log::info('Login4u登录请求开始处理');
+
             // 1. 验证登录密钥
             $keylogin = $data->getKeylogin();
+            Log::info('获取登录密钥', [
+                'keylogin_length' => strlen($keylogin),
+                'keylogin_empty' => empty($keylogin)
+            ]);
+
             if (empty($keylogin)) {
+                Log::error('登录密钥验证失败', ['error' => '登录密钥不能为空']);
                 throw new \Exception('登录密钥不能为空');
             }
 
             // 2. 使用URS获取用户信息
+            Log::info('开始获取URS用户信息');
             $ursUserInfo = $this->getUrsUserInfo($keylogin);
             $ursUserId = $ursUserInfo['userId'];
 
+            Log::info('URS用户信息获取成功', [
+                'urs_user_id' => $ursUserId,
+                'user_info_keys' => array_keys($ursUserInfo)
+            ]);
+
             // 3. 获取或创建农场用户ID
+            Log::info('开始获取农场用户ID', ['urs_user_id' => $ursUserId]);
             $farmUserId = UrsUserMappingService::getFarmUserId($ursUserId);
             if (!$farmUserId) {
+                Log::error('获取农场用户ID失败', [
+                    'urs_user_id' => $ursUserId,
+                    'farm_user_id' => $farmUserId
+                ]);
                 throw new \Exception('获取农场用户ID失败');
             }
 
+            Log::info('农场用户ID获取成功', [
+                'urs_user_id' => $ursUserId,
+                'farm_user_id' => $farmUserId
+            ]);
+
             // 4. 获取农场用户信息
+            Log::info('开始获取农场用户信息', ['farm_user_id' => $farmUserId]);
             $userDto = UserService::info($farmUserId);
             if (!$userDto) {
+                Log::error('农场用户不存在', [
+                    'farm_user_id' => $farmUserId,
+                    'user_dto' => $userDto
+                ]);
                 throw new \Exception('农场用户不存在');
             }
 
+            Log::info('农场用户信息获取成功', [
+                'farm_user_id' => $farmUserId,
+                'user_name' => $userDto->name ?? 'unknown'
+            ]);
+
             // 5. 同步上下级关系
             $this->syncReferralRelations($ursUserId);
 
@@ -87,12 +122,10 @@ class Login4uHandler extends BaseHandler
             // 9. 创建响应对象
             $response = new ResponsePublicLogin4u();
             $response->setToken($sessionId);
-            $response->setIsProhibit(false); // 根据用户状态设置
 
-            // 设置最后登录信息(可选)
-            $lastLoginInfo = new LastLoginInfo();
-            $lastLoginInfo->setLastLoginTimes(time());
-            $response->setLastLoginInfo($lastLoginInfo);
+
+
+
 
             return $response;
 
@@ -103,13 +136,10 @@ class Login4uHandler extends BaseHandler
                 'trace' => $e->getTraceAsString()
             ]);
 
-            // 返回失败响应
-            $response = new ResponsePublicLogin4u();
-            $response->setToken('');
-            $response->setIsProhibit(true);
-            
-            return $response;
+            throw new $e;
         }
+        return $response;
+
     }
 
     /**
@@ -121,19 +151,46 @@ class Login4uHandler extends BaseHandler
      */
     private function getUrsUserInfo(string $keylogin): array
     {
+        Log::info('开始获取URS用户信息', [
+            'keylogin_length' => strlen($keylogin),
+            'keylogin_prefix' => substr($keylogin, 0, 10) . '...'
+        ]);
+
         try {
             $result = UrsService::getUserInfo($keylogin);
-            
+
+            Log::info('URS服务调用完成', [
+                'result_keys' => array_keys($result),
+                'success' => $result['success'] ?? false,
+                'message' => $result['message'] ?? '',
+                'has_data' => isset($result['data']),
+                'data_keys' => isset($result['data']) ? array_keys($result['data']) : []
+            ]);
+
             if (!$result['success'] || empty($result['data']['userId'])) {
+                Log::error('URS用户信息获取失败详情', [
+                    'result' => $result,
+                    'success' => $result['success'] ?? false,
+                    'has_userId' => isset($result['data']['userId']),
+                    'userId_value' => $result['data']['userId'] ?? null
+                ]);
                 throw new \Exception('URS用户信息获取失败: ' . ($result['message'] ?? '未知错误'));
             }
 
+            Log::info('URS用户信息获取成功', [
+                'userId' => $result['data']['userId'],
+                'data_keys' => array_keys($result['data'])
+            ]);
+
             return $result['data'];
 
         } catch (\Exception $e) {
-            Log::error('获取URS用户信息失败', [
-                'keylogin' => $keylogin,
-                'error' => $e->getMessage()
+            Log::error('获取URS用户信息异常', [
+                'keylogin_length' => strlen($keylogin),
+                'error_message' => $e->getMessage(),
+                'error_file' => $e->getFile(),
+                'error_line' => $e->getLine(),
+                'trace' => $e->getTraceAsString()
             ]);
             throw new \Exception('URS用户验证失败: ' . $e->getMessage());
         }
@@ -150,14 +207,14 @@ class Login4uHandler extends BaseHandler
         try {
             // 获取用户的上级关系链
             $teamResult = UrsService::getUserTeam($ursUserId);
-            
+
             if (!$teamResult['success'] || empty($teamResult['data'])) {
                 Log::info('URS用户无上级关系', ['urs_user_id' => $ursUserId]);
                 return;
             }
 
             $teamData = $teamResult['data'];
-            
+
             // 检查是否已存在推荐关系
             $existingReferral = \App\Module\UrsPromotion\Models\UrsUserReferral::where('urs_user_id', $ursUserId)->first();
             if ($existingReferral) {
@@ -177,7 +234,7 @@ class Login4uHandler extends BaseHandler
 
             // 创建推荐关系
             $referralDto = UrsReferralService::createReferral($ursUserId, $directReferrerId);
-            
+
             Log::info('URS推荐关系同步成功', [
                 'urs_user_id' => $ursUserId,
                 'urs_referrer_id' => $directReferrerId,