1.wx.getUserProfile()方法用于返回当前用户的昵称及头像数据,无输入参数,调用后会弹出是否授权提示信息,点允许后返回昵称和头像。
2.wx.login()方法返回code信息,无需输入参数。
3.wx.request发起请求,用code,appid,appsecret三个参数可以返回用户openid值(可作用户主键)。
4.{ success(res){} } 可等价于: { success :res =>{} }
5.小程序授权登录逻辑:
a.) xwml :
<!--index.wxml-->
<view class="container">我是标题</view>
<view>
<button wx:if="{{!hasLoggedIn}}" bindtap="handleLogin">登录</button>
<text wx:else>{{userInfo.nickName}}</text>
<!-- 授权弹窗 -->
<view wx:if="{{showAuthDialog}}" class="auth-dialog">
<view class="dialog-content">
<text>是否同意授权登录?</text>
<view class="button-container">
<button bindtap="handleAuthConfirm">确认</button>
<button bindtap="cancelAuth">取消</button>
</view>
</view>
</view>
</view>
b) js:
Page({
data: {
userInfo: null,
hasLoggedIn: false,
showAuthDialog: false, // 控制授权弹窗的显示与隐藏
},
onLoad: function () {
// 检查是否已登录过
const userInfo = wx.getStorageSync('userInfo');
if (userInfo) {
this.setData({
userInfo: userInfo,
hasLoggedIn: true,
});
}
},
handleLogin: function () {
// 显示授权弹窗
this.setData({
showAuthDialog: true,
});
},
handleAuthConfirm: function () {
// 用户点击确认授权,执行登录操作
wx.login({
success: function (res) {
if (res.code) {
// 调用授权登录接口,获取用户信息
wx.getUserInfo({
success: function (userInfoRes) {
// 授权登录成功,保存用户信息到本地并展示昵称
wx.setStorageSync('userInfo', userInfoRes.userInfo);
this.setData({
userInfo: userInfoRes.userInfo,
hasLoggedIn: true,
showAuthDialog: false, // 隐藏授权弹窗
});
}.bind(this),
fail: function () {
// 拒绝授权,隐藏授权弹窗并提示用户重新授权登录
this.setData({
showAuthDialog: false, // 隐藏授权弹窗
});
wx.showToast({
title: '拒绝授权',
icon: 'none',
});
}.bind(this)
});
} else {
// 调用登录接口失败,隐藏授权弹窗并处理失败情况
this.setData({
showAuthDialog: false, // 隐藏授权弹窗
});
wx.showToast({
title: '登录失败',
icon: 'none',
});
}
}.bind(this),
fail: function () {
// 调用登录接口失败,隐藏授权弹窗并处理失败情况
this.setData({
showAuthDialog: false, // 隐藏授权弹窗
});
wx.showToast({
title: '登录失败',
icon: 'none',
});
},
});
},
});
c) wxss:
.auth-dialog {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 999;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.5);
}
.dialog-content {
background-color: #fff;
padding: 20px;
border-radius: 10px;
width: 80%;
}
.button-container {
margin-top: 20px;
display: flex;
justify-content: space-between;
}
.button-container button {
width: 45%;
height: 40px;
background-color: #4CAF50;
color: #fff;
border: none;
border-radius: 5px;
font-size: 16px;
}