一、登錄流程
在談論登錄流程之前,我們需要先了解Wexin小程序的登錄機制。微信小程序登錄分為兩種:一種是微信登錄,一種是手機號登錄。
微信登錄:用戶使用微信賬號進行授權,獲取用戶信息,再訪問開發者自己的服務器登錄。相對於手機號登錄,微信登錄具有更好的用戶體驗,減少用戶的操作步驟。
手機號登錄:用戶需要輸入手機號和短信驗證碼,完成登錄。對於不想使用微信授權登錄的用戶,可以選擇手機號登錄。開發者需要在服務器中存儲用戶的登錄狀態,給予用戶持久化的方式。
在Uniapp中,通過微信小程序官方提供的API,可以方便地實現微信登錄和手機號登錄功能。
二、微信登錄
微信登錄是Uniapp在小程序端比較推薦的一種登錄方式。Uniapp通過封裝微信官方提供的Session API,實現了微信登錄的功能。下面是實現微信登錄的步驟:
1、在小程序manifest.json文件中,註冊小程序的appid,並設置request合法域名和sld(頂級域名)
"appid": "yourAppid", // 註冊小程序的appid "networkTimeout": { "request": 10000, // 單位為ms "connectSocket": 10000, // 單位為ms "uploadFile": 10000, // 單位為ms "downloadFile": 10000 // 單位為ms }, "permission": { "scope.userLocation": { "desc": "你的位置信息將用於小程序的定位功能,不會泄露給其他人" } }, "mp-weixin": { "subPackages": [] }, "debug": true, "request": { "domain": { "main": "www.yourdomain.com", // 服務器域名 "images": [ "https://www.yourdomain.com/images", "https://img.yourdomain.com" ] }, "header": { "Content-Type": "application/json" } }, "requiredBackgroundModes": ["audio", "location"]
2、在uni賬戶中添加微信應用,獲取Appid與AppSecret,在Uniapp中使用這兩個信息進行微信登錄
// 在login.vue頁面中引入uni-account-login組件,在template中添加uni-account-login組件 // 在login.vue的標籤中添加下面的代碼 import uniAccountLogin from '@/components/uni-account-login/uni-account-login.vue' export default { components: { uniAccountLogin }, data() { return { loginType: 'wx', // 微信登錄 companyId: 'yourCompanyId', // 註冊的企業ID或個人ID } }, // 小程序通過微信授權登錄後,可以獲取到用戶的openid和session_key, // 維護着用戶的登錄狀態,然後把登錄結果返回給開發者的服務器。 onLoad() { uni.login({ provider: 'weixin', success: function (loginResult) { const wxcode = loginResult.code // 登錄憑證 uni.request({ url: 'https://api.weixin.qq.com/sns/jscode2session', method: 'GET', data: { appid: 'yourAppid', // 註冊的小程序appid secret: 'yourSecret', // 註冊的小程序AppSecret js_code: wxcode, grant_type: 'authorization_code' }, success: (res) => { const openid = res.data.openid // 用戶唯一標識 const sessionKey = res.data.session_key // 會話密鑰 const result = { type: 'wx', openId: openid, session_key: sessionKey, companyId: 'yourCompanyId', // 註冊的企業ID或個人ID } this.$refs.uniAccountLogin.login(result) } }) } }) } }
三、手機號登錄
手機號登錄需要在Uniapp中調用小程序官方的API。下面是實現手機號登錄的步驟:
1、在小程序manifest.json文件中,註冊小程序的手機號登錄模板
"mp-weixin": { "phone": { "templateMessageInfo": { "parameterList": [ { "name": "佔位符唯一標識", "value": "{{佔位符}}", // 替換為實際參數 "color": "#173177" // 參數字體顏色 } ], "templateId": "下發的模板消息唯一標識", // 模板id "type": "微信服務通知" // 模板類型 } } }
2、在uni賬戶中添加手機號登錄模板,獲取模板id,在Uniapp中使用模板id進行手機號登錄
// 在login.vue頁面中引入uni-account-login組件,在template中添加uni-account-login組件 // 在login.vue的標籤中添加下面的代碼 import uniAccountLogin from '@/components/uni-account-login/uni-account-login.vue' export default { components: { uniAccountLogin }, data() { return { loginType: 'phone', // 手機號登錄 companyId: 'yourCompanyId', // 註冊的企業ID或個人ID templateId: 'yourTemplateId' // 註冊的手機號登錄模板id } }, onLoad() { // 調用微信登錄,獲取用戶信息 uni.login({ provider: 'weixin', success: function (loginResult) { const wxcode = loginResult.code // 登錄憑證 uni.request({ url: 'https://api.weixin.qq.com/sns/jscode2session', method: 'GET', data: { ... }, success: (res) => { const openid = res.data.openid // 用戶唯一標識 const sessionKey = res.data.session_key // 會話密鑰 uni.getUserInfo({ provider: 'weixin', success: (infoResult) => { const userInfo = JSON.parse(infoResult.userInfo) const result = { type: 'phone', phone: '', templateId: this.templateId, companyId: this.companyId, openid: openid, session_key: sessionKey } // 調用uni-account-login組件,進行驗證碼驗證 this.$refs.uniAccountLogin.sendCode(result, (phoneNumber) => { result.phone = phoneNumber this.$refs.uniAccountLogin.login(result) }) } }) } }) } }) } }
四、登錄狀態
在Uniapp中,可以通過SessionStorage、本地存儲、服務端存儲等方式來維護用戶的登錄狀態。通常情況下,為了保障用戶信息的安全性,我們會選擇服務端存儲用戶登錄狀態。
服務端存儲用戶登錄狀態需要以下步驟:
1、在服務端生成一個唯一的token,然後把token和用戶信息關聯。可以通過redis或memcached等緩存庫來實現。同時在返回的api中,把token返回給用戶。
2、在前端通過SessionStorage或本地存儲來存儲token信息。在用戶請求的時候,把token添加在http header中,然後上傳到服務端驗證是否登錄。
3、在服務端驗證token,驗證通過後返回用戶信息。
// 在login.vue的標籤中,添加下面的代碼。 verifiedLogin(res) { // 服務端返回的驗證登錄結果 if (res.code == 200) { // 登錄成功 const data = res.data uni.setStorageSync('token', data.token) // 存儲用戶token uni.setStorageSync('userInfo', data.userInfo) // 存儲用戶信息 uni.switchTab({ url: '/pages/index/index' }) } else { uni.showToast({ title: '登錄失敗', icon: 'none' }) } }, login() { // 從uni-account-login組件中獲取登錄信息,提交到服務器進行登錄信息驗證 const result = this.$refs.uniAccountLogin.getLoginResult() console.log(JSON.stringify(result)) uni.request({ url: 'https://api.yourdomain.com/login', method: 'POST', data: { code: result.code, openid: result.openId ? result.openId : '', session_key: result.session_key ? result.session_key : '', phone: result.phone ? result.phone : '', verify_code: result.verifyCode ? result.verifyCode : '' }, success: (res) => { this.verifiedLogin(res.data) }, fail: () => {}, complete: () => {} }) }
五、總結
Uniapp是一個跨平台的開發框架,開發者可以通過一套代碼,覆蓋App、小程序、H5等多種平台。微信小程序是Uniapp中非常重要的一個平台,同時小程序登錄也是非常具有代表性的功能之一。本文從微信小程序登錄流程、微信登錄、手機號登錄和登錄狀態四個方面,對Uniapp微信小程序登錄進行了詳細的闡述。閱讀本文後,讀者可以掌握Uniapp微信小程序登錄的實現方式,為開發小程序提供指引。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/246275.html