微信小程序授权获取用户信息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;
}

猜你喜欢

转载自blog.csdn.net/weixin_43844696/article/details/108405668