为优化用户体验,使用 wx.getUserInfo 接口直接弹出授权框的开发方式将逐步不再支持。
oh~my god!!!
开发者可使用以下方式获取或展示用户信息:
一、小程序:
1、使用 button 组件,并将 open-type 指定为 getUserInfo 类型,获取用户基本信息。
详情参考文档:
https://developers.weixin.qq.com/miniprogram/dev/component/button.html
2、使用 open-data 展示用户基本信息。
详情参考文档:
https://developers.weixin.qq.com/miniprogram/dev/component/open-data.html
二、小游戏:
1、使用用户信息按钮 UserInfoButton。
详情参考文档:
2、开放数据域下的展示用户信息。
详细参考文档:
https://developers.weixin.qq.com/minigame/dev/document/open-api/data/wx.getUserInfo.html
用button来获取用户基本信息的代码如下:
<view class="container">
<view class="userinfo">
<button wx:if="{{ !hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="onGetUserinfo"
>授权登录</button>
<block wx:else>
<image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
</view>
</view>
/**index.wxss**/
.userinfo {
display: flex;
flex-direction: column;
align-items: center;
}
.userinfo-avatar {
width: 128rpx;
height: 128rpx;
margin: 20rpx;
border-radius: 50%;
}
.userinfo-nickname {
color: #aaa;
}
.usermotto {
margin-top: 200px;
}
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
//事件处理函数
bindViewTap: function() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad: function () {
// 查看是否授权
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
} else if (this.data.canIUse){
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
} else {
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
}
},
onGetUserinfo: function(e) {
console.log(e.detail.userInfo)
if (e.detail.userInfo) {
//用户按了允许授权按钮
console.log("允许")
console.log(e.detail.errMsg)
console.log(e.detail.userInfo)
console.log(e.detail.rawData)
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
} else {
//用户按了拒绝按钮
console.log("拒绝")
}
}
})
![](https://i-blog.csdnimg.cn/blog_migrate/c20e45b2960a1a4d79b6b2bf6118e8d3.gif)