


How to do user login in mini program? How to maintain login status?
Allowing users to log in, identifying users and obtaining user information, and providing services with users as the core are what most small programs will do. Today we will learn how to log in users in the mini program and how to maintain the session state after login. [Related learning recommendations: Mini Program Development Tutorial]
In WeChat Mini Programs, we will generally involve the following three types of login methods:
- own Account registration and login;
- Use other third-party platform accounts to log in;
- Use WeChat account to log in (that is, directly use the currently logged-in WeChat account to log in as a user of the mini program).
The first and second methods are the two most common methods currently used in Web applications. They can also be used in WeChat mini programs, but it is important to note that there are no # in the mini programs. ##Cookie mechanism, so before using these two methods, please confirm whether your or third-party APIs need to rely on
Cookie; and the mini program does not support HTML pages, those who need Third-party APIs that use page redirection for login need to be modified or may not be used.
Login process
Quoting the login flow chart from the official document of the mini program, the entire login process is basically as shown below:Step 1: Obtain the login credentials (code) of the currently logged-in WeChat user on the client
The first step to log in in the mini program is to obtain the login credentials first . We can use thewx.login() method and get a login credentials.
Step 2: Send the login credentials to your server, and use the credentials on your server to exchange the WeChat server for the WeChat user’s unique identifier (openid) and session key (session_key )
First, we use the wx.request() method to request a backend API we implemented ourselves, and bring the login credentials (code) there. For example, add: Your background service then needs to use the passed login credentials to call the WeChat interface in exchange for openid and session_key Let’s introduce openid first. Children’s shoes who have used official accounts should be familiar with this Identification is no stranger. In the public platform, it is used to identify each user’s unique identification in three different applications: subscription account, service account, and mini program. In other words, the openid of each user in each application is inconsistent. , so in the mini program, we can use openid to identify the uniqueness of the user. So what is session_key used for? With the user ID, we need to let the user log in. Then the session_key ensures the validity of the current user's session operation. This session_key is distributed to us by the WeChat server. In other words, we can use this identifier to indirectly maintain the login status of our applet users. So how did we get this session_key? We need to request the third-party interface provided by WeChat on our own server https://api.weixin.qq.com/sns/jscode2session From these parameters, we can see that we need to request this interface You must first call wx.login() to obtain the code of the user's current session. So why do we need to request this interface on the server side? In fact, it is for security reasons. If we call this interface through request on the front end, we will inevitably need to expose the appid of our mini program and the secret of the mini program to the outside. At the same time, we will also expose the session_key issued by the WeChat server. To "people with good intentions", this brings great risks to our business security. In addition to obtaining session_key on the server side, we also need to pay attention to two points:- session_key corresponds one-to-one with the code distributed by WeChat, and the same code can only be exchanged for session_key once. Each time
wx.login()
is called, a new code and corresponding session_key will be issued. In order to ensure the user experience and the validity of the login state, developers need to know that the user needs to log in again before calling it.
wx.login() - session_key is invalid. Even if wx.login is not called, the session_key will expire. The expiration time depends on the user's use of the applet. The frequency is positively correlated, but the specific length of time is not available to developers and users
Step 3: Generate 3rd_session
As mentioned before, session_key is used to "indirectly" maintain the login state. The so-called indirection means that we need to maintain the user ourselves. Login status information, security factors are also taken into consideration here. If the session_key distributed by the WeChat server is used directly as the login status of the business party, it will be used by "intentional people" to obtain the user's sensitive information, such as wx.getUserInfo()
This interface requires session_key to decrypt the sensitive information of WeChat users.
So what if we generate our own login status identification? Here we can use several common irreversible hash algorithms, such as md5, sha1, etc., to generate the login status identification (here we collectively refer to it as 'skey ') is returned to the front end, and the login status identifier is maintained at the front end (usually stored in storage). On the server side, we will store the generated skey in the data table corresponding to the user, and the front end will access the user's information by passing the skey.
Step 4: Save Session ID on the client
When developing web applications, in the client (browser), we usually store the Session ID in a cookie , but the mini program does not have a cookie mechanism, so cookies cannot be used. However, the mini program has local storage, so we can use storage to save the Session ID for subsequent background API calls.
Later, when calling background services that require login to access, you can take out the Session ID saved in storage and carry it in the request (it can be carried in the header or in the querystring, or put it in the body, use it according to your own needs), pass it to the background service, after getting the Session ID in the background code, check whether the Session ID exists from redis, if it exists, that is Confirm that the session is valid and continue with subsequent code execution, otherwise error handling will be performed.
Earlier we stored the skey in the front-end storage. Every time we make a user data request, we will bring the skey. So what if the session_key expires at this time? So we need to call wx.checkSession()
this API to verify whether the current session_key has expired. This API does not need to pass in any information parameters about session_key, but the WeChat applet adjusts itself. Service to query whether the user's most recently generated session_key has expired. If the current session_key expires, let the user log in again, update the session_key, and store the latest skey in the user data table.
Step 5: Support emoji expression storage
If you need to store the user's WeChat name in the data table, then confirm the encoding format of the data table and data columns. Because the user's WeChat name may contain emoji icons, and the commonly used UTF8 encoding only supports 1-3 bytes, the emoji icons are stored in exactly 4 bytes of encoding.
There are two ways here (taking mysql as an example):
1. Set the storage character set
After mysql5.5.3 version, support Set the character set of the database, data table and data column to utf8mb4, so you can set the default character set encoding and server-side encoding format in /etc/my.cnf
[client] default-character-set=utf8mb4 [mysql] default-character-set=utf8mb4 [mysqld] character-set-client-handshake = FALSE character-set-server=utf8mb4 collation-server=utf8mb4_unicode_ci
After setting the default character set encoding and server-side Character set encoding. If you are encoding existing tables and fields, you need to perform the following steps:
Set the database character set to utf8mb4
ALTER DATABASE 数据库名称 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
Set the data table character set to utf8mb4
ALTER TABLE 数据表名称 CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Set the character set of the data column field to utf8mb4
ALTER TABLE 数据表名称 CHANGE 字段列名称 VARCHAR(n) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
The COLLATE here refers to the sorting character set, which is used to sort and compare the stored characters. The commonly used collation of utf8mb4 There are two types: utf8mb4_unicode_ci and utf8mb4_general_ci. It is generally recommended to use utf8mb4_unicode_ci because it is sorted based on the standard Unicode Collation Algorithm (UCA) and can be accurately sorted in various languages. For the specific differences between these two sorting methods, please refer to: What's the difference between utf8_general_ci and utf8_unicode_ci
2. Use sequelize to encode emoji characters into the library, and then decode them when using them
Here is the configuration of sequelize, please refer to the Sequelize document
{ dialect: 'mysql', // 数据库类型 dialectOptions: { charset: 'utf8mb4', collate: "utf8mb4_unicode_ci" }, }
Attachment: Backend code (tp5)
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of How to do user login in mini program? How to maintain login status?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include
