微信小程序:获取用户信息(昵称和头像)

微信小程序获取用户信息的接口几经变更,建议直接使用方式四: wx.getUserProfile获取

方式一:open-data展示用户信息不推荐

组件功能调整为优化用户体验,平台将于2022年2月21日24时起回收通过展示个人信息的能力。
如有使用该技术服务,请开发者及时对小程序进行调整,避免影响服务流程。查看详情:
https://developers.weixin.qq.com/community/develop/doc/000e881c7046a8fa1f4d464105b001

<!-- 如果只是展示用户头像昵称,可以使用 <open-data /> 组件 -->

<open-data type="userAvatarUrl"></open-data>
<open-data type="userNickName"></open-data>

方式二: wx.getUserInfo 不推荐

小程序登录、用户信息相关接口调整说明:
https://developers.weixin.qq.com/community/develop/doc/000cacfa20ce88df04cb468bc52801

Page({
    
    
  onLoad: function (options) {
    
    
    this.getUserInfo();
  },
  async getUserInfo() {
    
    
    // 可以直接调用,无需用户授权
    const res = await wx.getUserInfo();
    console.log(res);
  },
});

获取的数据

{
    
    
	userInfo{
    
    
		avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
		city: ""
		country: ""
		gender: 0
		language: ""
		nickName: "微信用户"
		province: ""
	}
}

调用后发现,获取的数据已经不是真实的用户数据了

方式三:open-type=“getUserInfo” 不推荐

调用后发现,获取的数据已经不是真实的用户数据了

bug:开发者工具中 2.10.4~2.16.1 基础库版本通过 会返回真实数据,真机上此区间会按照公告返回匿名数据。
查看公告:
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html#Bug-Tip

wxml

<button open-type="getUserInfo"
        bind:getuserinfo="handleGetUserinfo">获取用户信息</button>

js

Page({
    
    
  handleGetUserinfo(e) {
    
    
    console.log(e);
  },
});

输出

{
    
    
	detail{
    
    
		userInfo:{
    
    
			avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
			city: ""
			country: ""
			gender: 0
			language: ""
			nickName: "微信用户"
			province: ""
			}
	}
}

方式四:wx.getUserProfile 推荐

获取用户信息。页面产生点击事件(例如 button 上 bindtap 的回调中)后才可调用,每次请求都会弹出授权窗口,用户同意后返回 userInfo。该接口用于替换 wx.getUserInfo

文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html

用户数据结构 UserInfo : https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/UserInfo.html

<button bindtap="getUserProfile">获取头像昵称</button>
Page({
    
    
  async getUserProfile(e) {
    
    
    const res = await wx.getUserProfile({
    
    
      desc: '用于完善会员资料',
    });
    console.log(res);
  },
});

输出

{
    
    
	detail{
    
    
		userInfo:{
    
    
			avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
			city: ""
			country: ""
			gender: 0
			language: ""
			nickName: "真实昵称"
			province: ""
			}
	}
}

猜你喜欢

转载自blog.csdn.net/mouday/article/details/123153296
今日推荐