随手记:小程序手机号一键登录
获取手机号码的前提:
非个人小程序
认证的小程序
非海外的企业认证
大致流程图
获取对应code
<u-button type="primary" shape="circle" open-type="getPhoneNumber" lang="zh_CN" @getphonenumber="getPhoneNumber">手机号快捷登录</u-button>
getPhoneNumber(e) {
if (!e.detail.hasOwnProperty("encryptedData")) { // 没有encryptedData代表用户拒绝授权
return
}
// 授权登录获取用户code
uni.login({
provider: 'weixin',
success: loginRes => {
console.log(loginRes);
this.miniProgramCode = loginRes.code;
console.log(e)
uni.showLoading({
mask: true,
title: '授权登录中'
})
// 调接口传递给后端参数获取手机号码-完成授权并做页面跳转
wxMiniProgramLogin({
jsCode: this.miniProgramCode,
code: e.detail.code,
hospitalId: getApp().globalData.hospitalId || ''
}).then(res => {
console.log(res)
uni.hideLoading();
uni.setStorageSync('_USER_OPENID', res.data.openid);
this.settingToken(res.data.token);
this.getUserInfo().then(response => {
let url = '';
this.initIm();
uni.showToast({ title: '登录成功', icon: 'none'});
url = '/pages/index/main'
setTimeout(() => { uni.switchTab({ url }) }, 500);
})
})
}
});
},