获取用户信息会用到的接口有:
1.wx.getSetting() 获取用户授权信息
2.wx.getUserInfo() 获取用户信息
3.wx.authorize() 弹出授权窗口 如果用户已经授权将不会弹出,次方法虽然有success回调方法,貌似是异步的,所以基本不会用到
我最开始是准备这么去实现,如果用户没有授权,用户需要登录的时候弹出授权窗口,授权后就登录,没有授权就还是未登录状态,但是发现无法在用户触发授权或者拒绝后处理相应的逻辑,最后想到以下两种方式。
<view class="container">
<view class='avatar'><image src="{{userIcon}}"></image></view>
<view class="user-name">{{userName}}</view>
<button bindtap="openSetting" class='btn'>设置</button>
</view>
为了能够方便的测试用户授权和没有授权的情况,我加了一个设置按钮方便打开设置页面。
const app = getApp()
Page({
data:{
userIcon:"../../images/default_icon.gif",
userName:"未登录"
}, onShow:function(){
let that = this;
wx.getSetting({
success(res) {
if (!res.authSetting['scope.userInfo']) {
console.info("用户未授权");
wx.openSetting();
} else {
console.info("用户已经授权");
that.setUserInfo();
}
}
})
},setUserInfo:function(){
let that = this;
wx.getUserInfo({
success: function (userRes) {
that.setData({
userIcon: userRes.userInfo.avatarUrl,
userName: userRes.userInfo.nickName,
haveLogin:true
})
}
});
},//打开权限设置
openSetting: function () {
let that = this;
wx.openSetting()
}
})
注意,检测用户是否授权了获取用户信息要放在onShow方法中,不能放到onLoad中,从生命周期一章中知道,只要界面展示就会调用onShow,onLoad只会调用一次,所以必须用onShow
.avatar{
text-align: center;
}
.avatar image{
margin: 0px auto;
width: 100px;
height: 100px;
border-radius: 50px;
}
.user-name{
text-align: center;
margin-top: 10px;
}
.btn{
margin: 50px 20px 0px 20px;
background:red;
color: #fff;
}
我们来看下效果:
<view class="container">
<view class='avatar'><image src="{{userIcon}}"></image></view>
<view class="user-name">{{userName}}</view>
<block wx:if="{{!haveLogin}}">
<button bindtap="openSetting" class='btn'>点我登录</button>
</block>
<button bindtap="openSetting" class='btn'>设置</button>
</view>
js:
const app = getApp()
Page({
data:{
userIcon:"../../images/default_icon.gif",
userName:"未登录",
haveLogin:true,
}, onShow:function(){
let that = this;
wx.getSetting({
success(res) {
if (!res.authSetting['scope.userInfo']) {
console.info("用户未授权");
that.setData({
haveLogin:false
})
} else {
console.info("用户已经授权");
that.setUserInfo();
}
}
})
},setUserInfo:function(){
let that = this;
wx.getUserInfo({
success: function (userRes) {
that.setData({
userIcon: userRes.userInfo.avatarUrl,
userName: userRes.userInfo.nickName,
haveLogin:true
})
}
});
},//打开权限设置
openSetting: function () {
let that = this;
wx.openSetting()
}
})