解决vue路由hash模式下,微信网页授权问题
程序员文章站
2024-01-09 22:29:10
...
解决vue路由hash模式下,微信网页授权问题
本人开发负责微信公众号端,菜单都是自定义菜单,然后每个菜单路径都是经过授权如:
http://xxxx.com/ceshi/wechat/authorize?returnUrl=http://xxxx.com/charge/#/setParameters
经过后台授权后返回给前端页面拼接当前用户的openidhttp://xxxx.com/charge/#/setParameters?openid=xxxxxxxx
这样进行注册,登录都可以传递openid让前端可以获取openid来关联微信账户信息.
理想状态是这样的,然而实验后发现,.微信授权返回的returnurl,会把路径截取成http://xxxx.com/charge/
这样的重定向后,前端那边处理直接跳转到登录接口了,然后看了很多的解决方案,有跳转空白页面,来location.href真正的路径的.这边我的解决方案就是自定义菜单路径是先忽略掉#,比如之前的http://xxxx.com/ceshi/wechat/authorize?returnUrl=http://xxxx.com/charge/#/setParameters
改正后returnUrl=http://xxxx.com/charge/setParameters
然后后台这边再把路径进行重新拼接#号,以下为代码片段帮助理解.
WxMenuButton button1 = new WxMenuButton();
button1.setName("充值");
WxMenuButton button11 = new WxMenuButton();
button11.setType(MenuButtonType.VIEW);
button11.setName("充值");
button11.setUrl("http://xxxx.com/ceshi/wechat/authorize?returnUrl=http://xxxx.com/charge/home");
WxMenuButton button12 = new WxMenuButton();
button12.setType(MenuButtonType.VIEW);
button12.setName("充值历史记录");
button12.setUrl("http://xxxx.com/ceshi/wechat/authorize?returnUrl=http://xxxx.com/charge/operationRecord");
@RequestMapping(value = "authorize",method = RequestMethod.GET)
public String authorize(@RequestParam("returnUrl") String returnUrl) throws Exception{
String url=config.getRealmName()+"/ceshi/wechat/userInfo";
String redirectUrl=wxMpService.oauth2buildAuthorizationUrl(url,WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl,
"UTF-8"));
logger.info("【微信网页授权】获取code,redirectUrl={}",redirectUrl);
return "redirect:"+redirectUrl;//重定向到下面一个方法
}
@RequestMapping(value = "userInfo",method = RequestMethod.GET)
public String userInfo(@RequestParam("code") String code,
@RequestParam("state") String returnUrl){
WxMpOAuth2AccessToken wxMpOAuth2AccessToken=new WxMpOAuth2AccessToken();
try {
wxMpOAuth2AccessToken=wxMpService.oauth2getAccessToken(code);
}catch (WxErrorException e){
logger.error("【微信网页授权】,{}",e);
}
String openId=wxMpOAuth2AccessToken.getOpenId();
logger.info("【微信网页授权】获取openid,returnUrl={}",returnUrl);
try {
WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
//TODO 保存授权用户信息
} catch (WxErrorException e) {
logger.info("【微信网页授权】获取用户信息异常={}",e.getError());
}
String[] split = returnUrl.split("/charge/");
String url = "http://xxxx.com/charge/#/"+split[1];
return "redirect:"+ url+"?openid="+openId;
}
上一篇: 面部识别:商机与风险并存