


User login and login status maintenance in WeChat mini program
Update description:
Due to the official revision of the relevant API of the WeChat applet, there have been some changes in the login function process, so another article has been updated recently (with video description and Complete sample code), you can read it together with this article for reference:
Login and session retention process after the revision of WeChat applet interface
Provide user login and maintain user login status , is something that a software application with a user system generally needs to do. For a social platform like WeChat, if we make a small program application, we may rarely make a pure tool software that is completely separated from and abandons the connection of user information.
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.
In the WeChat mini program, we will generally involve the following three types of login methods:
- Own account registration and login
- Use other third-party platforms Account login
- Log in with a WeChat account (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 currently Web The two most common methods in applications can also be used in WeChat mini programs, but need to pay attention is that there is no Cookie
mechanism in the mini program, so when using this Before using the 2 methods, please confirm whether your or third-party APIs need to rely on Cookie
; also, HTML pages are not supported in mini programs. Those third-party APIs that need to use page redirection to log in do so. Renovated, or no longer usable.
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 in the following figure:
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.
App({ onLaunch: function() { wx.login({ success: function(res) { var code = res.code; if (code) { console.log('获取用户登录凭证:' + code); } else { console.log('获取用户登录态失败:' + res.errMsg); } } }); } })
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 identification (openid)
andSession key (session_key)
First, we use the wx.request() method to request a background API implemented by ourselves and carry the login credentials (code), for example, in our Based on the previous code, add:
App({ onLaunch: function() { wx.login({ success: function(res) { var code = res.code; if (code) { console.log('获取用户登录凭证:' + code); // --------- 发送凭证 ------------------ wx.request({ url: 'https://www.my-domain.com/wx/onlogin', data: { code: code } }) // ------------------------------------ } else { console.log('获取用户登录态失败:' + res.errMsg); } } }); } })
Your background service (/wx/onlogin) then needs to use the passed login credentials to call the WeChat interface in exchange for openid and session_key. The interface address format is as follows:
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
Here is the code of the background service I built using Node.js Express, for reference only:
router.get('/wx/onlogin', function (req, res, next) { let code = req.query.code request.get({ uri: 'https://api.weixin.qq.com/sns/jscode2session', json: true, qs: { grant_type: 'authorization_code', appid: '你小程序的APPID', secret: '你小程序的SECRET', js_code: code } }, (err, response, data) => { if (response.statusCode === 200) { console.log("[openid]", data.openid) console.log("[session_key]", data.session_key) //TODO: 生成一个唯一字符串sessionid作为键,将openid和session_key作为值,存入redis,超时时间设置为2小时 //伪代码: redisStore.set(sessionid, openid + session_key, 7200) res.json({ sessionid: sessionid }) } else { console.log("[error]", err) res.json(err) } }) })
If this background code is successfully executed, you can get the openid and session_key. This information is the login status of the current WeChat account on the WeChat server.
However, for security reasons, please do not directly use this information as the user ID and session ID of your mini program to be sent back to the mini program client. We should make our own layer on the server side. session, generate a session id from this WeChat account login state and maintain it in our own session mechanism, and then distribute this session id to the mini program client for use as a session identifier.
Regarding how to implement this session mechanism on the server side, we now generally use key-value storage tools, such as redis. We generate a unique string as a key for each session, and then store session_key and openid as values in redis. For safety, a timeout should be set when saving.
Step 3: Save sessionid 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 sessionid for subsequent background API calls.
在之后,调用那些需要登录后才有权限的访问的后台服务时,你可以将保存在storage中的sessionid取出并携带在请求中(可以放在header中携带,也可以放在querystring中,或是放在body中,根据你自己的需要来使用),传递到后台服务,后台代码中获取到该sessionid后,从redis中查找是否有该sessionid存在,存在的话,即确认该session是有效的,继续后续的代码执行,否则进行错误处理。
这是一个需要session验证的后台服务示例,我的sessionid是放在header中传递的,所以在这个示例中,是从请求的header中获取sessionid:
router.get('/wx/products/list', function (req, res, next) { let sessionid = req.header("sessionid") let sessionVal = redisStore.get(sessionid) if (sessionVal) { // 执行其他业务代码 } else { // 执行错误处理 } })
好了,通过微信账号进行小程序登录和状态维护的简单流程就是这样,了解这些知识点之后,再基于此进行后续的开发就会变得更容易了。
另外,腾讯前端团队也开源了他们封装的相关库Wafer,可以借鉴和使用。
- 服务端SDK: wafer-node-session
- 小程序端SDK: wafer-client-sdk
感谢阅读我的文章,如有疑问或写错的地方请不吝留言赐教。
一斤代码的《微信小程序》相关教程文章
一斤代码的《从编程小白到全栈开发》系列教程文章
推荐教程:《Vue.js教程推荐:最新的5个vue.js视频教程精选》
The above is the detailed content of User login and login status maintenance in WeChat mini program. 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

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

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.

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
