Do not understand how third-party websites and apps access wechat login? Here I explain the third-party wechat login of single sign on (recommended Collection)

Keywords: Java Spring wechat

2021/9/3

1, Pre preparation

First, go to wechat open platform for developer qualification certification

Address: https://open.weixin.qq.com/
You must also understand Tencent's things (white whoring is impossible - > audit fee is required)

After passing the certification, three core parameters need to be recorded

1,appid
2,app
3,redirecturl

2, Wechat login process analysis

Document address: https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html

Step 1: request code

The function of this step is to initiate the wechat authorization login request. After the user confirms, wechat will redirect to the third-party application with the temporary bill code

After the user allows authorization, it will be redirected to redirect_uri, with code and state parameters (this redirect)_ Uri is the development domain name you filled in)

redirect_uri?code=CODE&state=STATE

Step 2: get access through code_ token

Add AppID and AppSecret through the code parameter, and exchange access through the API_ token;

{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE",
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}

The returned data is json data, so we can convert it into a map collection and get access to it_ The value of token (through Google's Gson package, others are OK)

Gson gson = new Gson();
HashMap mapResult = gson.fromJson(result, HashMap.class);
String accessToken = (String) mapResult.get("access_token");
String openId = (String) mapResult.get("openid");

Step 3: through access_token calling interface

This step is through credential access_token goes to wechat to obtain the information of the code scanning user


The value value is also obtained by converting to map format

HashMap<String, Object> mapUserInfo = gson.fromJson(userInfo, HashMap.class);
String nickname = (String) mapUserInfo.get("nickname");    
String avatar = (String) mapUserInfo.get("headimgurl");

3, Detailed explanation of interface core code

Tip: take Java code as an example

Note: some tool classes are used. For example, HttpClientUtils is used for remote calls, JwtUtils is a tool class using jwt, and some other codes will not be demonstrated

1. Write and generate wechat QR code interface

Since you want to log in through wechat, you must scan the QR code. It's ridiculous if you don't have a QR code. Write QR code interface,


Note the following baseUrl. You can use the method of splicing parameters in the above picture. If this method is used, the format code in the code can be omitted

String qrUrl =String.format(baseUrl,ConstantVxUtil.VX_APP_ID, redirectUrl, "zsh")

public String getQrConnect(HttpSession session) {
        // The wechat open platform authorizes baseUrl, which is fixed
//You can also splice parameters: https://open.../qrconnect?appid= Your appid & redirect_ uri=.....
//If you use the method of splicing parameters (similar to adding parameters to the path), you don't need the following String.format
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        String redirectUrl = ConstantVxUtil.VX_REDIRECT_URL;
        try {
       // Using utf-8 encoding
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String qrUrl = String.format(
                baseUrl,
                ConstantVxUtil.VX_APP_ID,
                redirectUrl,
                "zsh"
        );
        //Redirect to QR code address
        return "redirect:" + qrUrl;
    }

2. Write callback interface

After the user scans the code and clicks confirm login, this interface will be called. In this interface, the previously obtained code, appid and appsecret will be used to exchange the access certificate from wechat_ Token, and finally through access_token and appid go to wechat to obtain user information (that is, analyze access_token, which should be understood by all brothers who know single sign on)

	@GetMapping("callback") //Don't change this
    public String callback(String code, String state, HttpSession session) {
    //The following two lines of code are splicing parameters. You can also use a method similar to a path? a=1&b=2
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantVxUtil.VX_APP_ID,
                ConstantVxUtil.VX_APP_SECRET,
                code);
        String result = null;
        try {
            //Send a request to wechat (parameter: address) to obtain access_token
            result = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            throw new CommonException(40026, "accessToken Acquisition failed!");
        }
        //Parse the accessToken and convert it to the form of key value
        Gson gson = new Gson();
        HashMap mapResult = gson.fromJson(result, HashMap.class);
        String accessToken = (String) mapResult.get("access_token");
        String openId = (String) mapResult.get("openid");
        User user= userInfoService.getUserByOpenId(openId);
        //Judge whether it is the first time to log in using wechat. If it is not the first time, there is no need to store the information in the database
        //If you log in using wechat for the first time, the database stores
        if (user == null) {
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl,
                    accessToken,
                    openId);
            String userInfo = null;
            try {
                //To vx obtain user information according to the token
                userInfo = HttpClientUtils.get(userInfoUrl);
            } catch (Exception e) {
                throw new CommonException(20001, "getting information failure");
            }
            //Parse the user information and convert it into key value form to obtain the value value therein
            HashMap<String, Object> mapUserInfo = gson.fromJson(userInfo, HashMap.class);
            String nickname = (String) mapUserInfo.get("nickname");
            String avatar = (String) mapUserInfo.get("headimgurl");
            //Stored in database
            user= new User();
            user.setNickname(nickname).setAvatar(avatar).setOpenid(openId);
            userService.save(user);
        }
        String token = JwtUtils.getToken(user.getId(), user.getNickname());
        return "redirect:http://localhost:8555?token="+token;
    }

This article only describes two interface codes, and other related codes (front end, tool class, xml, etc.) will not be repeated. The picture in the article comes from the screenshot of wechat open platform

2021/9/3

Posted by remmargorp on Fri, 03 Sep 2021 15:29:38 -0700