微信小程序wx.getUserInfo授權獲取用戶信息(頭像、昵稱) - 新聞資訊 - 雲南小程序開發|雲南軟件開發|雲南網站建設-昆明融晨信息技術有限公司

159-8711-8523

雲南網建設/小程序開發/軟件開發

知識

不(bù)管是(shì)網站,軟件還是(shì)小程序,都要(yào / yāo)直接或間接能爲(wéi / wèi)您産生價值,我們在(zài)追求其視覺表現的(de)同時(shí),更側重于(yú)功能的(de)便捷,營銷的(de)便利,運營的(de)高效,讓網站成爲(wéi / wèi)營銷工具,讓軟件能切實提升企業内部管理水平和(hé / huò)效率。優秀的(de)程序爲(wéi / wèi)後期升級提供便捷的(de)支持!

您當前位置>首頁 » 新聞資訊 » 小程序相關 >

微信小程序wx.getUserInfo授權獲取用戶信息(頭像、昵稱)

發表時(shí)間:2021-1-11

發布人(rén):融晨科技

浏覽次數:117

這(zhè)個(gè)接口隻能獲得一些非敏感信息,例如用戶昵稱,用戶頭像,經過用戶授權允許獲取的(de)情況下即可獲得用戶信息,至于(yú)openid這(zhè)些,需要(yào / yāo)調取wx.login來(lái)獲取。

index.wxml

<!-- 當已經授權的(de)時(shí)候 -->
<view wx:if="{{result == 'ok'}}" class="result">
  <view class="headimg">
    <image src="{{avatarUrl}}"></image>
  </view>
  <view class="nickname">{{nickName}}</view>
</view>
<!-- 當未授權的(de)時(shí)候 -->
<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;
    // 查看是(shì)否授權
    wx.getSetting({
      success (res){
        if (res.authSetting['scope.userInfo']) {
          // 已經授權,可以(yǐ)直接調用 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授權,獲得用戶頭像和(hé / huò)昵稱
  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.png

已授權頁面

image.png

動圖演示

image


相關案例查看更多