Home > WeChat Applet > Mini Program Development > Introduction to the method of adding session mechanism to WeChat applet

Introduction to the method of adding session mechanism to WeChat applet

不言
Release: 2018-10-24 10:24:30
forward
4026 people have browsed it

This article brings you an introduction to the method of adding session mechanism to WeChat applet. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The idea of ​​this article comes from reading the source code of WeChat wafer a few days ago. Thanks to all wafer code writers.

Let’s look at the code implementation first

var SESSION_KEY = 'xxxxxx';var Session = {
    get: function() {
            return wx.getStorageSync(SESSION_KEY) || null;
    },    
    set: function(session) {
        wx.setStorageSync(SESSION_KEY, session);
    },    
    clear: function() {
        wx.removeStorageSync(SESSION_KEY);
    },
};
module.exports = Session;
Copy after login

It’s very simple, isn’t it? This is how it is implemented. Explain, for example, when we log in, we need to make a storage on the mini program side. Mainly What is stored is the access_token returned by the backend (this value is used for interface requests that require user authentication), then the above Session can be used.

if (result.statusCode === 200 && data.access_token)
 {
    Session.set(data.access_token);    
}
Copy after login

When we determine whether the local user is logged in, we can also perform the following operations

var session = Session.get();
if (session) {
    wx.checkSession({
            success: function () {            
            ////
        },
                fail: function () {
            Session.clear();            
            // doLogin();
        },
    });
} else {    
//doLogin(); 进行登录
}
Copy after login

Of course, this mechanism is not necessary, but with it, the code becomes more concise and obtains The user's session, writing session and clearing session, one thing is very easy for your backend junior to understand when they see your code.

The above is the detailed content of Introduction to the method of adding session mechanism to WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template