电脑端微信授权登录逻辑
一、用户点击授权后先跳转到本地的后台服务器,然后响应302跳转,重定向到微信服务器。
@Override
public void oAuth2RedirectURL(OAuthApiDto oAuthApiDto, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
String weixin_auth_url = MessageFormat.format(weixin_auth_url_format, oAuthApiDto.getState(),
oAuthApiDto.getCallbackUrl());
httpServletResponse.setStatus(HttpStatus.SC_MOVED_TEMPORARILY);
httpServletResponse.setHeader("location", weixin_auth_url);
}
二、用户扫码之后,微信将浏览器重定向到TOPPGO,然后进行回调,TOPPGO获取用户的基本信息,根据unionid判单用户是否存在,没有注册,有直接获取信息且生成将要登陆的链接
String code = httpServletRequest.getParameter("code");
String token_url = MessageFormat.format(token_url_format, code);
System.out.println(token_url);
String result = JsoupUtils.getDocumentUseGet(token_url);
try {
JSONObject jonJsonObject = JSONObject.parseObject(result);
String unionid = jonJsonObject.getString("unionid");
String openid = jonJsonObject.getString("openid");
LOGGER.info("openid:{},unionid:{}", openid, unionid);
User userDb = userService.findUserByOpenidOrUnionid(openid, unionid);
if (userDb != null) {
// 直接跳转开始进行登录
redirect2WxLoginAction(unionid, httpServletRequest, httpServletResponse);
} else {
String ip = IPUtils.getIP(httpServletRequest);
User user = new User();
user.setRegistIp(ip);
user.setWechatOpenid(unionid);
// 新增用户的注册来源
user.setFromType(FromType.WECHAT4PC);
userService.save(user, null);
// 开始跳转登录
redirect2WxLoginAction(unionid, httpServletRequest, httpServletResponse);
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
LOGGER.info("result:" + JSONObject.toJSONString(result));
}
三、根据重定向的链接和目的的URL,浏览器重定向,直接登录。
String targetServer = auhtorServer;
String state = httpServletRequest.getParameter("state");
if (StringUtils.isNotBlank(state)) {
if (state.contains(OAuth2AuthController.stateSplitCharacter)) {
String[] stateSplits = state.split(OAuth2AuthController.stateSplitCharacter);
if (stateSplits.length > 1) {
String targetDomain = stateSplits[1];
if (targetDomain.startsWith("http")) {
targetServer = targetDomain;
} else {
targetServer = "http://" + targetDomain;
}
}
}
}
String redirectUrl = MessageFormat.format("{0}/subject/wxRedirect?token=@WX@{1}&wxRedirect={2}", targetServer, unionid,
targetServer);
//返回freemark页面
httpServletResponse.setContentType("text/html;charset=utf-8");
Template template = configuration.getTemplate("/wxAuth.ftl");
Map<String,Object> dateModel = Maps.newHashMap();
dateModel.put("redirectUrl", redirectUrl);
template.process(dateModel, httpServletResponse.getWriter());