一、官方文档
地址
官方文档地址
接入流程
- 第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;
- 通过code参数加上AppID和AppSecret等,通过API换取access_token;
- 通过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操作。
第一步:(本人没做app端,故直接引用文档内容)
第二步:
示例代码
public void getAccessToken(String code) {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
Map<String, String> uriParams = new HashMap<>();
uriParams.put("appid", APP_ID);
uriParams.put("secret", APP_SECRET);
uriParams.put("grant_type", "authorization_code");
uriParams.put("code", code);
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, uriParams);
// 成功返回的样例
/*{
"access_token": "ACCESS_TOKEN",
"expires_in": 7200,
"refresh_token": "REFRESH_TOKEN",
"openid": "OPENID",
"scope": "SCOPE"
}*/
if (response != null && StringUtil.isNotEmpty(response.getBody())) {
JSONObject resJson = JSON.parseObject(response.getBody());
if (resJson.containsKey("access_token")) {
// TODO access_token等相关信息到数据库或者redis
}
}
}
第三步:
public void refreshToken() {
String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
Map<String, String> uriParams = new HashMap<>();
uriParams.put("appid", APP_ID);
uriParams.put("grant_type", "refresh_token");
// 填写通过 access_token 获取到的 refresh_token 参数
// 信息安全问题,应取redis或者数据库(access_token不存客户端)
uriParams.put("access_token", "");
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, uriParams);
// 成功返回样例
/*{
"access_token": "ACCESS_TOKEN",
"expires_in": 7200,
"refresh_token": "REFRESH_TOKEN",
"openid": "OPENID",
"scope": "SCOPE"
}*/
if (response != null && StringUtil.isNotEmpty(response.getBody())) {
JSONObject resJson = JSON.parseObject(response.getBody());
if (resJson.containsKey("access_token")) {
// TODO access_token等相关信息到数据库或者redis
}
}
}
第四步:获取个人信息,也是最终目的
@Override
public void getWxUserInfo(String openid) {
String url = "https://api.weixin.qq.com/sns/userinfo";
Map<String, String> uriParams = new HashMap<>();
// TODO 本系统应从redis获取access_token
uriParams.put("access_token", "");
uriParams.put("openid", openid);
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, uriParams);
// 成功返回样例
/*{
"openid": "OPENID",
"nickname": "NICKNAME",
"sex": 1,
"province": "PROVINCE",
"city": "CITY",
"country": "COUNTRY",
"headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
"privilege": ["PRIVILEGE1", "PRIVILEGE2"],
"unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
}*/
if (response != null && StringUtil.isNotEmpty(response.getBody())) {
JSONObject resJson = JSON.parseObject(response.getBody());
if (resJson.containsKey("nickname")) {
// TODO 得到个人信息后,拿unionid或者openid做自己系统用户表的关联来达到微信登陆的目的
}
}
}