WeChat applet authorization login details

 


 
 

  

process

WeChat applet login flow chart
illustrate

  • Call wx.login() to obtain the temporary login credential code and send it back to the developer server.
  • Call the auth.code2Session interface in exchange for the user's unique identifier OpenID , the user's unique identifier UnionID under the WeChat open platform account (if the current mini program has been bound to the WeChat open platform account) and the session key session_key .

Afterwards, the developer server can generate a custom login status according to the user ID, which is used to identify the user's identity during the front-end and back-end interactions in the subsequent business logic.

Precautions

  1. Session key session_key is the key for cryptographically signing user data. In order to protect the application's own data, the developer server should not deliver the session key to the applet , nor should it provide this key to the outside world.
  2. The temporary login credential code can only be used once

 
 

 
 

wx.login()

official document

Call the interface to obtain the login credentials (code). Use the credentials to exchange for user login status information, including the user's unique identifier (openid) in the current Mini Program, the unique identifier under the WeChat Open Platform account (unionid, if the current Mini Program has been bound to the WeChat Open Platform account) and this login The session key (session_key), etc. The encryption and decryption communication of user data needs to rely on the session key to complete.

parameter

Attributes type Defaults required illustrate
timeout number no Timeout time, unit ms Timeout time, unit ms
success function no Callback function for successful interface call
fail function no Callback function for interface call failure
complete function no The callback function of the end of the interface call (the call will be executed successfully or failed)

 

success callback function

Attributes type illustrate
code string User login credentials ( valid for five minutes ). The developer needs to call auth.code2Session in the background of the developer server, and use the code to exchange openid, unionid, session_key and other information

 

wx.login({
    
    
  success (res) {
    
    
    if (res.code) {
    
    
      //发起网络请求
      wx.request({
    
    
        url: 'https://example.com/onLogin',//开发的后台地址,传输code获取openid登录信息
        data: {
    
    
          code: res.code
        }
      })
    } else {
    
    
      console.log('登录失败!' + res.errMsg)
    }
  }
})

 
 

 
 

auth.code2Session

Official website document

Login credential verification. Obtain the temporary login credential code through the wx.login interface and pass it to the developer server to call this interface to complete the login process.

request address

GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

request parameters

Attributes type Defaults required illustrate
appid string yes Mini program appId
secret string yes Applet appSecret
js_code string yes The code obtained when logging in
grant_type string yes Authorization type, just fill in authorization_code here

The applet appId and applet appSecret can be found in the development management
insert image description here
insert image description here

return value

Attributes type illustrate
openid string unique user ID
session_key string session key
unions string The unique identifier of the user on the open platform, if the current Mini Program has been bound to the WeChat open platform account, it will return
errcode number error code
errmsg string error message

Legal values ​​for errcode

value illustrate
-1 The system is busy, please try again later
0 successful request
40029 code invalid
45011 Frequency limit, 100 times per minute per user
40226 For high-risk users, applet login interception.

 
 

 
 

 
 

combat

front-end code

The front end of the WeChat applet gets the code and sends it to the background

wx.login({
    
    
  success (res) {
    
    
    if (res.code) {
    
    
      //发起网络请求
      wx.request({
    
    
        url: 'https://example.com/onLogin',//开发的后台地址,传输code获取openid登录信息
        data: {
    
    
          code: res.code
        }
      })
    } else {
    
    
      console.log('登录失败!' + res.errMsg)
    }
  }
})

 
 

 
 

backend code

The background receives the code and obtains the user's openid through the code

After the background receives the code, it creates an http request to access the WeChat background server to obtain the user's openid. If everything is normal, it will get the user's openid corresponding to the applet and the user's personal Access_token.

Two dependencies used:

<!--    json数据格式依赖    -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.79</version>
</dependency>
<!--    http请求工具包依赖    -->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
/**
     * 获取微信的openid和session_key
     * @param code wx.login的code
     * @return 返回JSON:openid和session_key
     */
    public static JSONObject gainWxLogin(String code){
    
    
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppID + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject = null;
        try {
    
    
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
            HttpResponse response = client.execute(get);//提交GET请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            System.out.println(content);//打印返回的信息
            jsonObject = JSONObject.parseObject(content);//把信息封装为json
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return jsonObject;
    }

The information obtained by the backend:
information obtained
In this way, the openid of WeChat is obtained. The next step is to check whether the openid is already in the database. If it exists, log in. If it does not exist, register.

Guess you like

Origin blog.csdn.net/qq_43448856/article/details/123784490