目录
3.4 拉取用户信息(需scope为 snsapi_userinfo)
1、前置条件
网页授权要求公众号是服务号,且完成认证才行。
2、微信公众平台配置及说明
2.1 网页授权回调域名
在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“设置与开发 - 公众
号设置 - 功能设置 - 网页授权域名”的配置选项中,修改授权回调域名。请注意,这里填写的是域名
(是一个字符串),而不是URL,因此请勿加 http:// 等协议头。
配置域名之前,将下面这个文档下载下来放到配置的域名可以访问到的位置。
2.2 获取AppID及AppSecret
公众平台官网中的“设置与开发 - 基本配置 ”的公众号开发信息中获取,注意AppSecret只有第
一次保存机会,如果未能及时保存,那就需要重置获取。
2.3 特殊说明
个人开发者申请微信公众号测试号进行开发,微信公众号测试号申请系统网址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
进入步骤:
1、打开微信公众平台首页:https://mp.weixin.qq.com/
2、选择服务号开发文档
3、开始开发 - 接口测试号申请
3、对接步骤
具体而言,网页授权流程分为四步:
1、引导用户进入授权页面同意授权,获取code
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)
3.1 用户同意授权,获取code
在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口
后,默认拥有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开如下页面:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。
参数说明:
参数 | 是否必须 | 说明 |
---|---|---|
appid | 是 | 公众号的唯一标识 |
redirect_uri | 是 | 授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理 |
response_type | 是 | 返回类型,请填写code |
scope | 是 | 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 ) |
state | 否 | 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节 |
#wechat_redirect | 是 | 无论直接打开还是做页面302重定向时候,必须带此参数 |
如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。
3.2 通过code换取网页授权access_token
这里通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token(该
access_token用于调用其他接口)不同。公众号可通过下述接口来获取网页授权access_token。
如果网页授权的作用域为snsapi_base,则本步骤中获取到网页授权access_token的同时,也获取
到了openid,snsapi_base式的网页授权流程即到此为止。
获取code后,请求以下链接获取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
参数说明
参数 | 是否必须 | 说明 |
---|---|---|
appid | 是 | 公众号的唯一标识 |
secret | 是 | 公众号的appsecret |
code | 是 | 填写第一步获取的code参数 |
grant_type | 是 | 填写为authorization_code |
返回说明
正确时返回的JSON数据包如下:
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}
参数 | 描述 |
---|---|
access_token | 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 |
expires_in | access_token接口调用凭证超时时间,单位(秒) |
refresh_token | 用户刷新access_token |
openid | 用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID |
scope | 用户授权的作用域,使用逗号(,)分隔 |
3.3 刷新access_token(如果需要)
请求方法
获取第二步的refresh_token后,请求以下链接获取access_token: https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
参数 | 是否必须 | 说明 |
---|---|---|
appid | 是 | 公众号的唯一标识 |
grant_type | 是 | 填写为refresh_token |
refresh_token | 是 | 填写通过access_token获取到的refresh_token参数 |
返回说明
正确时返回的JSON数据包如下:
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}
参数 | 描述 |
---|---|
access_token | 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 |
expires_in | access_token接口调用凭证超时时间,单位(秒) |
refresh_token | 用户刷新access_token |
openid | 用户唯一标识 |
scope | 用户授权的作用域,使用逗号(,)分隔 |
3.4 拉取用户信息(需scope为 snsapi_userinfo)
如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。
请求方法
http:GET(请使用https协议) https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
参数说明
参数 | 描述 |
---|---|
access_token | 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 |
openid | 用户的唯一标识 |
lang | 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 |
返回说明
正确时返回的JSON数据包如下:
{
"openid": "OPENID",
"nickname": NICKNAME,
"sex": 1,
"province":"PROVINCE",
"city":"CITY",
"country":"COUNTRY",
"headimgurl":"https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
"privilege":[ "PRIVILEGE1" "PRIVILEGE2" ],
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
参数 | 描述 |
---|---|
openid | 用户的唯一标识 |
nickname | 用户昵称 |
sex | 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知 |
province | 用户个人资料填写的省份 |
city | 普通用户个人资料填写的城市 |
country | 国家,如中国为CN |
headimgurl | 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。 |
privilege | 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom) |
unionid | 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。 |
4、示例代码
http请求工具类
package com.qdeicc.bigscreen.util;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Slf4j
public class HttpClientUtil {
public static String doGet(String url, Map<String, String> param) {
log.info("调用第三方接口开始,接口地址:" + url + ",调用参数:" + JSONObject.toJSONString(param));
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String result = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
log.error("调用第三方接口出现异常,接口地址:" + url + ",调用参数:" + JSONObject.toJSONString(param) + ",异常信息:" + e);
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
log.error("系统错误:", e);
}
}
log.info("调用第三方接口技术,接口地址:" + url + ",调用参数:" + JSONObject.toJSONString(param) + ",返回结果:" + result);
return result;
}
public static String doGet(String url, Map<String, String> headMap, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
if (headMap != null && !headMap.isEmpty()) {
for (String key : headMap.keySet()) {
log.info("头部信息key:" + key + "===值: " + headMap.get(key));
httpGet.addHeader(key, headMap.get(key));
}
}
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
log.error("系统错误:", e);
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
log.error("系统错误:", e);
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> headers, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
log.info("调用第三方接口开始,接口地址:" + url + ",调用参数:" + JSONObject.toJSONString(param) + ",调用header:" + JSONObject.toJSONString(headers));
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
if (headers != null) {
for (String key : headers.keySet()) {
httpPost.setHeader(key, headers.get(key));
}
}
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
log.error("调用第三方接口出现异常,接口地址:" + url + ",调用参数:" + JSONObject.toJSONString(param) + ",异常信息:" + e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error("系统错误:", e);
}
}
log.info("调用第三方接口技术,接口地址:" + url + ",调用参数:" + JSONObject.toJSONString(param) + ",返回结果:" + resultString);
return resultString;
}
}
@GetMapping("/code2accesstoken")
public void code2accesstoken(tring code, String state) throws Exception {
String appid = "appid";
String secret = "secret";
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid +
"&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
String result = HttpClientUtil.doGet(url);
JSONObject jsonObject = JSONObject.parseObject(result);
// WxOAuth2AccessToken wxOAuth2AccessToken = JSONObject.parseObject(result, WxOAuth2AccessToken.class);
String accessToken = jsonObject.getString("access_token");
String openId = jsonObject.getString("openid");
String scope = jsonObject.getString("scope");
String unionid = jsonObject.getString("unionid");
if ("snsapi_userinfo".equals(scope)) {
String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
String userResult = HttpClientUtil.doGet(url);
WxOAuth2UserInfo wxOAuth2UserInfo = JSONObject.parseObject(userResult, WxOAuth2UserInfo.class);
// 获取头像等用户信息
String headimgurl = wxOAuth2UserInfo.getHeadImgUrl();
}
}
将3.1中的redirect_uri参数替换为http://xx.com/code2accesstoken即可。
参考文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#4