本文内容基本按照官方文档,若想直接看官方文档,可直接点击查看:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
1、测试账号准备工作
(1)点击链接(https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index)。使用微信客户端扫码登录即可。
说明:如果自身已存在已认证的微信公众号,可直接使用自己的公众进行开发。
(2)关注公众号
(3)修改回调地址
在网页服务中,找到“网页授权获取用户基本信息”,点击“修改”,填写回调域名,直接填域名即可。
出现如下检测通过说明域名可用
关于网页授权回调域名的说明
1、在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;
2、授权回调域名配置规范为全域名,比如需要网页授权的域名为:www.qq.com,配置以后此域名下面的页面http://www.qq.com/music.html 、 http://www.qq.com/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq.com 、 http://music.qq.com 、 http://qq.com 无法进行OAuth2.0鉴权
3、如果公众号登录授权给了第三方开发者来进行管理,则不必做任何设置,由第三方代替公众号实现网页授权即可
2、开发流程
1 第一步:用户同意授权,获取code
2 第二步:通过code换取网页授权access_token
3 第三步:刷新access_token(如果需要)
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
直接撸代码:
说明:示例代码后台使用SpringMvc
@RequestMapping(params = "getWxCode", method = RequestMethod.GET)
public String wxLogin(HttpServletRequest request, HttpServletResponse response) throws ParseException {
// 这个url的域名必须要进行再公众号中进行注册验证,这个地址是成功后的回调地址
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID
+ "&redirect_uri=" + REDIRECT_URI
+ "&response_type=code"
+ "&scope=snsapi_userinfo&state=2&connect_redirect=1#wechat_redirect";
return "redirect:" + url;// 必须重定向,否则不能成功
}
其中
@RequestMapping(params = "callBack", method = RequestMethod.GET)
public void callBack(ModelMap modelMap, HttpServletRequest req, HttpServletResponse resp) {
// 开始获取微信用户的基本信息
// 获取code
String code = req.getParameter("code");
logger.info("code:" + code);
// 通过code换取网页授权access_token
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WeiXinUtil.APPID
+ "&secret=" + WeiXinUtil.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
logger.info("获取Access_token地址:" + url);
JSONObject jsonObject = doGetJson(url);
logger.info("回调函数返回内容:" + jsonObject);
String openid = jsonObject.getString("openid");
String access_token = jsonObject.getString("access_token");
String refresh_token = jsonObject.getString("refresh_token");
// 验证access_token是否失效;展示都不需要
String chickUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
JSONObject chickuserInfo = doGetJson(chickUrl);
logger.info("验证结果:" + chickuserInfo.toString());
if(!"0".equals(chickuserInfo.getString("errcode"))){
String refreshTokenUrl="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="
+ openid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
JSONObject refreshInfo = doGetJson(refreshTokenUrl);
logger.info(refreshInfo.toString());
access_token = refreshInfo.getString("access_token");
}
// 获取用户信息(需scope为 snsapi_userinfo)
String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="
+ access_token
+ "&openid=" + openid
+ "&lang=zh_CN";
logger.info("infoUrl:"+infoUrl);
JSONObject userInfo = doGetJson(infoUrl);
logger.info("用户基本信息:" + userInfo);
}
其中doGetJson方法是通过网页获取网页返回的json值:以下为参考,可使用其他方式
public static JSONObject doGetJson(String url) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// // 发送请求参数
// out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
JSONObject jsonObject = JSON.parseObject(result);
return jsonObject;
} catch (Exception e) {
logger.error("获取失败:" + e.getMessage());
}
return null;
}
如有不正确的地方欢迎随时指出,感恩。