1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 微信小程序——获取用户信息

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

时间:2020-06-28 08:58:25

相关推荐

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

文章目录

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

用户信息

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

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

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

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

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

官方文档:https://developers./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./miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html

根据微信官方接口调整消息:https://developers./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){//点击回调,如果授权成功拿到用户数据,否则为undefinedconsole.log(e.detail.userInfo); //对象console.log(e.detail.rawData); //Json}})

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。