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:

    https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect


0. Add callback domain web address to accept callback information

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

redirect_uri?code=CODE&state=STATE

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

`https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code`

Correct return:

{ 
"access_token":"ACCESS_TOKEN", 
"expires_in":7200, 
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID", 
"scope":"SCOPE",
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
parameterExplain
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;
@Component
@Data
@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 -->
<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>

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

@Slf4j
@Controller
public class WXController {
    @Autowired
    private WXConfig wxConfig;
​
    @ResponseBody
    @RequestMapping("/wx/login")
    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 +
                "&grant_type=authorization_code";
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
​
        HttpEntity entity = response.getEntity();
        String body = CommonUtil.getBody(entity.getContent());
        log.info(body);
        response.close();
​
        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);
        response.close();
        // 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