微信登录功能开发过程中的Bug解决日志
在进行微信用户登录这一功能的开发时,我被一个bug卡了好久:使用Postman向微信接口服务发送GET请求获取openid是成功的,但在Java程序中却失败,报错:
json
{
"errcode":40002,
"errmsg":"invalid grant_type, rid: 69613ee1-1363e562-5faeede8"
}
经过仔细排查和Gemini的协助,发现UserServiceImpl中新用户自动完成注册部分的代码存在bug。
原代码如下:
java
@Service
@Slf4j
public class UserServiceImpl implements UserService {
// 微信接口服务地址
public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
@Autowired
private WeChatProperties weChatProperties;
@Autowired
private UserMapper userMapper;
// 微信用户登录
@Override
public User wxLogin(UserLoginDTO userLoginDTO) {
// 1.调用微信接口服务,获取当前微信用户的openid
Map<String, String> map=new HashMap<>();
map.put("appid",weChatProperties.getAppid());
map.put("secret",weChatProperties.getSecret());
map.put("js_code", userLoginDTO.getCode());
map.put("grant_type","authorization_code");
String json = HttpClientUtil.doGet(WX_LOGIN, map);
JSONObject jsonObject = JSON.parseObject(json);
String openid = jsonObject.getString("openid");
// 2.判断openid是否为空,如果为空,说明登录失败,抛出业务异常
if(openid==null){
throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
}
// 3.根据openid去user表中查询是否存在对应用户,从而判断当前用户是否为苍穹外卖的新用户
LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
lqw.eq(User::getOpenid,openid);
User user = userMapper.selectOne(lqw);
if(user==null){
// 4.如果是新用户,自动完成注册
user.setOpenid(openid);
user.setCreateTime(LocalDateTime.now());
userMapper.save(user);
}
return user;
}
}
可以发现,在if(user==null){...}内部,我忘记先new一个User出来,导致user仍为数据库查出的结果也就是null,这时候调用setOpenid必然失败,因为不能给null对象赋值!
修改如下:
java
if(user==null){
// 4.如果是新用户,自动完成注册
//Caution: 必须先new一个User出来,否则user仍为null,调用setter会报错!
user=new User();
user.setOpenid(openid);
user.setCreateTime(LocalDateTime.now());
userMapper.save(user);
}
修改后就返回200 OK了。