


Understand the front-end design and implementation of WeChat mini program login
Oct 28, 2020 pm 05:24 PMTodayWeChat Mini Program Development column introduces the front-end design and implementation of mini program login.
1. Preface
The purpose of the login/registration design is of course to make this the basic capability of the application and be robust enough to avoid the occurrence of the whole site. sexual obstruction.
At the same time, we must fully consider how to decouple and encapsulate. When developing new small programs, we can quickly remove reuse capabilities and avoid repeated pitfalls.
The login and registration module is like an iceberg. We think it is just "enter your account and password, and you are logged in." But in fact, there are various issues that need to be considered.
Here, I would like to share with you all the design experiences and ideas I have accumulated after recently completing a small program login/registration module.
2. Business Scenario
In the process of users browsing the mini program, due to business needs, it is often necessary to obtain some basic information of the user. Common ones include:
- 微信nickname
- 微信手機
Different products have different information requirements for users, and will also have different authorization processes.
The first type is common in e-commerce systems. When users purchase goods, in order to identify the user's multi-platform account, they often use their mobile phone number to make a contact. In this case, the user needs to authorize the mobile phone number.
Second, in order to get basic initialization of user information, it is often necessary to obtain further user information: such as WeChat nickname, unionId
, etc. User authorization is required.
The third type includes the first type and the second type.
3. Concept
With the goal of precipitating a set of universal mini program login solutions and services, let’s analyze the business and derive the variables.
Before doing technical design, talk some necessary nonsense and conduct basic tuning on some concepts.
2.1 About "Login"
Login is "login" in English, and the corresponding one is "logout". Before logging in, you need to have an account and "register" (or sign up).
It is said that the initial product did not have a login/registration function, but it gradually became available as more people used it. Due to the needs of the product itself, the "user" needs to be identified.
In the real society, each of us has an identity ID: ID card. When I turned 16, I completed a "registration" when I went to the Public Security Bureau to get my ID card for the first time. Then I went to the Internet cafe to surf the Internet, swiped my ID card, and completed the "login" behavior.
So for the Internet in the virtual world, this identity certificate is "account password".
Common login/registration methods are:
-
Account and password registration
In the early days of the Internet, personal email and mobile phone Coverage is small. Therefore, the user needs to think of an account name. We register a QQ account, which is this form.
-
Email address registration
After the millennium, the PC Internet era has rapidly become popular, and we have all created Get your own personal email. In addition, QQ also comes with an email account. Since email is personal and private and can communicate information, most websites have begun to use email accounts as user names for registration, and during the registration process they will be asked to log in to the corresponding email to check for activation emails to verify that we have Ownership of the registered email address.
-
Mobile Number Registration
After the popularization of the Internet, smartphones and mobile Internet developed rapidly. Mobile phones have become an indispensable mobile device for everyone, and the mobile Internet has been deeply integrated into everyone's modern life. Therefore, compared to email, mobile phone numbers are currently more closely related to individuals, and more and more mobile applications are emerging, and registration methods that use mobile phone numbers as user names are also widely used.
# By 2020, the number of WeChat users will reach 1.2 billion. Well, WeChat accounts, at least in China, have become the "identity mark" of the new generation of the Internet world.
For WeChat applet, it is natural to know the WeChat account ID of the current user. WeChat allows mini program applications to quietly "log in" to our mini program applications without the user being aware of it. This is what we often call "silent login."
In fact, the login of WeChat applet is essentially the same concept as the "single sign-on" of traditional web applications.
- Single sign-on: After logging in at station A, station C and station B can achieve fast "silent login".
- WeChat mini program login: In WeChat, if you log in to your WeChat account, you can achieve "silent login" in the entire mini program ecosystem.
Since Http is originally stateless, the industry’s basic general approach to login state is:
- cookie-session: commonly used in browser applications
- access token: often used in non-browser applications such as mobile terminals
In the WeChat applet, the "JS logic layer" is not a browser environment, and naturally there is no Cookie
, then access token
is usually used.
2.2 About "Authorization"
For products that need to further obtain user nicknames, user mobile phone numbers and other information. For the sake of user privacy, WeChat requires users to actively agree to authorize. Only mini program applications can obtain this part of the information. This is the interaction of the currently popular mini programs "authorized user information" and "authorized mobile phone number".
Due to the different sensitivities of different user information, WeChat mini programs provide different "authorization" methods for different user information:
- Call the specific API method, Pop-up authorization.
- For example, when calling
wx.getLocation()
, if the user is not authorized, the address authorization interface will pop up. - If rejected, the window will not pop up again, and
wx.getLocation()
will directly return failure.
- For example, when calling
-
<button open-type="xxx"></button>
method.- Only supports: user sensitive information and user mobile phone number. You need to cooperate with the backend for symmetric encryption and decryption to obtain the data.
- The user has declined. If you click the button again, the pop-up window will still appear.
- Through
wx.authorize()
, ask for authorization in advance, and there is no need to pop up the authorization again when you need to obtain relevant information later.
4. Detailed Design
After sorting out the concepts, our modules can be divided into two large blocks:
-
Login: Responsible for creating a session with the server. This session implements silent login and related fault-tolerance processing. The module is named:
Session
- ##Authorization: Responsible for interacting with users, obtaining and updating information, and controlling permissions, etc. The module is named: Auth
3.1 .1 Silent login
The official login solution provided by WeChat is summarized in three steps:
- wx.login()
- Obtain the one-time encryption certificate code and hand it to the backend.
The backend transmits this code to the WeChat server in exchange for the user's unique identifier
openId - and authorization certificate
session_key
. (Special API calls used for subsequent server-side and WeChat servers, see for details: WeChat official documentation - server-side acquisition of open data).The backend transmits the user credentials obtained from the WeChat server and the self-generated login credentials (token) to the frontend. The front end saves it and brings it to the back end the next time it is requested, so that it can identify which user.
- If you just implement this process, it is quite simple.
But to achieve a robust login process, you need to pay attention to more edge cases:
- Collapse
wx.login() Call
wx.login():
Becausewill produce unpredictable side effects, for example, it may cause
session_key
to become invalid, resulting in subsequent authorization Failure in decryption scenarios. We can provide a method likesession.login()
here to take control ofwx.login()
and perform a series of encapsulation and fault tolerance processing on it. - Timing of the call
: Usually when the application starts (
app.onLaunch()), Go to initiate a silent login. However, there is an asynchronous problem caused by the applet life cycle design problem: when loading the page, when calling a back-end API that requires login state, the previous asynchronous static login process may not be completed, resulting in a request fail.
<p> Of course, you can also initiate a login call in an asynchronous blocking manner when the first interface that requires login status is called. This requires a well-designed interface layer. </p> <p>The detailed design ideas for the two scenarios mentioned above will be discussed below. </p>
-
Problems with concurrent calls:
In business scenarios, it is inevitable that there will be multiple codes that need to trigger login. If you encounter extreme situations, These multiple codes initiate calls at the same time. That will cause the login process to be initiated multiple times in a short period of time, even though the previous request has not been completed. For this situation, we can block the first call and wait for the result of subsequent calls, just like the process of combining sperm and eggs.
-
Problems with unexpired calls:
If our login status has not expired, it can be used normally. By default, there is no need to call again. Go and initiate the login process. At this time, we can first check whether the login state is available by default. If not, we can initiate a request. Then you can also provide a parameter similar to
session.login({ force: true })
to force login.
3.1.2 Handling of silent login asynchronous state
1. Called when the application starts
because in most cases They all need to rely on the login state. We will naturally think of calling this call when the application starts (app.onLaunch()
).
However, due to the native applet startup process, the life cycle hook functions of App
, Page
, Component
do not support asynchronous blocking. .
Then we can easily encounter that the "login process" initiated by app.onLaunch
has not been completed at page.onLoad
, and we will not be able to do it correctly. Some operations rely on login status.
In response to this situation, we designed a state machine tool: status
Based on the state machine, we can write code like this:
import?{?Status?}?from?'@beautywe/plugin-status';//?on?app.jsApp({????status:?{???????login:?new?Status('login'); ????},????onLaunch()?{ ????????session????????????//?發(fā)起靜默登錄調(diào)用 ????????????.login()????????????//?把Understand the front-end design and implementation of WeChat mini program login設(shè)置為?success ????????????.then(()?=>?this.status.login.success())?????? ????????????//?把Understand the front-end design and implementation of WeChat mini program login設(shè)置為?fail ????????????.catch(()?=>?this.status.login.fail()); ????}, });//?on?page.jsPage({????onLoad()?{??????const?loginStatus?=?getApp().status.login;?????? ??????//?must?里面會進行狀態(tài)的判斷,例如登錄中就等待,登錄成功就直接返回,登錄失敗拋出等。 ??????loginStatus().status.login.must(()?=>?{????????//?進行一些需要登錄態(tài)的操作... ??????}); ????}, });復(fù)制代碼
2. Initiate login when the "first interface that requires login state" is called
Further, we will find that a deeper level of login state is required The node is when launching the "backend API that requires login status".
Then we can initiate "silent login" when calling "backend API that requires login status". For concurrent scenarios, just let other requests wait.
Using fly.js as the "network request layer" encapsulated by wx.request()
, make a simple example:
//?發(fā)起請求,并表明該請求是需要登錄態(tài)的fly.post('https://...',?params,?{?needLogin:?true?});//?在?fly?攔截器中處理邏輯fly.interceptors.request.use(async?(req)=>{??//?在請求需要登錄態(tài)的時候 ??if?(req.needLogin?!==?false)?{????//?ensureLogin?核心邏輯是:判斷是否已登錄,如否發(fā)起登錄調(diào)用,如果正在登錄,則進入隊列等待回調(diào)。 ????await?session.ensureLogin();???? ????//?登錄成功后,獲取?token,通過?headers?傳遞給后端。 ????const?token?=?await?session.getToken();????Object.assign(req.headers,?{?[AUTH_KEY_NAME]:?token?}); ??}?? ??return?req; });復(fù)制代碼
3.1.3 Custom login state Expired fault-tolerance processing
When the custom login state expires, the backend needs to return a specific status code, such as: AUTH_EXPIRED
, AUTH_INVALID
, etc.
The front end can monitor the status code of all requests in the "network request layer", and then initiate a refresh of the login status, and then replay the failed request:
//?添加響應(yīng)攔截器fly.interceptors.response.use(????(response)?=>?{??????const?code?=?res.data;???????? ??????//?登錄態(tài)過期或失效 ??????if?(?['AUTH_EXPIRED',?'AUTH_INVALID'].includes(code)?)?{?????? ????????//?刷新登錄態(tài) ????????await?session.refreshLogin();???????? ????????//?然后重新發(fā)起請求 ????????return?fly.request(request); ??????} ????} )復(fù)制代碼
Then if there are multiple concurrent requests Each request returns a status code indicating that the login status is invalid, and the above code will be executed multiple times.
We need to do some special fault-tolerance processing for session.refreshLogin()
:
- Request lock: At the same time, only A network request in progress.
- Waiting queue: After the request is locked, all calls to this method are pushed into a queue, waiting for the network request to be completed to share the return result.
- Circuit breaker mechanism: If called multiple times in a short period of time, it will stop responding for a period of time, similar to TCP slow start.
Sample code:
class?Session?{??//?.... ?? ??//?刷新登錄保險絲,最多重復(fù)?3?次,然后熔斷,5s?后恢復(fù) ??refreshLoginFuseLine?=?REFRESH_LOGIN_FUSELINE_DEFAULT; ??refreshLoginFuseLocked?=?false; ??refreshLoginFuseRestoreTime?=?5000;??//?熔斷控制 ??refreshLoginFuse():?Promise<void>?{????if?(this.refreshLoginFuseLocked)?{??????return?Promise.reject('刷新登錄-保險絲已熔斷,請稍后'); ????}????if?(this.refreshLoginFuseLine?>?0)?{??????this.refreshLoginFuseLine?=?this.refreshLoginFuseLine?-?1;??????return?Promise.resolve(); ????}?else?{??????this.refreshLoginFuseLocked?=?true;??????setTimeout(()?=>?{????????this.refreshLoginFuseLocked?=?false;????????this.refreshLoginFuseLine?=?REFRESH_LOGIN_FUSELINE_DEFAULT; ????????logger.info('刷新登錄-保險絲熔斷解除'); ??????},?this.refreshLoginFuseRestoreTime);??????return?Promise.reject('刷新登錄-保險絲熔斷!!'); ????} ??}??//?并發(fā)回調(diào)隊列 ??refreshLoginQueueMaxLength?=?100; ??refreshLoginQueue:?any[]?=?[]; ??refreshLoginLocked?=?false;??//?刷新登錄態(tài) ??refreshLogin():?Promise<void>?{????return?Promise.resolve()???? ??????//?回調(diào)隊列?+?熔斷?控制 ??????.then(()?=>?this.refreshLoginFuse()) ??????.then(()?=>?{????????if?(this.refreshLoginLocked)?{??????????const?maxLength?=?this.refreshLoginQueueMaxLength;??????????if?(this.refreshLoginQueue.length?>=?maxLength)?{????????????return?Promise.reject(`refreshLoginQueue?超出容量:${maxLength}`); ??????????}??????????return?new?Promise((resolve,?reject)?=>?{????????????this.refreshLoginQueue.push([resolve,?reject]); ??????????}); ????????}????????this.refreshLoginLocked?=?true; ??????})??????//?通過前置控制之后,發(fā)起登錄過程 ??????.then(()?=>?{????????this.clearSession(); ????????wx.showLoading({?title:?'刷新登錄態(tài)中',?mask:?true?});????????return?this.login() ??????????.then(()?=>?{ ????????????wx.hideLoading(); ????????????wx.showToast({?icon:?'none',?title:?'登錄成功'?});????????????this.refreshLoginQueue.forEach(([resolve])?=>?resolve());????????????this.refreshLoginLocked?=?false; ??????????}) ??????????.catch(err?=>?{ ????????????wx.hideLoading(); ????????????wx.showToast({?icon:?'none',?title:?'登錄失敗'?});????????????this.refreshLoginQueue.forEach(([,?reject])?=>?reject());????????????this.refreshLoginLocked?=?false;????????????throw?err; ??????????}); ??????});??//?...}復(fù)制代碼</void></void>
3.1.4 Fault tolerance processing of WeChat session_key expiration
After we start the "silent login" above, the WeChat server will issue A session_key
is given to the backend, and this will be used when it is necessary to obtain WeChat open data.
And session_key
is time-sensitive. The following is taken from the official description of WeChat:
Session key session_key validity
If developers encounter signature verification failure or decryption failure due to incorrect session_key, please pay attention to the following precautions related to session_key.
- wx.login 調(diào)用時,用戶的 session_key 可能會被更新而致使舊 session_key 失效(刷新機制存在最短周期,如果同一個用戶短時間內(nèi)多次調(diào)用 wx.login,并非每次調(diào)用都導(dǎo)致 session_key 刷新)。開發(fā)者應(yīng)該在明確需要重新登錄時才調(diào)用 wx.login,及時通過 auth.code2Session 接口更新服務(wù)器存儲的 session_key。
- 微信不會把 session_key 的有效期告知開發(fā)者。我們會根據(jù)用戶使用小程序的行為對 session_key 進行續(xù)期。用戶越頻繁使用小程序,session_key 有效期越長。
- 開發(fā)者在 session_key 失效時,可以通過重新執(zhí)行登錄流程獲取有效的 session_key。使用接口 wx.checkSession可以校驗 session_key 是否有效,從而避免小程序反復(fù)執(zhí)行登錄流程。
- 當(dāng)開發(fā)者在實現(xiàn)自定義登錄態(tài)時,可以考慮以 session_key 有效期作為自身登錄態(tài)有效期,也可以實現(xiàn)自定義的時效性策略。
翻譯成簡單的兩句話:
-
session_key
時效性由微信控制,開發(fā)者不可預(yù)測。 -
wx.login
可能會導(dǎo)致session_key
過期,可以在使用接口之前用wx.checkSession
檢查一下。
而對于第二點,我們通過實驗發(fā)現(xiàn),偶發(fā)性的在 session_key
已過期的情況下,wx.checkSession
會概率性返回 true
社區(qū)也有相關(guān)的反饋未得到解決:
- 小程序解密手機號,隔一小段時間后,checksession:ok,但是解密失敗
- wx.checkSession有效,但是解密數(shù)據(jù)失敗
- checkSession判斷session_key未失效,但是解密手機號失敗
所以結(jié)論是:wx.checkSession
可靠性是不達 100% 的。
基于以上,我們需要對 session_key
的過期做一些容錯處理:
- 發(fā)起需要使用
session_key
的請求前,做一次wx.checkSession
操作,如果失敗了刷新登錄態(tài)。 - 后端使用
session_key
解密開放數(shù)據(jù)失敗之后,返回特定錯誤碼(如:DECRYPT_WX_OPEN_DATA_FAIL
),前端刷新登錄態(tài)。
示例代碼:
//?定義檢查?session_key?有效性的操作const?ensureSessionKey?=?async?()?=>?{??const?hasSession?=?await?new?Promise(resolve?=>?{ ????wx.checkSession({??????success:?()?=>?resolve(true),??????fail:?()?=>?resolve(false), ????}); ??});?? ??if?(!hasSession)?{ ????logger.info('sessionKey?已過期,刷新登錄態(tài)');????//?接上面提到的刷新登錄邏輯 ????return?session.refreshLogin(); ??}??return?Promise.resolve(); }//?在發(fā)起請求的時候,先做一次確保?session_key?最新的操作(以?fly.js?作為網(wǎng)絡(luò)請求層為例)const?updatePhone?=?async?(params)?=>?{??await?ensureSessionKey();??const?res?=?await?fly.post('https://xxx',?params); }//?添加響應(yīng)攔截器,?監(jiān)聽網(wǎng)絡(luò)請求返回fly.interceptors.response.use(????(response)?=>?{??????const?code?=?res.data;???????? ??????//?登錄態(tài)過期或失效 ??????if?(?['DECRYPT_WX_OPEN_DATA_FAIL'].includes(code))?{????????//?刷新登錄態(tài) ????????await?session.refreshLogin();???????? ????????//?由于加密場景的加密數(shù)據(jù)由用戶點擊產(chǎn)生,session_key?可能已經(jīng)更改,需要用戶重新點擊一遍。 ????????wx.showToast({?title:?'網(wǎng)絡(luò)出小差了,請稍后重試',?icon:?'none'?}); ??????} ????} )復(fù)制代碼
3.2 授權(quán)的實現(xiàn)
3.2.1 組件拆分與設(shè)計
在用戶信息和手機號獲取的方式上,微信是以 <button open-type="'xxx'"></button>
的方式,讓用戶主動點擊授權(quán)的。
那么為了讓代碼更解耦,我們設(shè)計這樣三個組件:
-
<user-contaienr getuserinfo="onUserInfoAuth"></user-contaienr>
: 包裝點擊交互,通過<slot></slot>
支持點擊區(qū)域的自定義UI。 -
<phone-container getphonennmber="onPhoneAuth"></phone-container>
: 與<user-container></user-container>
同理。 -
<auth-flow></auth-flow>
: 根據(jù)業(yè)務(wù)需要,組合<user-container></user-container>
、<phone-container></phone-container>
組合來定義不同的授權(quán)流程。
以開頭的業(yè)務(wù)場景的流程為例,它有這樣的要求:
- 有多個步驟。
- 如果中途斷掉了,可以從中間接上。
- 有些場景中,只要求達到「用戶信息授權(quán)」,而不需要完成「用戶手機號」。
那么授權(quán)的階段可以分三層:
//?用戶登錄的階段export?enum?AuthStep?{??//?階段一:只有登錄態(tài),沒有用戶信息,沒有手機號 ??ONE?=?1,??//?階段二:有用戶信息,沒有手機號 ??TWO?=?2,??//?階段三:有用戶信息,有手機號 ??THREE?=?3, }復(fù)制代碼
AuthStep
的推進過程是不可逆的,我們可以定義一個 nextStep
函數(shù)來封裝 AuthStep 更新的邏輯。外部使用的話,只要無腦調(diào)用 nextStep
方法,等待回調(diào)結(jié)果就行。
示例偽代碼:
//?auth-flow?componentComponent({??//?... ?? ??data:?{????//?默認(rèn)情況下,只需要到達階段二。 ????mustAuthStep:?AuthStep.TWO ??},?? ??//?允許臨時更改組件的需要達到的階段。 ??setMustAuthStep(mustAuthStep:?AuthStep)?{????this.setData({?mustAuthStep?}); ??},?? ??//?根據(jù)用戶當(dāng)前的信息,計算用戶處在授權(quán)的階段 ??getAuthStep()?{????let?currAuthStep;???? ????//?沒有用戶信息,尚在第一步 ????if?(!session.hasUser()?||?!session.hasUnionId())?{ ??????currAuthStep?=?AuthStepType.ONE; ????}????//?沒有手機號,尚在第二步 ????if?(!session.hasPhone())?{ ??????currAuthStep?=?AuthStepType.TWO; ????}????//?都有,尚在第三步 ????currAuthStep?=?AuthStepType.THREE;????return?currAuthStep; ??}?? ??//?發(fā)起下一步授權(quán),如果都已經(jīng)完成,就直接返回成功。 ??nextStep(e)?{????const?{?mustAuthStep?}?=?this.data;????const?currAuthStep?=?this.updateAuthStep();?? ????//?已完成授權(quán) ????if?(currAuthStep?>=?mustAuthStep?||?currAuthStep?===?AuthStepType.THREE)?{??????//?更新全局的授權(quán)Understand the front-end design and implementation of WeChat mini program login,廣播消息給訂閱者。 ??????return?getApp().status.auth.success(); ????}????//?第一步:更新用戶信息 ????if?(currAuthStep?===?AuthStepType.ONE)?{??????//?已有密文信息,更新用戶信息 ??????if?(e)?session.updateUser(e);??????//?更新到視圖層,展示對應(yīng)UI,等待獲取用戶信息 ??????else?this.setData({?currAuthStep?});??????return; ????}????//?第二步:更新手機信息 ????if?(currAuthStep?===?AuthStepType.TWO)?{??????//?已有密文信息,更新手機號 ??????if?(e)?this.bindPhone(e);??????//?未有密文信息,彈出獲取窗口 ??????else?this.setData({?currAuthStep?});??????return; ????}????console.warn('auth.nextStep?錯誤',?{?currAuthStep,?mustAuthStep?}); ??},?? ??//?...});復(fù)制代碼
那么我們的 <auth-flow></auth-flow>
中就可以根據(jù) currAuthStep
和 mustAuthStep
來去做不同的 UI 展示。需要注意的是使用 <user-container></user-container>
、<phone-container></phone-container>
的時候連接上 nextStep(e)
函數(shù)。
示例偽代碼:
<view> ??<!-- 已完成授權(quán) --> ??<block> ????<view>已完成授權(quán)</view> ??</block> ??<!-- 未完成授權(quán),第一步:Understand the front-end design and implementation of WeChat mini program login --> ??<block> ????<user-container> ??????<view>Understand the front-end design and implementation of WeChat mini program login</view> ????</user-container> ??</block> ??<!-- 未完成授權(quán),第二步:Understand the front-end design and implementation of WeChat mini program login --> ??<block> ????<phone-container> ??????<view>Understand the front-end design and implementation of WeChat mini program login</view> ????</phone-container> ??</block> ??</view>復(fù)制代碼
3.2.2 權(quán)限攔截的處理
到這里,我們制作好了用來承載授權(quán)流程的組件 <auth-flow></auth-flow>
,那么接下來就是決定要使用它的時機了。
我們梳理需要授權(quán)的場景:
-
點擊某個按鈕,例如:購買某個商品。
對于這種場景,常見的是通過彈窗完成授權(quán),用戶可以選擇關(guān)閉。
-
瀏覽某個頁面,例如:訪問個人中心。
對于這種場景,我們可以在點擊跳轉(zhuǎn)某個頁面的時候,進行攔截,彈窗處理。但這樣的缺點是,跳轉(zhuǎn)到目標(biāo)頁面的地方可能會很多,每個都攔截,難免會錯漏。而且當(dāng)目標(biāo)頁面作為「小程序落地頁面」的時候,就避免不了。
這時候,我們可以通過重定向到授權(quán)頁面來完成授權(quán)流程,完成之后,再回來。
那么我們定義一個枚舉變量:
//?授權(quán)的展示形式export?enum?AuthDisplayMode?{??//?以彈窗形式 ??POPUP?=?'button',??//?以頁面形式 ??PAGE?=?'page', }復(fù)制代碼
我們可以設(shè)計一個 mustAuth
方法,在點擊某個按鈕,或者頁面加載的時候,進行授權(quán)控制。
偽代碼示例:
class?Session?{??//?... ?? ??mustAuth({ ????mustAuthStep?=?AuthStepType.TWO,?//?需要授權(quán)的LEVEL,默認(rèn)需要獲取用戶資料 ????popupCompName?=?'auth-popup', //?授權(quán)彈窗組件的?id ????mode?=?AuthDisplayMode.POPUP,?//?默認(rèn)以彈窗模式 ??}?=?{}):?Promise<void>?{???? ????//?如果當(dāng)前的授權(quán)步驟已經(jīng)達標(biāo),則返回成功 ????if?(this.currentAuthStep()?>=?mustAuthStep)?return?Promise.resolve();????//?嘗試獲取當(dāng)前頁面的?<auth-popup></auth-popup>?組件實例 ????const?pages?=?getCurrentPages();????const?curPage?=?pages[pages.length?-?1];????const?popupComp?=?curPage.selectComponent(`#${popupCompName}`);????//?組件不存在或者顯示指定頁面,跳轉(zhuǎn)到授權(quán)頁面 ????if?(!popupComp?||?mode?===?AuthDisplayMode.PAGE)?{??????const?curRoute?=?curPage.route;??????//?跳轉(zhuǎn)到授權(quán)頁面,帶上當(dāng)前頁面路由,授權(quán)完成之后,回到當(dāng)前頁面。 ??????wx.redirectTo({?url:?`authPage?backTo=${encodeURIComponent(curRoute)}`?});??????return?Promise.resolve(); ????}???? ????//?設(shè)置授權(quán)?LEVEL,然后調(diào)用?<auth-popup>?的?nextStep?方法,進行進一步的授權(quán)。 ????popupComp.setMustAuthStep(mustAuthStep); ????popupComp.nextStep();????//?等待成功回調(diào)或者失敗回調(diào) ????return?new?Promise((resolve,?reject)?=>?{??????const?authStatus?=?getApp().status.auth; ??????authStatus.onceSuccess(resolve); ??????authStatus.onceFail(reject); ????}); ??}?? ??//?...}復(fù)制代碼</auth-popup></void>
那么我們就能在按鈕點擊,或者頁面加載的時候進行授權(quán)攔截:
Page({??onLoad()?{ ????session.mustAuth().then(()?=>?{??????//?開始初始化頁面... ????}); ??}?? ??onClick(e)?{ ????session.mustAuth().then(()?=>?{??????//?開始處理回調(diào)邏輯... ????}); ??} })復(fù)制代碼
當(dāng)然,如果項目使用了 TS 的話,或者支持 ES7 Decorator 特性的話,我們可以為 mustAuth
提供一個裝飾器版本:
export?function?mustAuth(option?=?{})?{??return?function( ????_target, ????_propertyName, ????descriptor,??)?{????//?劫持目標(biāo)方法 ????const?method?=?descriptor.value;???? ????//?重寫目標(biāo)方法 ????descriptor.value?=?function(...args:?any[])?{??????return?session.mustAuth(option).then(()?=>?{????????//?登錄完成之后,重放原來方法 ????????if?(method)?return?method.apply(this,?args); ??????}); ????}; ??}; }復(fù)制代碼
那么使用方式就簡單一些了:
Page({ ??@mustAuth();??onLoad()?{????//?開始初始化頁面... ??} ?? ??@mustAuth();??onClick(e)?{????//?開始處理回調(diào)邏輯... ??} });復(fù)制代碼
3.3. 前后端交互協(xié)議整理
作為一套可復(fù)用的小程序登錄方案,當(dāng)然需要去定義好前后端的交互協(xié)議。
那么整套登錄流程下來,需要的接口有這么幾個:
-
靜默登錄 silentLogin
- 入?yún)ⅲ?ol>
- code: 產(chǎn)自 wx.login()
- 出參:
- token: 自定義登錄態(tài)憑證
- userInfo: 用戶信息
- 說明:
- 后端利用 code 跟微信客戶端換取用戶標(biāo)識,然后注冊并登錄用戶,返回自定義登錄態(tài)
token
給前端 -
token
前端會存起來,每個請求都會帶上 - userInfo 需要包含
nickname
和phone
字段,前端用于計算當(dāng)前用戶的授權(quán)階段。當(dāng)然這個狀態(tài)的記錄可以放在后端,但是我們認(rèn)為放在前端,會更加靈活。
- 后端利用 code 跟微信客戶端換取用戶標(biāo)識,然后注冊并登錄用戶,返回自定義登錄態(tài)
更新用戶信息 updateUser
- 入?yún)ⅲ?ol>
- nickname: 用戶昵稱
- encrypt: Understand the front-end design and implementation of WeChat mini program login相關(guān)的
iv
,encryptedData
- 以及其他如性別地址等非必要字段
- userInfo:更新后的最新用戶信息
- 后端解密Understand the front-end design and implementation of WeChat mini program login,獲取隱蔽數(shù)據(jù),如:
unionId
等 - 后端支持更新包括
nickname
等用戶基本信息。 - 前端會把 userInfo 信息更新到
session
中,用于計算授權(quán)階段。
更新用戶手機號 updatePhone
- 入?yún)ⅲ?ol>
- encrypt:Understand the front-end design and implementation of WeChat mini program login相關(guān)的
iv
,encryptedData
- userInfo:更新后的最新用戶信息
- 后端解密開放式局,獲取手機號,并更新到用戶信息中。
- 前端會把 userInfo 信息更新到
session
中,用于計算授權(quán)階段。
解綁手機號 unbindPhone
- 入?yún)ⅲ?
- 出參:-
- 說明:后端解綁用戶手機號,成功與否,走業(yè)務(wù)定義的前后端協(xié)議。
登錄 logout
入?yún)ⅲ?
出參:-
說明:后端主動過期登錄態(tài),成功與否,走業(yè)務(wù)定義的前后端協(xié)議。
五. 架構(gòu)圖
最后我們來梳理一下整體的「登錄服務(wù)」的架構(gòu)圖:
由「登錄服務(wù)」和「底層建設(shè)」組合提供的通用服務(wù),業(yè)務(wù)層只需要去根據(jù)產(chǎn)品需求,定制授權(quán)的流程 <auth-flow></auth-flow>
,就能滿足大部分場景了。
六. 總結(jié)
本篇文章通過一些常見的登錄授權(quán)場景來展開來描述細(xì)節(jié)點。
整理了「登錄」、「授權(quán)」的概念。
然后分別針對「登錄」介紹了一些關(guān)鍵的技術(shù)實現(xiàn):
- Silent login
- Handling of silent login asynchronous state
- Fault-tolerant processing of custom login state expiration
- WeChat
session_key
Expired Fault-tolerant processing
As for "authorization", there will be the logic of designing the UI part, and it also needs to involve the splitting of components:
- Component splitting and design
- Processing of permission interception
Then, we sorted out the back-end interfaces that this login authorization scheme relies on, and gave the simplest reference protocol.
Finally, from the perspective of "with the goal of precipitating a set of universal mini program login solutions and services", we sorted out the layering at the architectural level.
- Business customization layer
- Login service layer
- Underlying construction
Related free learning recommendations:WeChat Mini Program Development
The above is the detailed content of Understand the front-end design and implementation of WeChat mini program login. 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)

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

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

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

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.

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;

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.

Xiaohongshu has now been integrated into the daily lives of many people, and its rich content and convenient operation methods make users enjoy it. Sometimes, we may forget the account password. It is really annoying to only remember the account but not be able to log in. 1. How to log in if Xiaohongshu only remembers the account? When we forget our password, we can log in to Xiaohongshu through the verification code on our mobile phone. The specific operations are as follows: 1. Open the Xiaohongshu App or the web version of Xiaohongshu; 2. Click the "Login" button and select "Account and Password Login"; 3. Click the "Forgot your password?" button; 4. Enter your account number. Click "Next"; 5. The system will send a verification code to your mobile phone, enter the verification code and click "OK"; 6. Set a new password and confirm. You can also use a third-party account (such as

Baidu Netdisk can not only store various software resources, but also share them with others. It supports multi-terminal synchronization. If your computer does not have a client downloaded, you can choose to enter the web version. So how to log in to Baidu Netdisk web version? Let’s take a look at the detailed introduction. Baidu Netdisk web version login entrance: https://pan.baidu.com (copy the link to open in the browser) Software introduction 1. Sharing Provides file sharing function, users can organize files and share them with friends in need. 2. Cloud: It does not take up too much memory. Most files are saved in the cloud, effectively saving computer space. 3. Photo album: Supports the cloud photo album function, import photos to the cloud disk, and then organize them for everyone to view.?
