微信獲取手機號(一鍵登錄)
需要將 button 組件 open-type
的值設置為 getPhoneNumber
,當用戶點擊並同意之后,可以通過 bindgetphonenumber
事件回調獲取到動態令牌code
,然后把code
傳到開發者后台,並在開發者后台調用微信后台提供的 phonenumber.getPhoneNumber 接口,消費code
來換取用戶手機號。每個code
有效期為5分鍾,且只能消費一次。
注:getPhoneNumber
返回的 code
與 wx.login
返回的 code
作用是不一樣的,不能混用。
code:動態令牌。可通過動態令牌換取用戶手機號。
步驟整理:
1、需要將 button 組件 open-type
的值設置為 getPhoneNumber
,當用戶點擊並同意之后,可以通過 bindgetphonenumber
事件回調獲取到動態令牌code
2、 bindgetphonenumber
事件回調中獲取 e.detail.encryptedData、e.detail.iv,傳給后端進行解密出手機號,
3、調佣登錄接口
調用登錄接口的步驟:
1、判斷用戶是否授權當前手機號,如果沒有手機號提示用戶授權,然后校驗手機號是否合法,
2、然后調用登錄接口,獲取用戶信息,並把用戶信息存儲到緩存和全局變量中。
// 授權獲取手機號
getPhoneNumber(e) {
if (this.data.phoneLoading) {
return;
}
if (!e.detail.encryptedData && !e.detail.iv) {
wx.showToast({
title: "拒絕授權獲取手機號,將無法登錄",
icon: "none",
});
} else {
api
.decodePhone({
openId: this.data.openId,
encryptedData: e.detail.encryptedData,
iv: e.detail.iv,
})
.then((res) => {
this.setData({
customerTel: res.responseData.customerTel || "",
phoneLoading: true,
});
this.handleBindOrLogin();
})
.catch((error) => {
this.setData({
phoneLoading: false,
});
});
}
},
async handleBindOrLogin() {
let _this = this;
let telPattern = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
if (!this.data.customerTel) {
wx.showToast({
title: "請授權獲取手機號",
icon: "none",
});
} else if (
this.data.customerTel &&
!telPattern.test(this.data.customerTel)
) {
wx.showToast({
title: "請輸入正確的手機號",
icon: "none",
});
} else {
api
.login({
openId: this.data.openId,
customerTel: this.data.customerTel,
unionId: this.data.unionId,
})
.then((res) => {
// 登錄信息存儲再storage,殺掉小程序進程再打開后保留小程序登錄信息
app.globalData.userInfo = res.responseData;
app.storage.setData(
app.storage.keys.userInfo,
Object.assign({}, res.responseData, {
openId: this.data.openId,
})
); //后端返回的登錄信息沒有openId,加入緩存
if (!app.globalData.isNewCustomer) {
//標識新用戶,'10'新用戶,'20'老用戶
app.globalData.isNewCustomer = res.responseData.newUser
? "10"
: "20";
}