微信小程序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

相關文章
相關標籤/搜索