小程式登入的邏輯和平常app的登入邏輯不同,下面用一幅圖來說明:
app 登入邏輯:

微信小程式 登入邏輯:
從上圖中可以看出,小程式需要作一系列判斷才能走到,請求自己公司背景接口登入這步驟.
附下源碼,包括登入前 檢查本地 storage 中是否有登入态辨別:
//app.jsconst api = require('./config/config.js'); App({ // 小程式啟動生命周期 onLaunch: function () { let that = this; // 檢查登入狀态 that.checkLoginStatus(); }, // 檢查本地 storage 中是否有登入态辨別 checkLoginStatus: function () { let that = this; let loginFlag = wx.getStorageSync('loginFlag'); if (loginFlag) { // 檢查 session_key 是否過期 wx.checkSession({ // session_key 有效(為過期) success: function () { // 直接從Storage中擷取使用者資訊 let userStorageInfo = wx.getStorageSync('userInfo'); if (userStorageInfo) { that.globalData.userInfo = JSON.parse(userStorageInfo); } else { that.showInfo('緩存資訊缺失'); console.error('登入成功後将使用者資訊存在Storage的userStorageInfo字段中,該字段丢失'); } }, // session_key 過期 fail: function () { // session_key過期 that.doLogin(); } }); } else { // 無登入态 that.doLogin(); } }, // 登入動作 doLogin: function (callback = () => {}) { let that = this; wx.login({ success: function (loginRes) { if (loginRes.code) { wx.getUserInfo({ withCredentials: true, // 非必填, 預設為true success: function (infoRes) { console.log(infoRes,'>>>') // 請求服務端的登入接口 wx.request({ url: api.loginUrl, data: { code: loginRes.code, // 臨時登入憑證 rawData: infoRes.rawData, // 使用者非敏感資訊 signature: infoRes.signature, // 簽名 encryptedData: infoRes.encryptedData, // 使用者敏感資訊 iv: infoRes.iv // 解密算法的向量 }, success: function (res) { console.log('login success'); res = res.data; if (res.result == 0) { that.globalData.userInfo = res.userInfo; wx.setStorageSync('userInfo', JSON.stringify(res.userInfo)); wx.setStorageSync('loginFlag', res.skey); callback(); } else { that.showInfo(res.errmsg); } }, fail: function (error) { // 調用服務端登入接口失敗 that.showInfo('調用接口失敗'); console.log(error); } }); }, fail: function (error) { // 擷取 userInfo 失敗,去檢查是否未開啟權限 wx.hideLoading(); that.checkUserInfoPermission(); } }); } else { // 擷取 code 失敗 that.showInfo('登入失敗'); console.log('調用wx.login擷取code失敗'); } }, fail: function (error) { // 調用 wx.login 接口失敗 that.showInfo('接口調用失敗'); console.log(error); } }); }, // 檢查使用者資訊授權設定 checkUserInfoPermission: function (callback = () => { }) { wx.getSetting({ success: function (res) { if (!res.authSetting['scope.userInfo']) { wx.openSetting({ success: function (authSetting) { console.log(authSetting) } }); } }, fail: function (error) { console.log(error); } }); }, // 擷取使用者登入标示 供全局調用 getLoginFlag: function () { return wx.getStorageSync('loginFlag'); }, // 封裝 wx.showToast 方法 showInfo: function (info = 'error', icon = 'none') { wx.showToast({ title: info, icon: icon, duration: 1500, mask: true }); }, // app全局資料 globalData: { userInfo: null }});
版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協定,轉載請附上原文出處連結和本聲明。
本文連結:https://blog.csdn.net/TianciZhu/article/details/84836726