一、效果贴图


二、实现方式:
1、一建获取用户信息
-
以前可以通过
<button open-type="getUserInfo" >一键登录</button>
来实现一建获取用户信息; -
2021年4月28日24时后发布的小程序新版本,无法通过wx.getUserInfo与获取用户个人信息(头像、昵称、性别与地区)
-
新增getUserProfile接口(基础库2.10.4版本开始支持),可获取用户头像、昵称、性别及地区信息,开发者每次通过该接口获取用户个人信息均需用户确认
所以我们要通过getUserProfile接口来实现一建获取用户信息功能;
具体代码如下
login.wxml文件
<button class='bottom' type='primary' bindtap="getUserProfile" lang="zh_CN">微信一键登录</button>
login.js文件
getUserProfile(e) {
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
// 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
let that = this
wx.getUserProfile({
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
if(res.errMsg === "getUserProfile:ok"){
that.setData({
userInfo: res.userInfo,
logined: true
})
that.userInfo = res.userInfo;
}else{
}
},
complete: (res) => {
if(res.errMsg === "getUserProfile:fail auth deny"){
}
},
})
},
2、一建获取用户手机号
login.wxml文件
<button class='bottom' type='primary' open-type="getPhoneNumber" lang="zh_CN" bindgetphonenumber="bindGetUserInfo">微信手机号一键登录</button>
login.js文件
bindGetUserInfo: function (e) {
if (e.detail.errMsg === "getPhoneNumber:ok") {
//用户按了允许授权按钮
var that = this;
wx.login({
success(loginRes) {
if (loginRes.code) {
let code = loginRes.code;
// 登录 - start
let data = {
code: code,
iv: e.detail.iv,
image: that.userInfo.avatarUrl,
encrypteData: e.detail.encryptedData,
}
// loading start
wx.showLoading({
title: '登录中...',
})
// 调用你的登录接口将用户收据发送给服务器
login(data).then(res => {
wx.hideLoading()
if(res.data.code === 0){
let dataString = JSON.stringify(res.data.data)
wx.setStorage({key: 'token', data: res.data.data.token})
wx.setStorage({key: 'userInfo', data: dataString})
wx.showToast({
title: '登录成功',
icon: 'success',
duration: 2500
})
let timer = setTimeout(() => {
clearTimeout(timer);
timer = null
app.onLaunch()
wx.reLaunch({
url: '/pages/home/index',
})
}, 2000);
}
}, err => {
// wx.hideLoading()
// wx.showToast({
// title: res.data.message,
// icon: 'none',
// duration: 2500
// })
});
// 登录 - end
}
}
})
} else {
// wx.switchTab({
// url: '/pages/home/index'
// })
}
},
这里面需要注意:文章来源:https://www.toymoban.com/news/detail-488472.html
- 1、用
e.detail.errMsg === "getPhoneNumber:ok"
来判断用户是确认还是拒绝获取手机号的申请,去做相应处理 - 2、我们获取到的用户手机号码是加密的数据。我们把
iv: e.detail.iv,
encrypteData: e.detail.encryptedData,
发送给后台,由后台来解析。文章来源地址https://www.toymoban.com/news/detail-488472.html
到了这里,关于小程序获取手机号和用户信息一键登录的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!