微信小程序获取用户信息(昵称、头像、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({
                //获取code
                success: function (res) {
                  var code = res.code; //返回code
                  console.log(code);
                  var appId = '';//微信小程序AppID
                  var secret = '';//可在微信公众平台设置扫描二维码获取
                  wx.request({
                    url: 'https://api.weixin.qq.com/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 //返回openid
                      console.log(openid)//控制台打印openid
                      app.globalData.userOpenId = openid;
                    }
                  })
                }
              })

其中
var appId = ‘’;//微信小程序AppID
var secret = ‘’;//可在微信公众平台设置扫描二维码获取

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

当然,如果你开通了云服务,直接调用云函数获取,会更加方便,并且不需要使用code。
详情:微信小程序云函数获取用户openid


版权声明:本文为ZHANGYANG_1109原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。