获取openid
1.引入依赖weixin-java-mp
2.构造网页授权
@GetMapping("/authorize")
public String authorize(@RequestParam("returnUrl") String returnUrl) {
//1. 配置WxMpService
//2. 调用方法
String url = projectUrlConfig.getWechatMpAuthorize() + "/sell/wechat/userInfo";
String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_BASE, URLEncoder.encode(returnUrl));
return "redirect:" + redirectUrl;
}
@GetMapping("/userInfo")
public String userInfo(@RequestParam("code") String code,
@RequestParam("state") String returnUrl) {
WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
try {
wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
} catch (WxErrorException e) {
log.error("【微信网页授权】{}", e);
throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg());
}
//拿到openid
String openId = wxMpOAuth2AccessToken.getOpenId();
return "redirect:" + returnUrl + "?openid=" + openId;
}
微信网页授权
访问项目的时候会重定向到wechat/authorize(在前端项目中需要配置项目地址...sell.com和获取openid的地址...wechat/authorize)
成功的话会提示请在微信客户端打开链接
电脑可以直接访问sell.com(有相应配置host,域名直接指向了虚拟机)
手机要访问sell.com的话,要在手机上配置http代理,填写电脑的ip(在无线局域网中),端口8888