uniapp微信登录的流程
使用流程:
1.调用wx.login()获取一个临时的登录凭证code(只能使用一次)
2.调用 auth.code2Session 接口,换取 用户唯一标识 OpenID 、 用户在微信开放平台账号下的唯一标识
业务需求:
1.基于微信小程序的登录功能实现
2.如果用户是新用户则需要自动完成创建
一个基本的用户表
源码示例
@Autowiredprivate UserService userService;@AutowiredJwtProperties jwtProperties;/*** 微信登录* @param userLoginDTO* @return*/@ApiOperation("微信登录")@PostMapping("/login")public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {log.info("微信用户登录:{}",userLoginDTO );//微信登录User user = userService.wxLogin(userLoginDTO);//生成jwt令牌HashMap<String, Object> claims = new HashMap<>();//存放用户idclaims.put("userId", user.getId());//生成令牌 参数1 密钥,参数2 有效期,参数3 存放在令牌中的自定义数据String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);//传递后前端所需的数据UserLoginVO userLoginVO = UserLoginVO.builder().id(user.getId()).openid(user.getOpenid()).token(token).build();return Result.success(userLoginVO);}
@AutowiredWeChatProperties weChatProperties;@AutowiredUserMapper userMapper;//定义获取微信openid的urlprivate static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";/**** 微信登录* @param userLoginDTO* @return*/@Overridepublic User wxLogin(UserLoginDTO userLoginDTO) {String openid = getOpenid(userLoginDTO);//判断当前传递的code是否正确if (openid == null) {throw new LoginFailedException(MessageConstant.LOGIN_FAILED);}log.info("微信登录openid:{}", openid);//通过openid查询对象,判断是否为新用户User user = userMapper.getByOpenid(openid);if (user != null) {return user;}//封装当前的用户对象user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();userMapper.insert(user);return user;}private String getOpenid(UserLoginDTO userLoginDTO) {//获取当前的openidHashMap hashMap = new HashMap();hashMap.put("appid", weChatProperties.getAppid());hashMap.put("secret", weChatProperties.getSecret());hashMap.put("js_code", userLoginDTO.getCode());hashMap.put("grant_type", "authorization_code");String json = HttpClientUtil.doGet(WX_LOGIN_URL, hashMap);JSONObject jsonObject = JSON.parseObject(json);String openid = jsonObject.getString("openid");return openid;}