这个接口只能取得一些非敏感信息,例如用户昵称,用户头像,通过用户受权容许获取的状况下即可取得用户信息,至于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;}
未受权页面
已受权页面
动图演示
Author:TANKING
Web:http://www.likeyun.cn/
Date:2020-08-19
WeChat:face6009