


A brief analysis of how to implement the login function in mini programs
Dec 06, 2021 am 10:11 AMHow to implement the login function in the mini program? This article will introduce to you the correct way to open the mini program login. I hope it will be helpful to you!
Mini Program Network Component
https://developers.weixin.qq.com/miniprogram /dev/api/network/request/wx.request.html
RequestTask Description
wx.request(Object object) attribute
Only the more commonly used attributes are listed here, all attributes please See Link.
Type | Default value | Required | Description | |
---|---|---|---|---|
string |
## is the |
developer server Interface address | ||
string/object/ArrayBuffer |
No |
Requested Parameter | ||
Object | ##No | Set the requested header, in the header Referer cannot be set. content-type | Default isapplication/json
| timeout|
No | Timeout in millisecondsmethod | |||
GET | No | HTTP request method | success | |
No | Callback function for successful interface callfail | |||
No | Callback function for interface call failurecomplete | |||
##No |
Interface The callback function that ends the call (will be executed if the call is successful or failed) even if it is an aborted request! |
Parameters It's all an object. Easy to remember and easy to expand.
all have the same result processing method: they all have three callback attributes: success, fail, and complete.
- Introduction to the errMsg object in various situations when the interface is executed.
Callback attribute
fail | |||||||||||||||||
abort | |||||||||||||||||
Sample code let reqTask = wx.request({ url: getApp().globalData.api, success(res) { if (res.errMsg === "request:ok") console.log("res", res); }, fail(err) { // if(err.errMsg.indexOf('request:fail')>-1) console.log('err', err); if (/^request:fail/i.test(err.errMsg)) console.log("err", err); }, complete(res) { console.log("resOrErr", res); }, }); const reqTaskOnHeadersReceived = (headers) => { reqTask.offHeadersReceived(reqTaskOnHeadersReceived); console.log("headers", headers); // 由于請求還未完全結束,所以我們沒辦法獲得請求的狀態(tài)碼,但是我們可以通過返回的requestBody的長度來進行判斷。 // 兩點說明:1. 兩個~~可以把字符串數(shù)字快速轉化為數(shù)字。 // 2. 為什么取小于19,是由于后臺返回沒有權限的requestBody的時候Content-length為“18”,正常情況下是大于19的。所以具體多少得看一下具體情況。 if (~~headers.header["Content-length"] < 19) reqTask.abort(); }; reqTask.onHeadersReceived(reqTaskOnHeadersReceived); Mini program login interface
Backend login interface code implementation The backend uses NodeJS, web framework KOA version ^2.13 .4, routing framework @koa/router version ^10.1.1, framework request, version ^2.88.2, jsonwebtoken is used to encrypt and decrypt token information, version ^8.5.1 // app.js const Koa = require("koa"); const Router = require("@koa/router"); const WeixinAuth = require("./lib/koa2-weixin-auth"); const jsonwebtoken = require("jsonwebtoken"); const app = new Koa(); // 小程序機票信息 const miniProgramAppId = "*********"; const miniProgramAppSecret = "***********"; const weixinAuth = new WeixinAuth(miniProgramAppId, miniProgramAppSecret); const JWT_SECRET = "JWTSECRET"; // 路由中間件需要安裝@koa/router // 開啟一個帶群組的路由 const router = new Router({ prefix: "/user", }); // 這是正規(guī)的登陸方法 // 添加一個參數(shù),sessionKeyIsValid,代表sessionKey是否還有效 router.post("/weixin-login", async (ctx) => { let { code, userInfo, encryptedData, iv, sessionKeyIsValid } = ctx.request.body; // 解析openid const token = await weixinAuth.getAccessToken(code); userInfo.openid = token.data.openid; // 這里可以自己進行處理,比方說記錄到數(shù)據(jù)庫,處理token等 let authorizationToken = jsonwebtoken.sign( { name: userInfo.nickName }, JWT_SECRET, { expiresIn: "1d" } ); Object.assign(userInfo, { authorizationToken }); ctx.status = 200; ctx.body = { code: 200, msg: "ok", data: userInfo, }; }); // lib/koa2-weixin-auth.js const querystring = require("querystring"); const request = require("request"); const AccessToken = function (data) { if (!(this instanceof AccessToken)) { return new AccessToken(data); } this.data = data; }; /*! * 檢查AccessToken是否有效,檢查規(guī)則為當前時間和過期時間進行對比 * * Examples: * ``` * token.isValid(); * ``` */ AccessToken.prototype.isValid = function () { return ( !!this.data.session_key && new Date().getTime() < this.data.create_at + this.data.expires_in * 1000 ); }; /** * 根據(jù)appid和appsecret創(chuàng)建OAuth接口的構造函數(shù) * 如需跨進程跨機器進行操作,access token需要進行全局維護 * 使用使用token的優(yōu)先級是: * * 1. 使用當前緩存的token對象 * 2. 調用開發(fā)傳入的獲取token的異步方法,獲得token之后使用(并緩存它)。 * Examples: * ``` * var OAuth = require('oauth'); * var api = new OAuth('appid', 'secret'); * ``` * @param {String} appid 在公眾平臺上申請得到的appid * @param {String} appsecret 在公眾平臺上申請得到的app secret */ const Auth = function (appid, appsecret) { this.appid = appid; this.appsecret = appsecret; this.store = {}; this.getToken = function (openid) { return this.store[openid]; }; this.saveToken = function (openid, token) { this.store[openid] = token; }; }; /** * 獲取授權頁面的URL地址 * @param {String} redirect 授權后要跳轉的地址 * @param {String} state 開發(fā)者可提供的數(shù)據(jù) * @param {String} scope 作用范圍,值為snsapi_userinfo和snsapi_base,前者用于彈出,后者用于跳轉 */ Auth.prototype.getAuthorizeURL = function (redirect_uri, scope, state) { return new Promise((resolve, reject) => { const url = "https://open.weixin.qq.com/connect/oauth2/authorize"; let info = { appid: this.appid, redirect_uri: redirect_uri, scope: scope || "snsapi_base", state: state || "", response_type: "code", }; resolve(url + "?" + querystring.stringify(info) + "#wechat_redirect"); }); }; /*! * 處理token,更新過期時間 */ Auth.prototype.processToken = function (data) { data.create_at = new Date().getTime(); // 存儲token this.saveToken(data.openid, data); return AccessToken(data); }; /** * 根據(jù)授權獲取到的code,換取access token和openid * 獲取openid之后,可以調用`wechat.API`來獲取更多信息 * @param {String} code 授權獲取到的code */ Auth.prototype.getAccessToken = function (code) { return new Promise((resolve, reject) => { const url = "https://api.weixin.qq.com/sns/jscode2session"; //由于此框架版本很久沒有更新了,此處地址發(fā)生了變化,需要修改為以上地址,不然會出現(xiàn) //41008錯誤。這也是沒有直接使用框架,引用本地使用的原因。 // const url = "https://api.weixin.qq.com/sns/oauth2/access_token"; const info = { appid: this.appid, secret: this.appsecret, js_code: code, grant_type: "authorization_code", }; request.post(url, { form: info }, (err, res, body) => { if (err) { reject(err); } else { const data = JSON.parse(body); resolve(this.processToken(data)); } }); }); }; /** * 根據(jù)refresh token,刷新access token,調用getAccessToken后才有效 * @param {String} refreshToken refreshToken */ Auth.prototype.refreshAccessToken = function (refreshToken) { return new Promise((resolve, reject) => { const url = "https://api.weixin.qq.com/sns/oauth2/refresh_token"; var info = { appid: this.appid, grant_type: "refresh_token", refresh_token: refreshToken, }; request.post(url, { form: info }, (err, res, body) => { if (err) { reject(err); } else { const data = JSON.parse(body); resolve(this.processToken(data)); } }); }); }; /** * 根據(jù)openid,獲取用戶信息。 * 當access token無效時,自動通過refresh token獲取新的access token。然后再獲取用戶信息 * @param {Object|String} options 傳入openid或者參見Options */ Auth.prototype.getUser = async function (openid) { const data = this.getToken(openid); console.log("getUser", data); if (!data) { var error = new Error( "No token for " + options.openid + ", please authorize first." ); error.name = "NoOAuthTokenError"; throw error; } const token = AccessToken(data); var accessToken; if (token.isValid()) { accessToken = token.data.session_key; } else { var newToken = await this.refreshAccessToken(token.data.refresh_token); accessToken = newToken.data.session_key; } console.log("accessToken", accessToken); return await this._getUser(openid, accessToken); }; Auth.prototype._getUser = function (openid, accessToken, lang) { return new Promise((resolve, reject) => { const url = "https://api.weixin.qq.com/sns/userinfo"; const info = { access_token: accessToken, openid: openid, lang: lang || "zh_CN", }; request.post(url, { form: info }, (err, res, body) => { if (err) { reject(err); } else { resolve(JSON.parse(body)); } }); }); }; /** * 根據(jù)code,獲取用戶信息。 * @param {String} code 授權獲取到的code */ Auth.prototype.getUserByCode = async function (code) { const token = await this.getAccessToken(code); return await this.getUser(token.data.openid); }; module.exports = Auth; Mini program terminal login code implementation <!--pages/index.wxml--> <view class="page-section"> <text class="page-section__title">微信登錄</text> <view class="btn-area"> <button bindtap="getUserProfile" type="primary">登錄</button> </view> </view> // pages/index.js Page({ /** * 頁面的初始數(shù)據(jù) */ data: {}, // 正確的登錄方式 getUserProfile() { // 推薦使用wx.getUserProfile獲取用戶信息,開發(fā)者每次通過該接口獲取用戶個人信息均需用戶確認 // 開發(fā)者妥善保管用戶快速填寫的頭像昵稱,避免重復彈窗 wx.getUserProfile({ desc: "用于完善會員資料", // 聲明獲取用戶個人信息后的用途,后續(xù)會展示在彈窗中,請謹慎填寫 success: (res) => { let { userInfo, encryptedData, iv } = res; const requestLoginApi = (code) => { // 發(fā)起網(wǎng)絡請求 wx.request({ url: "http://localhost:3000/user/weixin-login", method: "POST", header: { "content-type": "application/json", }, data: { code, userInfo, encryptedData, iv, }, success(res) { console.log("請求成功", res.data); let token = res.data.data.authorizationToken; wx.setStorageSync("token", token); onUserLogin(token); console.log("authorization", token); }, fail(err) { console.log("請求異常", err); }, }); }; const onUserLogin = (token) => { getApp().globalData.token = token; wx.showToast({ title: "登錄成功了", }); }; //必須進行session是否過期檢查,不然會出現(xiàn)第一次點擊登錄,服務器報Illegal Buffer //的錯誤,但是第二次點擊登錄正常。 wx.checkSession({ success: (res) => { // session_key 未過期,并且在本生命周期一直有效 console.log("在登陸中"); let token = wx.getStorageSync("token"); if (token) onUserLogin(token); }, fail: (res) => { // session_key已經(jīng)失效,需要重新執(zhí)行登錄流程 wx.login({ success(res0) { if (res0.code) { requestLoginApi(res0.code); } else { console.log("登錄失敗!" + res0.errMsg); } }, }); }, }); }, }); }, }); What optimizations can be done for the login code? For a software, at the code level, it is necessary to pursue the most basic aspects (far more than these, but let’s do these well first):
那么接下來就來優(yōu)化一下代碼吧: 模塊化 可以把登錄的代碼模塊化,代碼如下: // lib/login.js function loginWithCallback(cb) { // 推薦使用wx.getUserProfile獲取用戶信息,開發(fā)者每次通過該接口獲取用戶個人信息均需用戶確認 // 開發(fā)者妥善保管用戶快速填寫的頭像昵稱,避免重復彈窗 wx.getUserProfile({ desc: "用于完善會員資料", // 聲明獲取用戶個人信息后的用途,后續(xù)會展示在彈窗中,請謹慎填寫 success: (res) => { let { userInfo, encryptedData, iv } = res; const requestLoginApi = (code) => { // 發(fā)起網(wǎng)絡請求 wx.request({ url: "http://localhost:3000/user/weixin-login", method: "POST", header: { "content-type": "application/json", }, data: { code, userInfo, encryptedData, iv, }, success(res) { console.log("請求成功", res.data); let token = res.data.data.authorizationToken; wx.setStorageSync("token", token); onUserLogin(token); console.log("authorization", token); }, fail(err) { console.log("請求異常", err); }, }); }; const onUserLogin = (token) => { getApp().globalData.token = token; wx.showToast({ title: "登錄成功了", }); if (cb && typeof cb == "function") cb(token); }; wx.checkSession({ success: (res) => { // session_key 未過期,并且在本生命周期一直有效 console.log("在登陸中"); let token = wx.getStorageSync("token"); if (token) onUserLogin(token); }, fail: (res) => { // session_key已經(jīng)失效,需要重新執(zhí)行登錄流程 wx.login({ success(res0) { if (res0.code) { requestLoginApi(res0.code); } else { console.log("登錄失敗!" + res0.errMsg); } }, }); }, }); }, }); } export default loginWithCallback; Promise化 回調地獄問題,不利于代碼的閱讀,所以接下來我們基于Promise進行代碼優(yōu)化。有了 Promise 對象,就可以將異步操作以同步操作的流程表達出來,避免了層層嵌套的回調函數(shù)。此外,Promise 對象提供統(tǒng)一的接口,使得控制異步操作更加容易。 Promise的幾個方法簡介
The above is the detailed content of A brief analysis of how to implement the login function in mini programs. 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![]() Undress AI ToolUndress images for free ![]() Undresser.AI UndressAI-powered app for creating realistic nude photos ![]() AI Clothes RemoverOnline AI tool for removing clothes from photos. ![]() Clothoff.ioAI clothes remover ![]() Video Face SwapSwap faces in any video effortlessly with our completely free AI face swap tool! ![]() Hot Article
How to fix KB5060533 fails to install in Windows 10?
3 weeks ago
By DDD
Dune: Awakening - Where To Get Insulated Fabric
3 weeks ago
By Jack chen
Gmail Login: How to Sign Up, Sign In, or Sign Out of Gmail - MiniTool
1 months ago
By Jack chen
How to fix KB5060999 fails to install in Windows 11?
3 weeks ago
By DDD
Guild Guide In Tainted Grail: The Fall Of Avalon
4 weeks ago
By Jack chen
![]() Hot Tools![]() Notepad++7.3.1Easy-to-use and free code editor ![]() SublimeText3 Chinese versionChinese version, very easy to use ![]() Zend Studio 13.0.1Powerful PHP integrated development environment ![]() Dreamweaver CS6Visual web development tools ![]() SublimeText3 Mac versionGod-level code editing software (SublimeText3) ![]() Hot Topics![]() 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. ![]() 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 ![]() 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 ![]() 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.? ![]() |