微信小程序授权登录(有弹窗提示)
1 效果显示
1.1 授权登录页面
1.2 授权登录提示弹窗
1.3 拒绝授权登录
1.4 允许登录后,跳转到小程序首页
2 代码
2.1 wxml 文件
<view class='header'>
<image src="{{userInfo.avatarUrl}}"></image><!-- 用户头像 -->
</view>
<view>
<button class="bottom" bindtap="getUI"type='primary'>授权登录</button><!-- 授权登录按钮 -->
</view>
<!-- type='primary' 默认按钮为蓝色 --><!-- 授权登录 为按钮内容 -->
2.2 wxss 文件
.header {
margin: 90rpx 0 90rpx 50rpx;
border-bottom: 1px solid rgb(11, 165, 88);
text-align: center;
width: 650rpx;
height: 300rpx;
line-height: 450rpx;
margin-top: 120px;
}
.header image {
width: 185rpx;
height: 185rpx;
border-radius: 50%;
margin-right: 20rpx;
background-color: #f8f8f8;
}
.bottom {
border-radius: 80rpx;
margin: 70rpx 50rpx;
font-size: 35rpx;
}
2.3 js 文件
Page({
data: {
avatarUrl: './user-unlogin.png',
userInfo: {},
hasUserInfo: false,
logged: false,
takeSession: false,
requestResult: '',
canIUseGetUserProfile: false,
canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl')
},
onLoad: function () {},
getUI(e) {
var t = this
console.log('获取头像昵称', e)
wx.getUserProfile({
lang: 'zh_CN',
desc: '用于在后台更好的识别您的身份',
success(res) {
console.log('获取', res)
wx.setStorageSync('userInfo', res.userInfo);
t.setData({
userInfo: res.userInfo,
avatarUrl: res.userInfo.avatarUrl
}),
wx.switchTab({
url: "/pages/index/index",
});
wx.showToast({
image: "/static/image/success.png",
icon: "success",
title: '欢迎使用本小程序',
duration: 1000,
});
},
fail(err) {
console.error(err)
console.error("123")
wx.showToast({
image: "/static/image/error.png",
title: '用户拒绝授权',
icon: "error",
duration: 1000
});
}
})
},
onShow() {
this.setData({
userInfo: wx.getStorageSync('userInfo')
})
},
getUserProfile() {
wx.getUserProfile({
desc: '展示用户信息',
success: (res) => {
this.setData({
avatarUrl: res.userInfo.avatarUrl,
userInfo: res.userInfo,
hasUserInfo: true,
})
}
})
},
onGetUserInfo: function (e) {
if (!this.data.logged && e.detail.userInfo) {
this.setData({
logged: true,
avatarUrl: e.detail.userInfo.avatarUrl,
userInfo: e.detail.userInfo,
hasUserInfo: true,
})
}
},
})
不足之处还望指教!