欢迎来到代码驿站!

当前位置:首页 >

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

时间:2020-08-19 14:00:07|栏目:|点击:

这个接口只能获得一些非敏感信息,例如用户昵称,用户头像,经过用户授权允许获取的情况下即可获得用户信息,至于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;
}

上一篇:原生JS实现多条件筛选

栏    目:

下一篇:R语言ggplot2边框背景去除的实现

本文标题:微信小程序wx.getUserInfo授权获取用户信息(头像、昵称)的实现

本文地址:http://www.codeinn.net/misctech/3776.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有