小程序的登錄是必不可少的,那我們?nèi)绾稳?shí)現(xiàn)這個(gè)功能呢
1.首先我們是需要去調(diào)用uni.getUserProfile()去獲取用戶信息的,得到一些登錄接口相關(guān)的一些數(shù)據(jù)
2.再去調(diào)用uni.login()這個(gè)api去獲取code字段
3.結(jié)合以上這兩個(gè)api獲取的一些數(shù)據(jù)組合成接口所需要的參數(shù),然后通過調(diào)用后端的接口去得到用戶的token
具體實(shí)現(xiàn)如下文章來源:http://www.zghlxwxcb.cn/news/detail-613189.html
// 獲取微信用戶的基本信息
async getUserProfile () {
// desc 為必填字段,用于聲明獲取用戶個(gè)人信息后的用途,不超過 30 個(gè)字符
const [err, res] = await uni.getUserProfile({desc: '完善用戶信息'})
// 用戶拒絕授權(quán)
if (err) return uni.$showMsg('您拒絕授權(quán)!')
// 用戶同意授權(quán),保存用戶信息到 vuex 中
console.log(res)
this.saveUserInfo(res.userInfo)
// 獲取登錄成功后的 Token 字符串
this.getToken(res)
}
獲取token的方法文章來源地址http://www.zghlxwxcb.cn/news/detail-613189.html
// 調(diào)用登錄接口,換取永久的 token
async getToken(info) {
// 調(diào)用微信登錄接口
const [err, res] = await uni.login()
// 判斷微信登錄 uni.login() 是否調(diào)用失敗
if (err) return uni.$showMsg('微信登錄失??!')
// 準(zhǔn)備參數(shù)對象
const data = {
code: res.code, // 微信登錄返回的 code
encryptedData: info.encryptedData, // 包括敏感數(shù)據(jù)在內(nèi)的完整用戶信息的加密數(shù)據(jù)
iv: info.iv, // 加密算法的初始向量
rawData: info.rawData, // 不包括敏感信息的原始數(shù)據(jù)字符串
signature: info.signature // 用于校驗(yàn)用戶信息
}
// wxfb52f2d7b2f6123a
// 由于不是小程序開發(fā)者,可以寫死一個(gè)假值進(jìn)行下面流程的測試
const { data: loginResult } = await uni.$http.post('/users/wxlogin', data)
// 登錄是否成功判斷
if (loginResult.meta.status !== 200) return uni.$showMsg('黑馬優(yōu)購登錄失敗!')
uni.$showMsg('登錄成功!')
}
到了這里,關(guān)于uniapp開發(fā)微信小程序的登錄功能實(shí)現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!