


About the steps for login authentication of WeChat applet
Jun 22, 2018 pm 03:47 PMThe login function is a necessary function for many small programs. By logging into the system, we can record some of the user's behaviors in our small programs, and we can also vaguely confirm the user in the background. The following article mainly introduces relevant information about mini program login authentication. Friends in need can refer to it.
Preface
In order to facilitate the mini program application to use the WeChat login state for authorized login, the WeChat mini program provides the opening of login authorization interface. 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 on the official document here is clear enough, we will directly elaborate on the figure and Replenish.
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 code for the current user Temporary login 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 } } });
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 are the unique identifiers of three 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 https://api.weixin.qq.com/sns/jscode2session provided by WeChat on our own server. This interface needs to bring four parameter fields:
Parameter | Value |
---|---|
appid | The appid of the applet |
secret | Secret of the mini program |
js_code | The code sent by the previous call to wx.login |
grant_type | 'authorization_code' |
從這幾個參數(shù),我們可以看出,要請求這個接口必須先調(diào)用wx.login()來獲取到用戶當(dāng)前會話的code。那么為什么我們要在服務(wù)端來請求這個接口呢?其實是出于安全性的考量,如果我們在前端通過request調(diào)用此接口,就不可避免的需要將我們小程序的appid和小程序的secret暴露在外部,同時也將微信服務(wù)端下發(fā)的session_key暴露給“有心之人”,這就給我們的業(yè)務(wù)安全帶來極大的風(fēng)險。除了需要在服務(wù)端進行session_key的獲取,我們還需要注意兩點:
session_key和微信派發(fā)的code是一一對應(yīng)的,同一code只能換取一次session_key。每次調(diào)用
wx.login()
,都會下發(fā)一個新的code和對應(yīng)的session_key,為了保證用戶體驗和登錄態(tài)的有效性,開發(fā)者需要清楚用戶需要重新登錄時才去調(diào)用wx.login()
session_key是有失效性的,即便是不調(diào)用wx.login,session_key也會過期,過期時間跟用戶使用小程序的頻率成正相關(guān),但具體的時間長短開發(fā)者和用戶都是獲取不到的
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 || '返回數(shù)據(jù)字段不完整' } } else { return data } }); }
3. 生成3rd_session
前面說過通過 session_key 來“間接”地維護登錄態(tài),所謂間接,也就是我們需要 自己維護用戶的登錄態(tài)信息 ,這里也是考慮到安全性因素,如果直接使用微信服務(wù)端派發(fā)的session_key來作為業(yè)務(wù)方的登錄態(tài)使用,會被“有心之人”用來獲取用戶的敏感信息,比如wx.getUserInfo()
這個接口呢,就需要session_key來配合解密微信用戶的敏感信息。
那么我們?nèi)绻勺约旱牡卿洃B(tài)標(biāo)識呢,這里可以使用幾種常見的不可逆的哈希算法,比如md5、sha1等,將生成后的登錄態(tài)標(biāo)識(這里我們統(tǒng)稱為'skey')返回給前端,并在前端維護這份登錄態(tài)標(biāo)識(一般是存入storage)。而在服務(wù)端呢,我們會把生成的skey存在用戶對應(yīng)的數(shù)據(jù)表中,前端通過傳遞skey來存取用戶的信息。
可以看到這里我們使用了sha1算法來生成了一個skey:
const crypto = require('crypto'); return getSessionKey(code, appid, secret) .then(resData => { // 選擇加密算法生成自己的登錄態(tài)標(biāo)識 const { session_key } = resData; const skey = encryptSha1(session_key); }); function encryptSha1(data) { return crypto.createHash('sha1').update(data, 'utf8').digest('hex') }
4. checkSession
前面我們將skey存入前端的storage里,每次進行用戶數(shù)據(jù)請求時會帶上skey,那么如果此時session_key過期呢?所以我們需要調(diào)用到wx.checkSession()
這個API來校驗當(dāng)前session_key是否已經(jīng)過期,這個API并不需要傳入任何有關(guān)session_key的信息參數(shù),而是微信小程序自己去調(diào)自己的服務(wù)來查詢用戶最近一次生成的session_key是否過期。如果當(dāng)前session_key過期,就讓用戶來重新登錄,更新session_key,并將最新的skey存入用戶數(shù)據(jù)表中。
checkSession這個步驟呢,我們一般是放在小程序啟動時就校驗登錄態(tài)的邏輯處,這里貼個校驗登錄態(tài)的流程圖:
下面代碼即校驗登錄態(tài)的簡單流程:
let loginFlag = wx.getStorageSync('skey'); if (loginFlag) { // 檢查 session_key 是否過期 wx.checkSession({ // session_key 有效(未過期) success: function() { // 業(yè)務(wù)邏輯處理 }, // session_key 過期 fail: function() { // session_key過期,重新登錄 doLogin(); } }); ) else { // 無skey,作為首次登錄 doLogin(); }
5. 支持emoji表情存儲
如果需要將用戶微信名存入數(shù)據(jù)表中,那么就確認數(shù)據(jù)表及數(shù)據(jù)列的編碼格式。因為用戶微信名可能會包含emoji圖標(biāo),而常用的UTF8編碼只支持1-3個字節(jié),emoji圖標(biāo)剛好是4個字節(jié)的編碼進行存儲。
這里有兩種方式(以mysql為例):
1.設(shè)置存儲字符集
在mysql5.5.3版本后,支持將數(shù)據(jù)庫及數(shù)據(jù)表和數(shù)據(jù)列的字符集設(shè)置為 utf8mb4 ,因此可在 /etc/my.cnf 設(shè)置默認字符集編碼及服務(wù)端編碼格式
// 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
設(shè)置完默認字符集編碼及服務(wù)端字符集編碼,如果是對已經(jīng)存在的表和字段進行編碼轉(zhuǎn)換,需要執(zhí)行下面幾個步驟:
設(shè)置數(shù)據(jù)庫字符集為 utf8mb4
ALTER DATABASE 數(shù)據(jù)庫名稱 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
設(shè)置數(shù)據(jù)表字符集為 utf8mb4
ALTER TABLE 數(shù)據(jù)表名稱 CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
設(shè)置數(shù)據(jù)列字段字符集為 utf8mb4
ALTER TABLE 數(shù)據(jù)表名稱 CHANGE 字段列名稱 VARCHAR(n) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
這里的 COLLATE 指的是排序字符集,也就是用來對存儲的字符進行排序和比較的, utf8mb4 常用的collation有兩種: utf8mb4_unicode_ci 和 utf8mb4_general_ci ,一般建議使用 utf8mb4_unicode_ci ,因為它是基于標(biāo)準(zhǔn)的 Unicode Collation Algorithm(UCA) 來排序的,可以在各種語言進行精確排序。這兩種排序方式的具體區(qū)別可以參考: What's the difference between utf8_general_ci and utf8_unicode_ci
2.通過使用sequelize對emoji字符進行編碼入庫,使用時再進行解碼
這里是sequelize的配置,可參考 Sequelize文檔
{ dialect: 'mysql', // 數(shù)據(jù)庫類型 dialectOptions: { charset: 'utf8mb4', collate: "utf8mb4_unicode_ci" }, }
最后
前面講了微信小程序如何接入微信登錄態(tài)標(biāo)識的詳細流程,那么如何獲取小程序中的用戶數(shù)據(jù)以及對用戶敏感數(shù)據(jù)進行解密,并保證用戶數(shù)據(jù)的完整性,我將在下一篇文章給大家做一個詳細地介紹。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,更多相關(guān)內(nèi)容請關(guān)注PHP中文網(wǎng)!
相關(guān)推薦:
微信小程序開發(fā)中怎樣實現(xiàn)地址頁面三級聯(lián)動
The above is the detailed content of About the steps for login authentication of WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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 card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

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

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

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
