小程序登录、用户信息相关接口调整说明解读与解决方案
愉快的5.1假期,从客户一条条短消息中度过,为什么小程序不能弹出授权了!!!程序排查接口没问题,前端说我又没更改,仔细一搜官方文档,原来早就发了公告了,怎奈不经常开发小程序,没关注啊!!!!
官方公告
内容重点解读
1、新增了一个接口wx.getUserProfile
getUserProfile
2、请使用了wx.getUserInfo
接口或<button open-type="getUserInfo"/>
的开发者尽快适配,不会弹出授权提示了,获取不到userinfo了
3、通过wx.login
接口获取的登录凭证可直接换取unionID,程序整合用户统一更方便了
4、若开发者调用wx.authorize
接口请求scope.userInfo
授权,用户侧不会触发授权弹框,直接返回授权成功
5、若开发者调用wx.getSetting
接口请求用户的授权状态,会直接读取到scope.userInfo为true
开发者需要解决的问题
1、适配wx.getUserInfo
和wx.getUserProfile
,低版本微信还要适配啊!!!
解决方案
详细请看:官方适配方案
<block wx:if="{{!hasUserInfo}}">
<button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button>
<button wx:else open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
</block>
<block wx:else>
<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"</image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
<script>
Page({
data: {
userInfo: {},
hasUserInfo: false,
canIUseGetUserProfile: false,
},
onLoad() {
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
}
},
getUserProfile(e) {
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
// 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
},
getUserInfo(e) {
// 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
},
})
</script>
2、scope.userInfo
检测调整,现在不论有没有授权,都是true,坑爹呢这是
解决方案
在授权后,写一个缓存到本地,点击授权前,先检测是否有缓存
//授权成功后,写入缓存
getUserProfile(e){
wx.getUserProfile({
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
wx.setStorageSync('storageUserInfo', 1);
}
})
},
//进入页面检测是否有缓存授权过
onLoad(e) {
if (wx.getStorageSync('storageUserInfo')) {
this.setData({
hasUserInfo: true
})
}
}