forked from chanjarster/weixin-java-tools
-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
MP_OAuth2网页授权
qianzzbatt edited this page Nov 20, 2020
·
19 revisions
首先构造网页授权url,然后构成超链接让用户点击:
WxMpService wxMpService = ...;
String url = ...;
wxMpService.getOauth2Service().buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null)
当用户同意授权后,会回调所设置的url并把authorization code传过来,然后用这个code获得access token,其中也包含用户的openid等信息
WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
WxMpUser wxMpUser = wxMpService.getOauth2Service().getUserInfo(wxMpOAuth2AccessToken, null);
wxMpOAuth2AccessToken = wxMpService.getOauth2Service().refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
boolean valid = wxMpService.getOauth2Service().validateAccessToken(wxMpOAuth2AccessToken);
String encType = request.getParameter("encrypt_type");
String nonce = request.getParameter("nonce");
String timestamp = request.getParameter("timestamp");
String msgSignature = request.getParameter("msg_signature");
String signature = request.getParameter("signature");
String openid = request.getParameter("openid");
log.info("接收微信请求:[openid=[{}], [openid=[{}],[signature=[{}], encType=[{}], msgSignature=[{}],"
+ " timestamp=[{}], nonce=[{}], requestBody=[{}] ",
appid, openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
if (!this.wxMpService.switchover(appid)) {
throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
}
if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
throw new IllegalArgumentException("非法请求,可能属于伪造的请求!");
}
return ResponseEntity.ok("");