Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.


Recently, I have used some wechat open platforms to authorize third parties to log in and obtain users’ basic information. I have a look at the official document provided by wechat. It has been written in great detail. Here I summarize it according to my own steps and attach some examples for your understanding.

The process of authorization for a third party by wechat public account can be divided into the following four steps:

  1. User agrees to authorize, obtaincode
  2. Exchange web page authorization through codeaccess_token
  3. The refreshaccess_token(Optional)
  4. Pull user information (requiredscopeforsnsapi_userinfo)

In a normal process, the third step is not necessary. It is only used when the Access_token is invalid. The following steps are detailed.

1. Get the code

The official interfaces are as follows:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE &state=STATE&connect_redirect=1#wechat_redirectCopy the code

After the user confirms the authorized login, the redirect_URI address is redirected, and the code parameter generated in the background of wechat is added. The code can be saved in the front end for obtaining the access_token.

Parameter Description:

parameter Must be instructions
appid is The unique identifier of the public account
redirect_uri is A callback link address redirected after authorization needs to be processed using urlEncode
response_type is Return type, please fill in code
scope is Apply the authorization scope, snSAPi_BASE or SNSAPi_userinfo
state no After the redirect, the state parameter will be added. The developer can fill in the value of the a-zA-Z0-9 parameter, which is up to 128 bytes
#wechat_redirect is This parameter must be set when you open the page directly or perform page 302 redirection

Examples of back-end code:

@Controller
@RequestMapping("wechat")
public class WeChatContraller {
    @GetMapping("authorization")
    public String authorization(a) throws UnsupportedEncodingException {
        return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?"
                + "? appid=" + WeChatUtil.appid + "&redirect_uri="
                + URLEncoder.encode(WeChatUtil.DomainName + "/index.html"."UTF-8")
                + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect"; }}Copy the code

It should be noted that due to the high security level of authorization operation, wechat will perform regular strong match verification on the authorization link when the authorization request is initiated. If the parameters of the link are not in the correct order, the authorization page cannot be accessed normally.

In addition, when the application authorization scope is snSAPi_BASE, the authorization page is not displayed but the user openID can be obtained directly. When snSAPi_userinfo is displayed, the authorization page will pop up. You can obtain the nickname, gender, and location through OpenID. And, even in the absence of attention, as long as the user’s authorization, can also access their information.

2. Obtain access_token

Here, code is exchanged for a special web page authorization access_token. The official interface is as follows:

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

Parameter Description:

parameter Must be instructions
appid is The unique identifier of the public account
secret is The official account appSecret
code is Fill in the code parameter obtained in the first step
grant_type is Fill in for authorization_code

Examples of back-end code:

@ResponseBody
@GetMapping("getToken")
public String getToken(@RequestParam(name = "code") String code) {
    String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
           + "? appid=" + WeChatUtil.appid + "&secret=" + WeChatUtil.appsecret
           + "&code=" + code + "&grant_type=authorization_code";
    String rs = HttpSendUtil.get(url, null);
    JSONObject json = JSONObject.parseObject(rs);
    
    if(null == json.get("errcode")) {return json.get("access_token").toString();        
    }else{
        return "Error obtaining access_token"; }}Copy the code

Here the HttpClient is used to send a GET request to retrieve the Access_token from the returned JSON. The complete JSON packet returned correctly is as follows:

{
  "access_token":"ACCESS_TOKEN"."expires_in":7200."refresh_token":"REFRESH_TOKEN"."openid":"OPENID"."scope":"SCOPE" 
}
Copy the code

Parameter description:

parameter instructions
access_token The web page authorization interface invokes credentials. Note: This access_token is different from the access_token supported by the base
expires_in Timeout time for access_token interface to call credentials, in seconds
refresh_token The access_token was refreshed. Procedure
openid Unique user identification
scope Scope of user authorization, separated by commas (,)

In case of error, wechat will return JSON packet as follows (example: invalid code error) :

{
  "errcode":40029."errmsg":"invalid code"
}
Copy the code

Note that code can only be used once. A second request to obtain the access_token with the same code after being consumed will fail.

3. Refresh access_token (optional)

The access_token has a validity period. When the timeout expires, refresh_token can be used to refresh the access_token, requiring user re-authorization.

https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
Copy the code

Parameter Description:

parameter Must be instructions
appid is The unique identifier of the public account
grant_type is Fill in the refresh_token
refresh_token is Enter the refresh_token parameter obtained by access_token

If correct, the returned JSON packet is in the same format as that obtained directly:

{ 
  "access_token":"ACCESS_TOKEN"."expires_in":7200."refresh_token":"REFRESH_TOKEN"."openid":"OPENID"."scope":"SCOPE" 
}
Copy the code

4. Pull user information

If the web page authorization scope is snSAPi_userinfo, then the developer can pull user information using access_token and OpenID.

https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
Copy the code

Parameter Description:

parameter Must be instructions
access_token is The web page authorization interface invokes credentials. Note: This access_token is different from the access_token supported by the base
openid is Unique identification of a user
lang is Return country language version, zh_CN simplified, zh_TW traditional, en English

Examples of back-end code:

@ResponseBody
@GetMapping("getUserInfo")
public JSONObject getUserInfo(@RequestParam(name = "accessToken") String accessToken,
                          @RequestParam(name = "openid") String openid) {
    String url = "https://api.weixin.qq.com/sns/userinfo?"
            + "? access_token=" + accessToken + "&openid=" +openid
            + "&lang=zh_CN";

    String rs = HttpSendUtil.get(url, null);
    JSONObject json = JSONObject.parseObject(rs);
    
    return json;
}
Copy the code

If correct, the following JSON packet is returned:

{   
  "openid":" OPENID"."nickname": NICKNAME,
  "sex":"1"."province":"PROVINCE"."city":"CITY"."country":"COUNTRY"."headimgurl":"http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavH iaiceqxibJxCfHe/46"."privilege": ["PRIVILEGE1" "PRIVILEGE2"]."unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
Copy the code

Parameter description:

parameter instructions
openid Unique identification of a user
nickname The user nickname
sex Gender of the user. If the value is 1, it is male, if the value is 2, it is female, and if the value is 0, it is unknown
province The province in which the user’s personal information is filled in
city The city where the personal information of ordinary users is filled in
country Countries, such as China, are CN
headimgurl The avatars
privilege User privilege information, JSON array
unionid This field will only appear after the user binds the public account to the wechat open platform account

In case of error, wechat will return JSON packet as follows (example: OpenID is invalid) :

{  
  "errcode":40003."errmsg":" invalid openid "
}
Copy the code

It should be noted that the secret and access_token obtained by the public account are of very high security level, which can only be saved on the server and cannot be transmitted to the client. The subsequent steps, such as refreshing the access_token and obtaining user information through the access_token, must also be initiated from the server.

In general, wechat open platform authorization login this piece of function application of OAuth2 authorization code mode, if you understand OAuth2, this piece of content will be very easy to understand, if not familiar, you can move to take a look at this article: OAuth2.0 authorization code mode combat, I hope to help you.

The last

If you think it is helpful, you can like it and forward it. Thank you very much

Public number agriculture ginseng, add a friend, do a thumbs-up friend ah