700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 微信小程序获取用户信息(昵称 头像 openid等)

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

时间:2022-07-13 08:19:02

相关推荐

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

1、可以调用wx.getUserProfile来获取用户的昵称、头像(地址)、地区及性别。但是需要通过按钮事件触发,在showModal弹窗中用户点击确定后才能获取。

WXML:

<view><button class="login_btn" bindtap="login" type="primary">授权登录</button></view>

WXJS:

login: function(){var that = this;wx.showModal({//用户授权弹窗title: '温馨提示',content: '提示',success(res) {console.log(res)//如果用户点击了确定按钮if (res.confirm) {wx.getUserProfile({desc: '获取你的昵称、头像、地区及性别',success: res => {console.log(res.userInfo)//控制台输出结果console.log("获取成功");},fail: res => {console.log(res)//拒绝授权wx.showToast({title: '登录失败',icon: 'error',duration: 2000});return;}});} else if (res.cancel) {//如果用户点击了取消按钮console.log(3);wx.showToast({title: '登录失败',icon: 'error',duration: 2000});return;}}})}

2、值得注意的是,通过wx.getUserProfile并不能获取用户的openid,openid是唯一识别用户的标识,所以最好在用户授权登录时就获取。调用wx.login(),可以将次wx.login()放在wx.getUserProfile成功后的回调函数中。

js代码:

wx.login({//获取codesuccess: function (res) {var code = res.code; //返回codeconsole.log(code);var appId = '';//微信小程序AppIDvar secret = '';//可在微信公众平台设置扫描二维码获取wx.request({url: 'https://api./sns/jscode2session?appid='+appId+'&secret='+secret+'&js_code='+code+'&grant_type=authorization_code',data: {},header: {'content-type': 'json'}, success: function (res) {var openid = res.data.openid //返回openidconsole.log(openid)//控制台打印openidapp.globalData.userOpenId = openid;}})}})

其中

var appId = ‘’;//微信小程序AppID

var secret = ‘’;//可在微信公众平台设置扫描二维码获取

这两项需要填写你自己的appid 和 secret。获取openid后可以赋值给全局变量,这样所有页面在需要使用时都可以通过全局变量调用了。

当然,如果你开通了云服务,直接调用云函数获取,会更加方便,并且不需要使用code。

详情:微信小程序云函数获取用户openid

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