springboot微信登陆

微信登录的优势

springboot 接入微信登陆

准备工作

说白了就是需要一个AppID和对应的Appsecret 传送门: 登陆后选一个,这里是网站应用 顺便再把回调域改一下。

授权流程

那我们要做什么呢?

  1. 打开链接 设置一个链接,格式如下:

0. 添加回调域网址接受回调信息

正确的返回:

{ 
"access_token":"ACCESS_TOKEN", 
"expires_in":7200, 
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID", 
"scope":"SCOPE",
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
参数 说明 access_token 接口调用凭证(我们需要的) expires_in access_token接口调用凭证超时时间,单位(秒),一般是两小时 refresh_token 用户刷新access_token openid 授权用户唯一标识,对于当前appid是唯一的 scope 用户授权的作用域,使用逗号(,)分隔 unionid 当且仅当该网站应用已获得该用户的userinfo授权时,才会出现该字段。
  1. 获取用户详细信息 继续访问就可以获取用户的详细信息了

实际操作

1. appId和appSecret的配置

在application.yml的配置:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@Data
@ConfigurationProperties(prefix = "wx")
public class WXConfig {
    private String appId;
    private String appSecret;
}

2. 设置网址

3. 设置回调域

导包
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.78</version>
</dependency>
工具类
public class CommonUtil {
    private static final int BUFFER_SIZE = 1024 * 8;
    public static String getBody(InputStream inputStream) throws IOException {
        Reader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringWriter writer = new StringWriter();
        int read;
        char[] buf = new char[BUFFER_SIZE];
        while ((read = reader.read(buf)) != -1) {
            writer.write(buf, 0, read);
        }
        return writer.getBuffer().toString();
    }
}
回调域逻辑

经验分享 程序员 微信小程序 职场和发展