fix: 改进登录流程的错误处理和日志

- 添加详细的登录日志输出
- 获取openId失败时返回错误而非创建guest用户
- 避免重复创建用户账号
This commit is contained in:
H1d3rOne committed 2026-03-10 16:39:18 +08:00
1 parent f3b084a72f
commit 7b6df6426c
1 file changed
+22 -1
@@ -39,6 +39,11 @@ public class UserController {
String username = params.get("nickname") != null ? params.get("nickname").toString() : "微信用户";
String avatarUrl = params.get("avatarUrl") != null ? params.get("avatarUrl").toString() : "";
System.out.println("=== 登录请求 ===");
System.out.println("code: " + code);
System.out.println("appId: " + appId);
System.out.println("appSecret: " + (appSecret != null ? "已配置" : "未配置"));
String openId = null;
if (code != null && !code.isEmpty() && appId != null && !appId.isEmpty() && appSecret != null && !appSecret.isEmpty()) {
@@ -47,25 +52,39 @@ public class UserController {
appId, appSecret, code
);
System.out.println("调用微信API: " + url);
try {
RestTemplate restTemplate = new RestTemplate();
@SuppressWarnings("unchecked")
Map<String, Object> wxResult = restTemplate.getForObject(url, Map.class);
System.out.println("微信API返回: " + wxResult);
if (wxResult != null && wxResult.containsKey("openid")) {
openId = (String) wxResult.get("openid");
System.out.println("获取到openId: " + openId);
} else if (wxResult != null) {
System.err.println("微信API返回错误: " + wxResult.get("errmsg") + ", errcode: " + wxResult.get("errcode"));
}
} catch (Exception e) {
System.err.println("调用微信API失败: " + e.getMessage());
e.printStackTrace();
}
} else {
System.err.println("登录参数不完整: code=" + code + ", appId=" + appId + ", appSecret=" + (appSecret != null ? "有" : "无"));
}
if (openId == null || openId.isEmpty()) {
openId = "guest_" + System.currentTimeMillis();
result.put("success", false);
result.put("error", "获取用户身份失败,请重试");
return result;
}
UserInfo user = userInfoService.loginOrRegister(openId, username, avatarUrl);
System.out.println("登录成功: userId=" + user.getUserId() + ", openId=" + user.getOpenId());
Map<String, Object> data = new HashMap<>();
data.put("id", user.getId());
data.put("userId", user.getUserId());
@@ -81,6 +100,8 @@ public class UserController {
result.put("success", true);
result.put("data", data);
} catch (Exception e) {
System.err.println("登录异常: " + e.getMessage());
e.printStackTrace();
result.put("success", false);
result.put("error", e.getMessage());
}