Home Web Front-end JS Tutorial How to implement WeChat applet login authentication

How to implement WeChat applet login authentication

May 25, 2018 pm 03:27 PM
Applets Log in program

This time I will show you how to implement WeChat applet login authentication and what are the precautions to implement WeChat applet login authentication. The following is a practical case, let’s take a look.

Preface

In order to facilitate mini program applications to use the WeChat login state for authorized login, the WeChat mini program provides an open interface for login authorization. At first glance, I feel that the document is very reasonable, but when it comes to implementation, it is really confusing and I don’t know how to manage and maintain the login state. This article will teach you step by step how to access and maintain the WeChat login status in business. I won’t go into more details below. Let’s take a look at the detailed introduction.

Access process

The flow chart in the official document here is clear enough, so we will directly elaborate and supplement it.

First of all, when you see this picture, you will definitely notice that the mini program communicates and interacts not only with the mini program front end and our own server, but also with the WeChat third-party server Also involved, so what role does the WeChat server play in it? Let’s go through the login authentication process together and we’ll understand.

1. Call wx.login to generate code

wx.login() The function of this API is to generate a temporary login for the current user Credentials, this temporary login credential is only valid for five minutes. After we get this login credentials, we can proceed to the next step: Get openid and

session_key

wx.login({
 success: function(loginRes) {
 if (loginRes.code) {
  // example: 081LXytJ1Xq1Y40sg3uJ1FWntJ1LXyth
 }
 }
});
Copy after login

2. Get openid and session_key

Let’s first introduce openid. Children’s shoes who have used public accounts should be familiar with this logo. In the public platform, it is used to identify each user’s subscription account, service account, and mini program. A unique identifier for different applications, that is to say, 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. This interface needs to bring four parameter fields:

ParametersValue##appid#secretThe secret of the mini programjs_codeThe code sent by the previous call to wx.logingrant_type'authorization_code'

从这几个参数,我们可以看出,要请求这个接口必须先调用wx.login()来获取到用户当前会话的code。那么为什么我们要在服务端来请求这个接口呢?其实是出于安全性的考量,如果我们在前端通过request调用此接口,就不可避免的需要将我们小程序的appid和小程序的secret暴露在外部,同时也将微信服务端下发的session_key暴露给“有心之人”,这就给我们的业务安全带来极大的风险。除了需要在服务端进行session_key的获取,我们还需要注意两点:

  1. session_key和微信派发的code是一一对应的,同一code只能换取一次session_key。每次调用wx.login() ,都会下发一个新的code和对应的session_key,为了保证用户体验和登录态的有效性,开发者需要清楚用户需要重新登录时才去调用wx.login()

  2. session_key是有失效性的,即便是不调用wx.login,session_key也会过期,过期时间跟用户使用小程序的频率成正相关,但具体的时间长短开发者和用户都是获取不到的

function getSessionKey (code, appid, appSecret) {
 var opt = {
 method: 'GET',
 url: 'https://api.weixin.qq.com/sns/jscode2session',
 params: {
  appid: appid,
  secret: appSecret,
  js_code: code,
  grant_type: 'authorization_code'
 }
 };
 return http(opt).then(function (response) {
 var data = response.data;
 if (!data.openid || !data.session_key || data.errcode) {
  return {
  result: -2,
  errmsg: data.errmsg || '返回数据字段不完整'
  }
 } else {
  return data
 }
 });
}
Copy after login

3. 生成3rd_session

前面说过通过 session_key 来“间接”地维护登录态,所谓间接,也就是我们需要 自己维护用户的登录态信息 ,这里也是考虑到安全性因素,如果直接使用微信服务端派发的session_key来作为业务方的登录态使用,会被“有心之人”用来获取用户的敏感信息,比如wx.getUserInfo()这个接口呢,就需要session_key来配合解密微信用户的敏感信息。

那么我们如果生成自己的登录态标识呢,这里可以使用几种常见的不可逆的哈希算法,比如md5、sha1等,将生成后的登录态标识(这里我们统称为'skey')返回给前端,并在前端维护这份登录态标识(一般是存入storage)。而在服务端呢,我们会把生成的skey存在用户对应的数据表中,前端通过传递skey来存取用户的信息。

可以看到这里我们使用了sha1算法来生成了一个skey:

const crypto = require('crypto');
return getSessionKey(code, appid, secret)
 .then(resData => {
 // 选择加密算法生成自己的登录态标识
 const { session_key } = resData;
 const skey = encryptSha1(session_key);
 });
 
function encryptSha1(data) {
 return crypto.createHash('sha1').update(data, 'utf8').digest('hex')
}
Copy after login

4. checkSession

前面我们将skey存入前端的storage里,每次进行用户数据请求时会带上skey,那么如果此时session_key过期呢?所以我们需要调用到wx.checkSession()这个API来校验当前session_key是否已经过期,这个API并不需要传入任何有关session_key的信息参数,而是微信小程序自己去调自己的服务来查询用户最近一次生成的session_key是否过期。如果当前session_key过期,就让用户来重新登录,更新session_key,并将最新的skey存入用户数据表中。

checkSession这个步骤呢,我们一般是放在小程序启动时就校验登录态的逻辑处,这里贴个校验登录态的流程图:

 

下面代码即校验登录态的简单流程:

let loginFlag = wx.getStorageSync('skey');
if (loginFlag) {
 // 检查 session_key 是否过期
 wx.checkSession({
 // session_key 有效(未过期)
 success: function() {
  // 业务逻辑处理
 },
 
 // session_key 过期
 fail: function() {
  // session_key过期,重新登录
  doLogin();
 }
 });
) else {
 // 无skey,作为首次登录
 doLogin();
}
Copy after login

5. 支持emoji表情存储

如果需要将用户微信名存入数据表中,那么就确认数据表及数据列的编码格式。因为用户微信名可能会包含emoji图标,而常用的UTF8编码只支持1-3个字节,emoji图标刚好是4个字节的编码进行存储。

这里有两种方式(以mysql为例):

1.设置存储字符集

在mysql5.5.3版本后,支持将数据库及数据表和数据列的字符集设置为 utf8mb4 ,因此可在 /etc/my.cnf 设置默认字符集编码及服务端编码格式

// 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
Copy after login

设置完默认字符集编码及服务端字符集编码,如果是对已经存在的表和字段进行编码转换,需要执行下面几个步骤:

设置数据库字符集为 utf8mb4

ALTER DATABASE 数据库名称 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
Copy after login

设置数据表字符集为 utf8mb4

ALTER TABLE 数据表名称 CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Copy after login

设置数据列字段字符集为 utf8mb4

ALTER TABLE 数据表名称 CHANGE 字段列名称 VARCHAR(n) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Copy after login

这里的 COLLATE 指的是排序字符集,也就是用来对存储的字符进行排序和比较的, utf8mb4 常用的collation有两种: utf8mb4_unicode_ci 和 utf8mb4_general_ci ,一般建议使用 utf8mb4_unicode_ci ,因为它是基于标准的 Unicode Collation Algorithm(UCA) 来排序的,可以在各种语言进行精确排序。这两种排序方式的具体区别可以参考: What's the difference between utf8_general_ci and utf8_unicode_ci

2.通过使用sequelize对emoji字符进行编码入库,使用时再进行解码

这里是sequelize的配置,可参考 Sequelize文档

{
 dialect: 'mysql', // 数据库类型
 dialectOptions: { 
  charset: 'utf8mb4',
  collate: "utf8mb4_unicode_ci"
 },
}
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样搭建vue2.0+boostrap项目

Angular入口组件与声明式组件案例对比

Appid## of the applet

The above is the detailed content of How to implement WeChat applet login authentication. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
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)

How to make Google Maps the default map in iPhone How to make Google Maps the default map in iPhone Apr 17, 2024 pm 07:34 PM

The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? Mar 19, 2024 pm 02:00 PM

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? Mar 21, 2024 pm 09:41 PM

With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the "Login" button. (2) Select "Retrieve Password". (3) Enter the mobile phone number you used when registering your account

'Onmyoji' Ibaraki Doji's collection skin can be obtained as soon as you log in, and the new Zen Heart Cloud Mirror skin will be launched soon! 'Onmyoji' Ibaraki Doji's collection skin can be obtained as soon as you log in, and the new Zen Heart Cloud Mirror skin will be launched soon! Jan 05, 2024 am 10:42 AM

Thousands of ghosts screamed in the mountains and fields, and the sound of the exchange of weapons disappeared. The ghost generals who rushed over the mountains, with fighting spirit raging in their hearts, used the fire as their trumpet to lead hundreds of ghosts to charge into the battle. [Blazing Flame Bairen·Ibaraki Doji Collection Skin is now online] The ghost horns are blazing with flames, the gilt eyes are bursting with unruly fighting spirit, and the white jade armor pieces decorate the shirt, showing the unruly and wild momentum of the great demon. On the snow-white fluttering sleeves, red flames clung to and intertwined, and gold patterns were imprinted on them, igniting a crimson and magical color. The will-o'-the-wisps formed by the condensed demon power roared, and the fierce flames shook the mountains. Demons and ghosts who have returned from purgatory, let's punish the intruders together. [Exclusive dynamic avatar frame·Blazing Flame Bailian] [Exclusive illustration·Firework General Soul] [Biography Appreciation] [How to obtain] Ibaraki Doji’s collection skin·Blazing Flame Bailian will be available in the skin store after maintenance on December 28.

Discuz background login problem solution revealed Discuz background login problem solution revealed Mar 03, 2024 am 08:57 AM

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

How to log in to Kuaishou PC version - How to log in to Kuaishou PC version How to log in to Kuaishou PC version - How to log in to Kuaishou PC version Mar 04, 2024 pm 03:30 PM

Recently, some friends have asked me how to log in to the Kuaishou computer version. Here is the login method for the Kuaishou computer version. Friends who need it can come and learn more. Step 1: First, search Kuaishou official website on Baidu on your computer’s browser. Step 2: Select the first item in the search results list. Step 3: After entering the main page of Kuaishou official website, click on the video option. Step 4: Click on the user avatar in the upper right corner. Step 5: Click the QR code to log in in the pop-up login menu. Step 6: Then open Kuaishou on your phone and click on the icon in the upper left corner. Step 7: Click on the QR code logo. Step 8: After clicking the scan icon in the upper right corner of the My QR code interface, scan the QR code on your computer. Step 9: Finally log in to the computer version of Kuaishou

Clock app missing in iPhone: How to fix it Clock app missing in iPhone: How to fix it May 03, 2024 pm 09:19 PM

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and

How to log in to two devices on Quark How to log in to two devices on Quark Feb 23, 2024 pm 10:55 PM

How to log in to two devices with Quark? Quark Browser supports logging into two devices at the same time, but most friends don’t know how to log in to two devices with Quark Browser. Next, the editor brings users Quark to log in to two devices. Method graphic tutorials, interested users come and take a look! Quark Browser usage tutorial Quark how to log in to two devices 1. First open the Quark Browser APP and click [Quark Network Disk] on the main page; 2. Then enter the Quark Network Disk interface and select the [My Backup] service function; 3. Finally, select [Switch Device] to log in to two new devices.

See all articles