1.小程序用户登录
2.用户入库
3.返回token给小程序用户
4.授权小程序昵称和头像
参考官方流程图:
前端:
后端:
/** * 小程序登录获取接口访问token,主入口 * * @param jsCode 小程序jsCode * @return 返回token给前端 */ @ResponseBody @GetMapping("code2Session") @ApiOperation("小程序-code2Session(获取openid)") public ResponseData code2Session(String jsCode) { log.info("小程序用户登录,code2Session(获取openid)"); String code2SessionUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + jsCode + "&grant_type=authorization_code"; String content = restTemplate.getForEntity(code2SessionUrl, String.class).getBody(); String openid = JSON.parseObject(content).get("openid").toString(); String unionid = JSON.parseObject(content).get("unionid").toString(); if (StrUtil.isEmpty(openid)) { return new ErrorResponseData("openid不能为空"); } if (StrUtil.isEmpty(unionid)) { return new ErrorResponseData("unionid不能为空"); } Mapmap = new TreeMap<>(); QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_union", unionid); User user_union = userService.getOne(queryWrapper); QueryWrapper queryWrapper1 = new QueryWrapper<>(); queryWrapper1.eq("user_mini_wx ", openid); User user_mini = userService.getOne(queryWrapper1); //判断此用户是否存在数据库中 if (user_mini == null) { User user1; log.info("小程序用户登录,当前用户不存在数据库中,进行新建..."); if (user_union == null) { user1 = new User(); user1.setUserUnion(unionid); } else { user1 = user_union; } user1.setUserMiniWx(openid); user1.setUserMiniNick(BaseConstant.NICK_DEFAULT); user1.setUserMiniHead(BaseConstant.HEAD_DEFAULT); user1.setUserSex(1); userService.saveOrUpdate(user1); log.info("小程序用户登录,用户新建成功!user:{}", user1.toString()); map.put("token", tokenService.getToken(user1)); return new SuccessResponseData(map); } else { log.info("小程序用户登录,当前用户已存在数据库中,直接获取token"); map.put("token", tokenService.getToken(user_mini)); return new SuccessResponseData(map); } }
/** * 获取小程序头像和昵称进行入库 * * @param nickName 小程序昵称 * @param avatarUrl 小程序头像 * @param token token * @return 结果 */ @ResponseBody @ApiOperation("小程序-更新头像、昵称") @PostMapping("/updateNikeAndHead") public ResponseData updateNikeAndHead(String nickName, String avatarUrl, String token) { log.info("小程序更新用户头像和昵称,nickName:{},avatarUrl:{}", nickName, avatarUrl); Long userId = TokenUtil.getTokenUserIdMini(token); LambdaQueryWrapperqueryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(User::getUserId, userId); User user = userService.getOne(queryWrapper); if (user != null) { user.setUserMiniNick(nickName); user.setUserMiniHead(avatarUrl); userService.updateById(user); return new SuccessResponseData(); } else { log.error("小程序-更新头像跟昵称,当前token对应的用户不存在,请检查token取值"); return new ErrorResponseData("用户不存在"); } }
/*** * token 下发 * @Title: TokenService.java * @author zhang pan * @date 2022/7/6 23:15 * @version V1.0 */ @Slf4j @Service("TokenService") public class TokenService { public String getToken(User user) { Date start = new Date(); //7天有效时间 //long currentTime = System.currentTimeMillis() + 60* 60 * 1000 * 24 * 7; long currentTime = System.currentTimeMillis() + 60 * 60 * 1000 * 24; //long currentTime = System.currentTimeMillis() + 60 * 1000; Date end = new Date(currentTime); String token = ""; token = JWT.create() .withAudience(user.getUserId().toString()).withIssuedAt(start) .withExpiresAt(end) .sign(Algorithm.HMAC256("aaaaaa")); log.info("getToken..........token:{}", token); return token; } }
注意,此处下发的token用JWT形式
1.公众号授权登录
2.开放平台unionid机制,用unionid机制,可以关联绑定在同一开放平台下的不同端用户openid,也就是openid不同,但只要帮定于同一开放平台下,则会拿到同一unionid。
/**
* 公众号登录-主入口
*
* @return 接口访问token
*/
@RequestMapping(value = "/token", method = RequestMethod.GET)
@ApiOperation("获取用户token和user信息")
public ModelAndView getToken() {
log.info("公众号用户登录获取token");
String code = request.getParameter("code");
String state = request.getParameter("state");
if (code == null) {
log.error("公众号用户登录,用户禁止未授权");
return new ModelAndView(new RedirectView(null), null);
}
// 获取到了code值,回调没有问题
// 定义地址
String token_url = BaseConstant.WX_ACCESS_TOKEN + appid +
"&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
//发送请求
ResponseEntity
//获取请求结果 json格式字符串
String content = responseEntity.getBody();
//把json字符串装对象
Token token = JSON.parseObject(content, Token.class);
String user_url = BaseConstant.WX_USER_INFO + token.getAccess_token() + "&openid=" + token.getOpenid();
ResponseEntity
String content1 = new String(responseEntity2.getBody().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
WeiXinUser wxUser = JSON.parseObject(content1, WeiXinUser.class);
Map
if (wxUser.getOpenid() == null) {
return null;
}
QueryWrapper
queryWrapper.eq("user_wx", wxUser.getOpenid());
User user2 = userService.getOne(queryWrapper);
//判断此用户是否存在数据库中
if (user2 == null) {
log.info("微信公众号用户登录,用户不存在数据库中,新建...");
User user1 = new User();
user1.setUserWx(wxUser.getOpenid());
user1.setUserNick(wxUser.getNickname());
user1.setUserHead(wxUser.getHeadimgurl());
user1.setUserSex(wxUser.getSex());
user1.setUserUnion(wxUser.getUnionid());
userService.save(user1);
log.info("公众号用户登录,用户新建成功!");
//构造返回
map.put("token", tokenService.getToken(user1));
map.put("user", user1.getUserPhone());
return new ModelAndView(new RedirectView(state), map);
} else {
log.info("公众号用户登录,用户存在数据库中,修改");
user2.setUserWx(wxUser.getOpenid());
user2.setUserNick(wxUser.getNickname());
user2.setUserHead(wxUser.getHeadimgurl());
user2.setUserUnion(wxUser.getUnionid());
userService.updateById(user2);
map.put("token", tokenService.getToken(user2));
map.put("user", user2.getUserPhone());
return new ModelAndView(new RedirectView(state), map);
}
}