微信h5页面的授权登录,首先你要申请一个测试公众号
在配置里的网页服务-网页账号输入自己的ip地址+端口,如127.0.0.1:8080
第一步:前端拉起授权,用户同意,获取code,前端直接调用下边链接即可拉起授权
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
成功之后会回调到你写的redirect_uri地址,注意一点,这里的redirect_uri要和你在测试号里配置的一直,不然会一直报错
第二步:通过 code 换取网页授权access_token
前端通过接口把获取到的token传给后端,后端再调用以下链接,获取access_token和openid
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
public static JSONObject getAccessTokenOpenId(String code) throws IOException {
String params = "https://api.weixin.qq.com/sns/oauth2/access_token" +
"?appid=" + WX_APPID +
"&secret=" + AppSecret +
"&code=" + code +
"&grant_type=authorization_code";
GetMethod getMethod = new GetMethod(params);
HttpClient client = new HttpClient();
client.executeMethod(getMethod);
if (getMethod.getStatusCode() == 200) {
String responseBodyAsString = getMethod.getResponseBodyAsString();
getMethod.releaseConnection();
return JSONObject.parseObject(responseBodyAsString);
}
return null;
}
这里的HttpClient是org.apache.commons.httpclient包下的方法,微信的接口调用成功后会返回一个json对象,java里解析一下就能拿到
第三步:拉取用户信息
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
public static JSONObject getUserInfo(String code) throws IOException {
JSONObject jsonObject = getAccessTokenOpenId(code);
if (jsonObject == null) return null;
if (!StringUtils.isEmpty(jsonObject.getString("errcode"))){
return jsonObject;
}
String params = "https://api.weixin.qq.com/sns/userinfo" +
"?access_token=" + jsonObject.getString("access_token") +
"&openid=" + jsonObject.getString("openid") +
"&lang=zh_CN";
GetMethod getMethod = new GetMethod(params);
HttpClient client = new HttpClient();
client.executeMethod(getMethod);
if (getMethod.getStatusCode() == 200) {
String responseBodyAsString = getMethod.getResponseBodyAsString();
JSONObject jsonObject2 = JSONObject.parseObject(responseBodyAsString);
getMethod.releaseConnection();
return jsonObject2;
}
return null;
}
通过上个方法 获取到openid和access_token再调用userinfo链接 ,获取当前用户的信息。结果如下