微信文档其实已经写的很清晰,但是还是贴了一下代码
<view>
<view class="phone-tips">如您已在账号中维护手机号可直接授权登录</view>
<view class="form-item button-wrapper">
<button open-type="getPhoneNumber" bindgetphonenumber="bindAuthorizeClick" >授权手机号登录</button>
</view>
</view>
//手机号授权登录
bindAuthorizeClick (e) {
const data = e.detail;
if (data.code) { //拿到code
this.fetchPhoneNumber(data.code);
}
}
/**
* 通过code请求手机号并登录
* @param { String } code
* @param { String } domain 域名
*/
fetchPhoneNumber: function (code) {
let domain = this.data.systemConfig.domain;
const params = {
code,
domain,
}
wx.showLoading({
title: '正在加载中',
mask: true
});
fetch(service.phoneNumber, params, 'POST', {},false).then(res => {
wx.hideLoading();
if (res.code==200 ) {
this.processAfterLogin(res.data); //登录成功后的逻辑
} else {
wx.showToast({
title: res.message,
icon: 'none'
});
}
}).catch(err => {
wx.hideLoading();
wx.showToast({
title: err.message,
icon: 'none'
});
console.error('get phone number error: ', err.message);
});
},