WeChat applet realizes user login (details)

        User login is an important part of the WeChat Mini Program, so today we will talk about the process of user login. Of course, the official WeChat document also has a related login flow chart. Here is also an address for everyone: Official | Mini Program Login  .

User login process

      The user login process can be briefly summarized in this sentence: "3 roles, 4 steps", the 3 roles are "small program, developer server, WeChat interface service", and the 4 steps are: a small program to obtain code, The second is to send the code to the developer server, the third is to verify the login credentials through the WeChat interface service on the developer server, and the fourth is to customize the login status of the developer service.

        Know the corresponding three roles, and at the same time have a basic understanding of the four steps, then the link to the official document is provided above, you can read the document yourself, or just read a shallow opinion of mine; first, the small program passes through wx .login() obtains the login credential code. The code is different each time it is called, and the valid time is 5 minutes. The code will be invalid after being verified once by the WeChat interface service. After the applet obtains the code, pass the code to wx.request() Send to the developer server, the developer server will send the appid, appSecret (key), and code to the WeChat interface service to verify the login credentials, and if successful, it will return session_key (session information record) and openid (user unique identifier), and the user will log in After success, the developer server can save the openid and session_key, and generate a customized login status token (token) to respond to the applet. The openid and session_key can be queried through the token. The next request of the applet only needs to carry the token. Prove that you are logged in.


Build a developer server 

        In the actual development, it is to buy a server, so here is only for understanding and building, then use the local localhost:3000 as the port of the server, choose node.js to build the developer server, how to build you can read this content to learn How to build it, here is the code for the initial build, but I will introduce it more;

WeChat applet equipped with node.js server (simplified) https://blog.csdn.net/weixin_52203618/article/details/124225264 index.js file code

const express = require('express') 				
const bodyParser = require('body-parser')		
const request = require('request')				
const app = express()

app.use(bodyParser.json())	

app.listen(3000, () => {
    console.log('server running ...');
})

        We will not write all the interfaces here for the time being, we will write them when we need them, the content is a step-by-step process.


Step 1: Get the code

         The applet obtains the login credential code through wx.login(), then create a small program named Login in the WeChat developer tool, here to realize the automatic login operation when a small program starts, in the app.js file To write code, it can be triggered in onLaunch;

App({
    onLaunch:function(){
       this.login()  // 调用
    },
    
    login:function(){
        // wx.login()获取code
        wx.login({
            success:(res)=>{
                console.log("code: " + res.code);
            }
        })
    }
})

 The above is to get the code, and you can see the printed code on the console at this time;

Step 2: Send the code to the developer server

Send the code to the developer server via wx.request()

login:function(){
    // wx.login()获取code
        wx.login({
            success:(res)=>{
                console.log("code: " + res.code);
                wx.request({
                    url:'http://127.0.0.1:3000/login',
                    method:'POST',
                    data:{
                        code : res.code
                    }
                })
            }
    })
}

        There is a response request interface in the developer server. The request method is post. Then you can write code in the index.js file. If you have installed nodemon, you don’t need to restart it. If not, you need to re-export node from the command line. index.js reruns.

// 写在app.listen即可
// '/login'即响应在小程序中的请求http://127.0.0.1:3000/login
app.post('/login',(req,res)=>{
    console.log('code: '+req.body.code) // 打印一下code
})

app.listen(3000, () => {
    console.log('server running...');
})

 You can see that the applet successfully sends the code to the developer server through wx.request();

Step 3: Verify through the WeChat interface service

        The developer server sends the appid, appSecret (key), and code to the WeChat interface service to verify the login credentials, and if successful, it will return session_key (session information record) and openid (user unique identifier); at this time, it is mainly to write the developer server Among the codes, developers need to prepare their own appid and appSecret keys, and here is how to get them;

How to get appid (user unique identifier), appSecret (user key)?

Log in to the background of the WeChat applet. After logging in, click [Development Management] in the [Development] option to see it;  WeChat public platform (qq.com) https://mp.weixin.qq.com/

         Now write the code in the developer server; with the code, appid, and appsecret, you can verify the WeChat interface service, attach this official link and use it to copy, in case you make a mistake auth.code2Session | WeChat open  document

// 开发者信息
const wx = {
    // appid:' ',  // 填写用户自己的appid
    // secret:' '  // 填写用户自己的密钥
}

// 写在app.listen即可
// '/login'即响应在小程序中的请求http://127.0.0.1:3000/login
app.post('/login',(req,res)=>{
    console.log('code: '+req.body.code) // 打印一下code
    // code,appid,secret都有了就发起请求到微信接口服务校验
    var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + wx.appid + '&secret=' + wx.secret + '&js_code=' + req.body.code + '&grant_type=authorization_code'
    request(url, (err, response, body) => {
		//	可以获取到 session_key(会话信息) 、 openid(用户唯一标识)
        console.log('session: ' + body)
		//  上面的session信息是字符串数据,通过JSON.parse()转成js对象
        // var session = JSON.parse(body)
		console.log(session);
})

app.listen(3000, () => {
    console.log('server running...');
})

        After success, it will return openid and session_key. openid is the user's unique id on this applet. Different applet users have different ids. session_key is the user's session information record; print out the result and view it in the developer server to the following:

        The above are the session_key and openid returned after the verification is successful; note here that the account must not be a test account, otherwise the code cannot be obtained, and the verification cannot pass if the code cannot be obtained;

Step 4: Customize the login status of the developer server

        Save the session_key and openid returned after the verification is successful. In actual development, the database is usually used to save the data. For example, MongoDB can be used. Here, the database is not built to store the data, and it is saved as data in our variables. If there is a chance in the follow-up, we will do a special issue; openid is the unique identifier of the user, so we can judge whether there is an openid in the session, and if there is, we will return a token. The returned token cannot be fixed, and there is a certain analysis , at this time, you can use this timestamp to generate tokens. Of course, in actual development, it is recommended to use more mature modules to generate tokens to avoid adverse effects caused by token forgery. Here we will use timestamps to generate tokens for you to demonstrate this process;

// 开发者信息
const wx = {
    appid:'',
    secret:''
}

// 模拟数据库存放数据
var db = {
	user: {},		// userInfo
    session: {}		// 保存 openid 和session_key会话信息 
}

app.post('/login', (req, res) => {
    // 注意:小程序端的appid必须使用真实账号,如果使用测试账号,会出现login code错误
    console.log('code: ' + req.body.code)
	// 接收code参数(req.body.code)
    var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + wx.appid + '&secret=' + wx.secret + '&js_code=' + req.body.code + '&grant_type=authorization_code'
	request(url, (err, response, body) => {
        var session = JSON.parse(body)
		// 将openid和session_key保存后响应token回去,openid是用户的唯一标识
        // if(session.openid) {
			// 时间戳来生成token
            var token = 'token_' + new Date().getTime()  
            db.session[token] = session
			console.log(db);
            if(!db.user[session.openid]) {
                 db.user[session.openid] = {
                       state:1  // 成功登录可以获取
                 }
             }
        }
        res.json({
            token: token  // 返回token
        })
    })
})

        After the token is returned successfully, you can add it to the wx.request() request verification in the applet and print the returned data to the console of the applet after the request is successful;

login:function(){
...代码省略...
wx.request({
     url: 'http://127.0.0.1:3000/login',
     method:'POST',
     data:{ code:res.code },
     success:(res)=>{
     // 将请求成功的token打印
        console.log("token : " + res.data.token);
          }
     })
...代码省略...   
},

The token returned to the applet is cached. The next request of the applet only needs to carry the token to prove that the user has logged in. Then we need to check whether the user is logged in before entering the applet.

Check if user is logged in

         Before checking the user login, the returned token is cached for data. The token is public data, which is needed in multiple pages, and can be defined as global globalData; data cache can be used wx.setStorage(), if it has not been used Yes, official documents are provided here, and briefly speaking, there are mainly two parameters, one is key and the other is data. Encryption methods are not applicable here. Understand the basic usage and then think about encryption. Attach the address of the developer documentation: wx.setStorage() | WeChat development documentation

login:function(){
    // 1.wx.login()获取code
    wx.login({
      success:(res)=>{
        ....省略...
          success:(res)=>{
              console.log("token : " + res.data.token);

              // 将token保存为公共数据(多页面使用->全局globalData)
              this.globalData.token = res.data.token
              // 将token保存在数据缓存中(下次无需重新获取token)
              wx.setStorage({
                key:'token',
                data:res.data.token
              })

        ...省略...
  },
  globalData:{
    token:null
  }
})

You can check whether it has been cached, open the console to check, as shown below

Check user login

        The above content will be returned to the token cache, so to check whether there is a token in the cache, if there is, you can request the server to check whether the token is valid. If there is no token, call login() in the original way to get it token;

App({
  onLaunch:function(){
    // 检测用户是否登录
    this.checkLogin(res=>{
       console.log('is_login : ',res.is_login);
      // 未登录 -> login()
      if(!res.is_login){
        // 调用Login
        this.login();
       }
     })
  },
  // checkLogin()
  checkLogin:function(callback){
    var token = this.globalData.token
    if(!token){
      // 从缓存中获取token
      token = wx.getStorageSync('token')
      if(token){
        this.globalData.token = token
      }else{
        callback({ is_login : false })
      }
    }
  
    // 发送请求检验token是否存在
    wx.request({
      url: 'http://127.0.0.1:3000/checklogin',
      data:{
        token : token
      },
      success:(res)=>{
        console.log(res);
        callback({
          is_login:res.data.is_login
        })
      }
    }) 
  },
  ....省略....

Developer server code writing index.js

        Respond to the interface request, query whether the token exists in the saved database, and judge whether the extracted session is undefined. If so, it means that the token value has expired. If there is a cached token and the token is valid, it means that the user has logged in;

// index.js

...省略...

// 检查用户是否已经登录
app.get('/checklogin', (req, res) => {
    var session = db.session[req.query.token]
    console.log('checklogin: ', session)
    // 将用户是否已经登录的布尔值返回给客户端
    res.json({
        is_login: session !== undefined
    })
})

app.listen(3000, () => {
    console.log('server running...');
})

         Now that there is a token value in the cache, let’s recompile it. At this time, there is a token value in the cache, and the value of is_login is true, which proves that the user has logged in;

        The above is the content of this article. It describes the user login process of an important link in the WeChat applet. Xiaobai and the more basic ones are more suitable, and the length may be longer. Thank you for your support!

Guess you like

Origin blog.csdn.net/weixin_52203618/article/details/127130032