其实,道理很简单.
首先,你要明白一个流程,
first,生成一个你想让用户同意授权的链接,并且通过这个链接能返回到用户同意后,你想处理数据的位置
second,你要明白不是谁点这个链接都有用,你是微信第三方授权,你需要微信用户点击链接才有用
third,用户同意之后,会返回code这个String
now,代码
pom依赖与我的微信公众号开发一样
生成链接
@RequestMapping("/aut")
public void authorize() {
//设置回调地址
WechatMpConfig w = new WechatMpConfig();
WxMpService wxMpService = w.wxMpService();//配置wxMpService,不会的去我别的文章看一下
String url = "http://2078e56f.ngrok.io/userInfo";//用户同意授权后,微信服务器返回用户信息的路径
String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
System.out.println("生成的授权链接:"+redirectUrl);
}
生成的的链接大概是酱的:
用下面的代码来接收并处理code
@RequestMapping("/userInfo")
public String userInfo(@RequestParam("code") String code) {
String result = "";
WechatMpConfig w = new WechatMpConfig();
WxMpService wxMpService = w.wxMpService();
try {
WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
boolean b = wxMpService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
String name = wxMpUser.getNickname();
System.out.println(wxMpUser.getCity()+"--"+wxMpUser.getHeadImgUrl()+"--"+wxMpUser.getCountry());
System.out.println(name);
System.out.println(b);
} catch (WxErrorException e) {
e.printStackTrace();
}
return result;
}