微信小程序wx.getUserInfo受权获取用户信息(头像、昵称)

这个接口只能得到一些非敏感信息,例如用户昵称,用户头像,通过用户受权容许获取的状况下便可得到用户信息,至于openid这些,须要调取wx.login来获取。微信

index.wxml

<!-- 当已经受权的时候 -->
<view wx:if="{{result == 'ok'}}" class="result">
  <view class="headimg">
    <image src="{{avatarUrl}}"></image>
  </view>
  <view class="nickname">{{nickName}}</view>
</view>
<!-- 当未受权的时候 -->
<view wx:else class="result">
<view>未受权</view>
<button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">受权登陆</button>
</view>

index.js

Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function() {
    var that = this;
    // 查看是否受权
    wx.getSetting({
      success (res){
        if (res.authSetting['scope.userInfo']) {
          // 已经受权,能够直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res) {
              console.log(res.userInfo)
              that.setData({
                result:'ok',// 结果
                nickName:res.userInfo.nickName,// 微信昵称
                avatarUrl:res.userInfo.avatarUrl,// 微信头像
              })
            }
          })
        }else{
          // 未受权,结果返回null
          that.setData({
            result:'null',// 结果
          })
        }
      }
    })
  },
  // 请求API受权,得到用户头像和昵称
  bindGetUserInfo (e) {
    console.log(e.detail.userInfo.nickName)
    var that = this;
    that.setData({
      result:'ok',// 结果
      nickName:e.detail.userInfo.nickName,// 微信昵称
      avatarUrl:e.detail.userInfo.avatarUrl,// 微信头像
    })
  }
})

index.wxss

button{
  margin:30px auto 0;
}
.result{
  width:200px;
  margin:20px auto;
  text-align: center;
}
.result .headimg{
  width:200px;
  height: 200px;
  border-radius: 100px;
  margin-bottom: 20px;
}
.result .headimg image{
  width:200px;
  height: 200px;
  border-radius: 100px;
}

未受权页面
image.pngxss

已受权页面

image.png

动图演示

image

Author:TANKING
Web:http://www.likeyun.cn/
Date:2020-08-19
WeChat:face6009this

相关文章
相关标签/搜索