http://blog.csdn.net/xiangjai/article/details/52804308
功能:主要用于在用户通过手机端微信访问第三方H5页面时获取用户的身份信息(openId,昵称,头像,所在地等。。)可用来实现微信登录、微信账号绑定、用户身份鉴权等功能。
开发前的准备:
1、需要有一个公众号,拿到AppID和AppSecret;2、进入公众号开发者中心页配置授权回调域名。具体位置:接口权限-网页服务-网页账号-网页授权获取用户基本信息-修改
注意,这里仅需填写全域名(如www.qq.com、www.baidu.com),勿加 http:// 等协议头及具体的地址字段;
本文以 lovebread.tunnel.qydev.com 域名为例:
3、如果嫌手机上测试麻烦,可以使用微信官方提供的web开发者工具直接在浏览器中进行调试。
前提是需要在微信公众号中绑定开发者账号:登录公众号-开发者工具-进入web开发者工具-绑定web开发者微信账号
使用说明及下载地址:https://mp.weixin.qq.com/wiki?action=doc&id=mp1455784140&t=0.7272727088156665&token=&lang=zh_CN#6
微信开发资料收集
https://github.com/liyiorg/weixin-popular
网页授权获取用户基本信息
- @Test
- public void testAuthenticationUrl(){
- String url = MpOAuth2s.defaultOAuth2s().authenticationUrl("http://wxtest.gzriver.com/oS-I8EwVL9X.view", "snsapi_userinfo");
- System.out.println(url);
- Assert.assertNotNull(url);
- }
@Test
public void testAuthenticationUrl(){
String url = MpOAuth2s.defaultOAuth2s().authenticationUrl("http://wxtest.gzriver.com/oS-I8EwVL9X.view", "snsapi_userinfo");
System.out.println(url);
Assert.assertNotNull(url);
}
通过转发形式微信验证页面
- @RequestMapping(value = { "/xxx" })
- public ModelAndView testOrder(HttpSession httpSession) {
- ModelAndView modelView = new ModelAndView();
- String url = MpOAuth2s.defaultOAuth2s().authenticationUrl(StringUtils.generateWechatAuthUrl("xxx"),
- "xxx");
- // 转到微信验证页面
- return new ModelAndView("redirect:" + url);
- }
@RequestMapping(value = { "/xxx" })
public ModelAndView testOrder(HttpSession httpSession) {
ModelAndView modelView = new ModelAndView();
String url = MpOAuth2s.defaultOAuth2s().authenticationUrl(StringUtils.generateWechatAuthUrl("xxx"),
"xxx");
// 转到微信验证页面
return new ModelAndView("redirect:" + url);
}
- {
- state = ,
- code = 011ARkch0yXcSC1zgUah07uhch0ARkcp
- }
{
state = ,
code = 011ARkch0yXcSC1zgUah07uhch0ARkcp
}
- 2 第二步:通过code换取网页授权access_token
-
- AccessToken accessToken = MpOAuth2s.defaultOAuth2s().getAccessToken(code);
AccessToken accessToken = MpOAuth2s.defaultOAuth2s().getAccessToken(code);
-
- 3 第三步:刷新access_token(如果需要)
-
- accessToken = MpOAuth2s.defaultOAuth2s().refreshToken(accessToken.getRefreshToken());
accessToken = MpOAuth2s.defaultOAuth2s().refreshToken(accessToken.getRefreshToken());
-
- 4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
-
- OpenUser openUser = MpOAuth2s.defaultOAuth2s().userInfo(accessToken.getAccessToken(), accessToken.getOpenId());
- logger.debug("openUser........................." + openUser.toString());
OpenUser openUser = MpOAuth2s.defaultOAuth2s().userInfo(accessToken.getAccessToken(), accessToken.getOpenId()); logger.debug("openUser........................." + openUser.toString());
- 5 附:检验授权凭证(access_token)是否有效