微信获取手机号(一键登录)
需要将 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";
}