需求
如圖,點(diǎn)擊按鈕,獲取用戶(hù)手機(jī)號(hào)實(shí)現(xiàn)一鍵登錄,當(dāng)然,用戶(hù)也可以自行輸入其他手機(jī)號(hào)進(jìn)行登錄
問(wèn)題
要想獲取用戶(hù)手機(jī)號(hào)并不復(fù)雜,但由于近幾年微信小程序獲取手機(jī)號(hào)的api進(jìn)行了更新,當(dāng)前很多帖子使用的仍是舊的方式,先調(diào)wx.login()獲取code,iv,等等加密數(shù)據(jù), 給到后端換取手機(jī)號(hào), 現(xiàn)在這里說(shuō)明的是更新后的獲取手機(jī)號(hào)方式
ps : 現(xiàn)在獲取手機(jī)號(hào)首先需要小程序進(jìn)行認(rèn)證, 然后每次調(diào)用收費(fèi)0.03元
實(shí)現(xiàn)
簡(jiǎn)單說(shuō)明思路 :
1.wx.login() 獲取code,
2.步驟1拿到的code發(fā)送給服務(wù)端換取唯一用戶(hù)標(biāo)識(shí)openid
3.調(diào)getPhoneNumber() 獲取phoneCode
4. 步驟3獲取的phoneCode和步驟2拿到的openId一起傳給服務(wù)端獲取手機(jī)號(hào)
5. 完成登錄
1. 手機(jī)號(hào)快速驗(yàn)證組件↓
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
*這里小小注意一下, uniapp回調(diào)寫(xiě)法@getphonenumber, 微信小程序bindgetphonenumber
<button type="primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">手機(jī)號(hào)一鍵登錄</button>
2. 在bindgetphonenumber回調(diào)中獲取code動(dòng)態(tài)令牌文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-754706.html
getPhoneNumber(e) { // 在bindgetphonenumber回調(diào)中獲取code動(dòng)態(tài)令牌
loginFn().then(res => { // 微信登錄&服務(wù)端獲取openid
console.log(res, '接口換取的openid')
console.log('獲取手機(jī)號(hào)的動(dòng)態(tài)令牌:', e.detail.code) // 動(dòng)態(tài)令牌
getPhoneNumberFn(e.detail.code, res.openid).then(res2 => { // 服務(wù)端獲取手機(jī)號(hào)
if (res2.code == 0) {
uni.setStorageSync('phoneNumber', res.content.phone_info.phoneNumber)
uni.showToast({
title: '登錄成功'
})
}
})
})
},
3. login.js 函數(shù)封裝 : 微信登錄 / 服務(wù)端獲取openid / 服務(wù)斷獲取手機(jī)號(hào)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-754706.html
// 服務(wù)端接口 - 獲取openid
function queryOpenIdFn(code) {
return new Promise(resolve => {
queryOpenId({
code
}).then(res => {
if (res.code !== 0) {
console.log('獲取openid失敗1:', res.msg);
return
}
uni.setStorageSync('openId', res.content.openid)
resolve(res.content)
})
.catch(err => {
console.log('獲取openid失敗2:', err);
})
})
}
// 服務(wù)端接口 - 獲取手機(jī)號(hào)
function getPhoneNumberFn(phoneCode, openId) {
return new Promise(resolve => {
getPhoneNumber({
code:phoneCode,
openId
}).then(res => {
if (res.code !== 0) {
console.log('獲取手機(jī)號(hào)失敗1:', res.msg);
return
}
resolve(res)
})
.catch(err => {
console.log('獲取手機(jī)號(hào)失敗2:', err);
})
})
}
// 微信api : 微信登錄
function loginFn() {
return new Promise((resolve, reject) => {
uni.login({
success: async (res) => {
queryOpenIdFn(res.code).then(res => {
resolve(res)
})
},
fail: (err) => {
console.log('login fail:', err);
}
})
})
}
export {
loginFn,
getPhoneNumberFn
}
到了這里,關(guān)于【微信小程序】新版獲取手機(jī)號(hào)碼實(shí)現(xiàn)一鍵登錄(uniapp語(yǔ)法)(完整版附源碼)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!