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