springboot WeChat Login

Advantages of WeChat Login

At present, there are a large number of WeChat users, who prefer to sign in faster and easier than the traditional account password.

springboot Access WeChat Login

Dead work

Web site application WeChat login is a Microsoft OAuth2.0 authorized login system based on OAuth2.0 protocol standard. Before authorizing Wechat OAuth2.0 login access, register the developer account in the Wechat Open Platform, have a website application approved, obtain the corresponding AppID and AppSecret, apply for Wechat login and pass the audit, then start the access process.

To put it plainly, you need an AppID and a corresponding Appsecret

Port: WeChat Open Platform (qq.com)

Select one after login, here is the website application

By the way, change the callback field again.

Authorization process

So what are we going to do?

Set up a link to let the user jump to the WeChat login scanner interface, and then the user's point confirmation will redirect with code and state to the callback domain we set. This is how we access WeChat with code to get some basic information of the user and access_token refresh_token, with token, we can get user-specific information. At this point, we can set up session to let the user log in successfully.

  1. Open Link

    Set up a link in the following format:


0. Add callback domain web address to accept callback information

After user authorization, it will be redirected to the callback domain.


And then we get it code,Visit link acquisition later access_token


Correct return:

"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
access_tokenInterface call credentials (what we need)
expires_inAccess_ The token interface calls a credential timeout in seconds, usually two hours
refresh_tokenUser Refresh access_token
openidAuthorized User Unique ID, unique for current appid
scopeUser authorized scopes, separated by commas (,)
unionidThis field will only appear if and only if the site application has been authorized by the user's userinfo.
  1. Get user details

    Continue visiting https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID Now you can get the user's details

Actual operation

1. Configuration of appId and appSecret

Configuration in application.yml:

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

2. Set up a web address

3. Set callback domain

Guide Pack

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->

Tool class

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();

Callback Domain Logic

public class WXController {
    private WXConfig wxConfig;
    public String login(HttpServletRequest request) throws IOException {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        if (code == null){
            log.error("User Cancel Logon");
        log.info("code = {}", code);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + wxConfig.getAppId() +
                "&secret=" + wxConfig.getAppSecret() +
                "&code=" + code +
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String body = CommonUtil.getBody(entity.getContent());
        JSONObject bodyJson = JSON.parseObject(body);
        // Now that you have some information about the user, you can query it in the database. If you have already recorded it, there is no need to go to the next step.
        String accessToken = bodyJson.getString("access_token");
        String openId = bodyJson.getString("openId");
        url = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + accessToken +
                "&openid=" + openId;
        httpGet = new HttpGet(url);
        response = httpClient.execute(httpGet);
        body = CommonUtil.getBody(response.getEntity().getContent());
        bodyJson = JSON.parseObject(body);
        // Store user information after it is retrieved
        log.info("the info of user is {}", bodyJson);
        // Logon successful, session set
        request.getSession().setAttribute("unionId", bodyJson.getString("union_id"));
        return "Login Successful";


Tags: Java Spring Boot Back-end wechat

Posted on Thu, 21 Oct 2021 14:53:13 -0400 by saeed42