【第三方互联】十六、微信(wechat)授权第三方登录

第三方平台系列文章,今天终于又开始更新了,今天继续学习微信(wechat)授权第三方登录

一、准备工作

1、申请微信公众测试号

由于我们是个人开发者,我们需要去注册申请一个微信公众平台的测试号

https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

微信公众平台
我们使用微信扫码登录后,我们可以拿到 appID 和 appsecret

测试号管理

2、关注公众测试号

测试号二维码

3、配置回调域名

在“网页服务”中找到“网页账号”,修改“网页授权获取用户基本信息”接口的回调域名

修改接口信息
授权回调页面域名
注意:这里说的是,配置网页授权回调页面 域名,跟我们平常对接的第三方接口不一样,不用填写完整的回调地址,只是回调域名,回调地址在回调域名之下

  • 例如
    回调地址:http://www.baidu.com/wechat/back
    那么这里:baidu.com

新手一般在这里容易弄混,配置完成,点击“确认”即可

二、开始开发

1、获取应用信息

我们将获取到的 appID 和 appsecret 写在配置文件中,我这里是 SpringBoot 项目,我就放在 application.yml 文件中

配置信息

2、引入 maven 依赖

<!-- 网络请求 -->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.6</version>
</dependency>
<!-- alibaba的fastjson -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.51</version>
</dependency>

这里我们需要用到网络请求,和 JSON 对象的转换,所以我引入了 httpclient 和 fastjson,其余依赖请自行引入

3、从配置文件中获取 “wechat” 配置信息

/**
 * 公众平台提供的 appid 和 appsecret
 */
@Value("${wechat.oauth.appid}")
public String APPID;
@Value("${wechat.oauth.appsecret}")
public String APPKEY;
@Value("${wechat.oauth.callback}")
public String URL;

4、重定向到授权页面

/**
 * 请求授权页面
 */
@RequestMapping("/auth")
public String token(HttpSession session) throws Exception {
    
    
    // 用于第三方应用防止CSRF攻击
    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    session.setAttribute("state", uuid);
	// Step1:获取Authorization Code
    String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
            "appid=" + APPID +
            "&redirect_uri=" + URLEncoder.encode(URL) +
            "&response_type=code" +
            "&scope=snsapi_userinfo" +
            "&state=" + uuid +
            "#wechat_redirect";
    return PasswordUtils.redirectTo(url);
}
  • Step1 参数解释如下:
参数 是否必须 说明
appid 公众号的唯一标识
redirect_uri 授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理
response_type 返回类型,请填写code
scope 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
state 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
#wechat_redirect 无论直接打开还是做页面302重定向时候,必须带此参数

授权页面
这时,我们访问,便会出现授权页面

5、授权回调

/**
 * 授权回调
 */
@GetMapping(value = "/callback")
public void callback(HttpServletRequest request) throws Exception {
    
    
    HttpSession session = request.getSession();
    // 得到Authorization Code
    String code = request.getParameter("code");
    // 我们放在地址中的状态码
    String state = request.getParameter("state");
    String uuid = (String) session.getAttribute("state");

    // 验证信息我们发送的状态码
    if (null != uuid) {
    
    
        // 状态码不正确,直接返回登录页面
        if (!uuid.equals(state)) {
    
    
            return PasswordUtils.redirectTo("/login");
        }
    }

    // Step2:通过Authorization Code获取Access Token
    String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
            "appid=" + APPID +
            "&secret=" + APPKEY +
            "&code=" + code +
            "&grant_type=authorization_code";
    JSONObject resJson = HttpRequestUtils.httpRequestGet(url);
    if (null == resJson) {
    
    
        return PasswordUtils.redirectTo("/login");
    }
    String accessToken = resJson.getString("access_token");
    String openId = resJson.getString("openid");
    if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(openId)) {
    
    
        return PasswordUtils.redirectTo("/login");
    }

    url = "https://api.weixin.qq.com/sns/userinfo?" +
            "access_token=" + accessToken +
            "&openid=" + openId +
            "&lang=zh_CN";
    // Step3: 获取微信用户信息
    resJson = HttpRequestUtils.httpRequestGet(url);
    /**
     * TODO 这时就该写自己的业务逻辑了
     */
}
  • Step2 参数解释如下:
参数 是否必须 说明
appid 公众号的唯一标识
secret 公众号的appsecret
code 填写第一步获取的code参数
grant_type 填写为authorization_code
  • Step3 参数解释如下:
参数 是否必须 说明
access_token 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
openid 用户的唯一标识
lang 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语

6、网络请求方法

Step 2 和 Step 3 均为 GET 请求方式

/**
 * GET 请求
 */
public static JSONObject httpRequestGet(String url) throws IOException {
    
    
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
    
    
        String result = EntityUtils.toString(entity, "UTF-8");
        return JSONObject.parseObject(result);
    }
    httpGet.releaseConnection();
    return null;
}

三、文档资料

关于微信授权登录的文档地址如下:

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

四、总结

该授权认证过程符合 OAuth2 认证基本流程,对于应用而言,其流程由获取Authorization Code和通过Authorization Code获取Access Token这2步组成,如图所示:

OAuth授权认证

如您在阅读中发现不足,欢迎留言!!!

猜你喜欢

转载自blog.csdn.net/qq_40065776/article/details/109369262