Home >WeChat Applet >Mini Program Development >How to do user login in mini program? How to maintain login status?

How to do user login in mini program? How to maintain login status?

青灯夜游
青灯夜游forward
2021-05-28 11:29:349026browse

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.

Today we will mainly discuss the third method, that is, how to log in using a WeChat account, because this method is most closely integrated with the WeChat platform and has a better user experience.

Login process

Quoting the login flow chart from the official document of the mini program, the entire login process is basically as shown below:

In this figure, "mini program" refers to the code part we write using the mini program framework. "Third-party server" is generally our own background service program, and "WeChat server" is WeChat's official API server.

Let’s break down this flow chart step by step.

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 the

wx.login() method and get a login credentials.

We can initiate a login credential request in the App code of the mini program, or in any other Page code, mainly based on the actual needs of your mini program.

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete