1. 程式人生 > 程式設計 >微信小程式wx.getUserInfo授權獲取使用者資訊(頭像、暱稱)的實現

微信小程式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;
}

微信小程式wx.getUserInfo授權獲取使用者資訊(頭像、暱稱)的實現

到此這篇關於微信小程式wx.getUserInfo授權獲取使用者資訊(頭像、暱稱)的實現的文章就介紹到這了,更多相關小程式wx.getUserInfo授權內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!