微信小程序登陆getUserProfile
wxml
wxml代码:
<view class='content'>
<text>申请获得你的公开信息(昵称,头像等)</text>
</view>
<button catchtap="handerUserInfo" class="userinfo">授权登录</button>
<button catchtap="handlerCancelClick" class="userinfo">取消登录</button>
css:
.content {
margin-left: 50rpx;
margin-bottom: 90rpx;
}
.content text {
display: block;
color: #9d9d9d;
margin-top: 40rpx;
}
.userinfo {
border-radius: 80rpx;
margin: 70rpx 50rpx;
font-size: 35rpx;
}
getUserProfile:
下面展示一些 `内联代码片`。//触发授权登陆
handerUserInfo(e) {
const token = wx.getStorageSync('token')
if (token) return Promise.resolve(true)
return new Promise((resolve,rej)=>{
wx.getUserProfile({
desc:'正在获取...',//不写不弹提示框
success:function(res){
wx.login({
success : function(re){
if (re.code){
wx.request({
url: NEW_LOGIN,//登陆接口,通过登陆接口将用户信息写入数据库
data: {
code: re.code,
nickName: res.userInfo.nickName,//昵称
avatarUrl: res.userInfo.avatarUrl, //头像
},
success:function(response){
if(response.data.data.code != 1 ){
wx.showToast({
title: '授权失败',
icon:'none',
duration:4000
})
}else{
wx.showToast({
title: '授权成功',
icon:'none',
duration:3000
})
let user = response.data.data;
Auth.setUser(user);
wx.navigateBack();
}
},
fail:function(){
wx.showToast({
title: '授权失败',
icon:'none',
duration:4000
})
}
})
}
}
})
},
fail:function(err){
wx.showToast({
title: '您已拒绝授权登陆',
icon:'none',
duration:3000
})
return;
}
})
})
},
//点击取消登陆
handlerCancelClick: function(e) {
},