微信小程序——获取用户信息

xiaoxiao2025-10-07  43

文章目录

用户信息使用open-data展示微信开放的数据使用wx.getUserInfo保存用户信息

用户信息

首先明确一下用户信息有哪些:

微信用户昵称、头像、性别、城市、省份、国家和语言等。

【注意】上述信息都是微信资料中填写的,并不是用户的实时定位城市等。

获取用户信息分为两种情况: 在小程序中显示上述信息(使用open-data)获得上述信息存入数据库(使用wx.getUserInfo)

使用open-data展示微信开放的数据

官方文档:https://developers.weixin.qq.com/miniprogram/dev/component/open-data.html

对应的信息会直接展示到页面上。

<open-data type="userAvatarUrl"></open-data> <open-data type="userNickName"></open-data> <open-data type="userGender" lang="zh_CN"></open-data> <open-data type="userCity" lang="zh_CN"></open-data> <open-data type="userCountry" lang="zh_CN"></open-data>

使用wx.getUserInfo保存用户信息

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

根据微信官方接口调整消息:https://developers.weixin.qq.com/community/develop/doc/0000a26e1aca6012e896a517556c01

使用wx.getUserInfo接口直接弹出授权框不再支持。接口调用的机制是:如果用户已经授权过了,可以直接拿到用户信息,否则直接进入fail回调。

所以【解决方案】如下: onload时查看权限,如果已经授权直接获取用户信息。在页面中放置button,将open-type指定为getUserInfo类型,让用户主动点击发起授权询问,从而获得用户信息。

lang默认为en,表示返回用户信息的语言,例如en模式下返回“China”,而zh_CN是“中国”。

<button open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="onGotUserInfo">获取用户信息</button> Page({ onLoad: function(e) { // 查看是否授权 wx.getSetting({ success:function(res){ if (res.authSetting['scope.userInfo']) { //已授权,可以获取用户信息 wx.getUserInfo({ success: function(res) { console.log(res.userInfo); //对象 console.log(res.rawData); //Json } }) } } }) }, onGotUserInfo(e){ //点击回调,如果授权成功拿到用户数据,否则为undefined console.log(e.detail.userInfo); //对象 console.log(e.detail.rawData); //Json } })

转载请注明原文地址: https://www.6miu.com/read-5037486.html

最新回复(0)