Table of Contents
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:
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.
Home WeChat Applet Mini Program Development Mini Program Development--User Login and Maintenance Example Tutorial

Mini Program Development--User Login and Maintenance Example Tutorial

May 20, 2017 pm 04:55 PM

Providing user login and maintaining the user's login status are generally things that a software application with a user system 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 (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 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 need to pay attention to the following: There is no Cookie<a href="http://www.php.cn/wiki/422.html" target="_blank"></a> mechanism in the mini program, so before using these two methods, please confirm whether yours or a third party's API needs to rely on Cookie ; In addition, HTML pages are not supported in mini programs. Those third-party APIs that need to use page redirection for login need to be modified or cannot 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:

Mini Program Development--User Login and Maintenance Example Tutorial

Login flowchart

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 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(&#39;获取用户登录凭证:&#39; + code);
        } else {
          console.log(&#39;获取用户登录态失败:&#39; + res.errMsg);
        }
      }
    });
  }
})
Copy after login

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(&#39;获取用户登录凭证:&#39; + code);

          // --------- 发送凭证 ------------------
          wx.request({
            url: &#39;https://www.my-domain.com/wx/onlogin&#39;,
            data: { code: code }
          })
          // ------------------------------------

        } else {
          console.log(&#39;获取用户登录态失败:&#39; + res.errMsg);
        }
      }
    });
  }
})
Copy after login

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:

api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
Copy after login

Here is the code of the background service I built using

Node.js

Express, for reference only:

If this background code is executed successfully, you can Get 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

在之后,调用那些需要登录后才有权限的访问的后台服务时,你可以将保存在storage中的sessionid取出并携带在请求中(可以放在header中携带,也可以放在querystring中,或是放在body中,根据你自己的需要来使用),传递到后台服务,后台代码中获取到该sessionid后,从redis中查找是否有该sessionid存在,存在的话,即确认该session是有效的,继续后续的代码执行,否则进行错误处理。

这是一个需要session验证的后台服务示例,我的sessionid是放在header中传递的,所以在这个示例中,是从请求的header中获取sessionid:

router.get(&#39;/wx/products/list&#39;, function (req, res, next) {
  let sessionid = req.header("sessionid")
  let sessionVal = redisStore.get(sessionid)
  if (sessionVal) {
    // 执行其他业务代码
  } else {
    // 执行错误处理
  }
})
Copy after login

好了,通过微信账号进行小程序登录和状态维护的简单流程就是这样,了解这些知识点之后,再基于此进行后续的开发就会变得更容易了。

另外,腾讯前端团队也开源了他们封装的相关库,可以借鉴和使用。

  • 服务器端库 weapp-session

  • 小程序端库 weapp-session-client

感谢阅读我的文章,如有疑问或写错的地方请不吝留言赐教。

【相关推荐】

1. 微信小程序完整源码下载

2. 简单的左滑操作和瀑布流布局

3. 微信小程序游戏类demo挑选不同色块

The above is the detailed content of Mini Program Development--User Login and Maintenance Example Tutorial. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1254
24
PHP development skills: How to implement user login restriction function PHP development skills: How to implement user login restriction function Sep 21, 2023 am 11:39 AM

PHP development skills: How to implement user login restriction function In website or application development, user login restriction function is a very important security measure. By limiting the number of login attempts and frequency of users, you can effectively prevent accounts from being maliciously cracked or brute force cracked. This article will introduce how to use PHP to implement user login restriction function and provide specific code examples. 1. Requirements analysis of user login restriction function User login restriction function usually includes the following requirements: Limitation on the number of login attempts: when the user continuously inputs errors

How to use PHP and CGI to implement user registration and login functions How to use PHP and CGI to implement user registration and login functions Jul 21, 2023 pm 02:31 PM

How to use PHP and CGI to implement user registration and login functions User registration and login are one of the necessary functions for many websites. In this article, we will introduce how to use PHP and CGI to achieve these two functions. We'll demonstrate the entire process with a code example. 1. Implementation of the user registration function The user registration function allows new users to create an account and save their information to the database. The following is a code example to implement the user registration function: Create a database table First, we need to create a database table to store user information. Can

How to use PHP arrays to implement user login and permission management functions How to use PHP arrays to implement user login and permission management functions Jul 15, 2023 pm 08:55 PM

How to use PHP arrays to implement user login and permission management functions When developing a website, user login and permission management are one of the very important functions. User login allows us to authenticate users and protect the security of the website. Permission management can control users' operating permissions on the website to ensure that users can only access the functions for which they are authorized. In this article, we will introduce how to use PHP arrays to implement user login and permission management functions. We'll use a simple example to demonstrate this process. First we need to create

How to send SMS verification code and email notification when user logs in in PHP How to send SMS verification code and email notification when user logs in in PHP Sep 26, 2023 pm 08:40 PM

How to send SMS verification codes and email notifications when users log in in PHP. With the rapid development of the Internet, more and more applications require user login functions to ensure security and personalized experience. In addition to basic account and password verification, in order to improve user experience and security, many applications will also send mobile phone SMS verification codes and email notifications when users log in. This article will describe how to implement this functionality in PHP and provide corresponding code examples. 1. Send SMS verification code 1. First, you need someone who can send SMS

UniApp implements detailed analysis of user login and authorization UniApp implements detailed analysis of user login and authorization Jul 05, 2023 pm 11:54 PM

UniApp implements detailed analysis of user login and authorization. In modern mobile application development, user login and authorization are essential functions. As a cross-platform development framework, UniApp provides a convenient way to implement user login and authorization. This article will explore the details of user login and authorization in UniApp, and attach corresponding code examples. 1. Implementation of user login function Create login page User login function usually requires a login page, which contains a form for users to enter their account number and password and a login button

How to use Pagoda Panel for website repair and maintenance How to use Pagoda Panel for website repair and maintenance Jun 21, 2023 pm 03:19 PM

In the current Internet era, websites have become an important means for many companies to display and promote themselves. However, it is inevitable that some unexpected situations will cause the website to be inaccessible or have limited functions. At this time, the website needs to be repaired and maintained. This article will introduce how to use Pagoda Panel for website repair and maintenance. 1. Introduction to Pagoda Panel Pagoda Panel is a website management software running on a Linux server. It can help users quickly build a Web environment on the server operating system. The Pagoda panel integrates numerous functional modules

How to build a user login and permission management system using Elasticsearch and PHP How to build a user login and permission management system using Elasticsearch and PHP Jul 08, 2023 pm 04:15 PM

How to use Elasticsearch and PHP to build a user login and permission management system Introduction: In the current Internet era, user login and permission management are one of the necessary functions for every website or application. Elasticsearch is a powerful and flexible full-text search engine, while PHP is a widely used server-side scripting language. This article will introduce how to combine Elasticsearch and PHP to build a simple user login and permission management system

PHP permission management and user role setting in mini program development PHP permission management and user role setting in mini program development Jul 04, 2023 pm 04:48 PM

PHP permission management and user role setting in mini program development. With the popularity of mini programs and the expansion of their application scope, users have put forward higher requirements for the functions and security of mini programs. Among them, permission management and user role setting are An important part of ensuring the security of mini programs. Using PHP for permission management and user role setting in mini programs can effectively protect user data and privacy. The following will introduce how to implement this function. 1. Implementation of Permission Management Permission management refers to granting different operating permissions based on the user's identity and role. in small

See all articles