微信小程序 - 获取用户信息的几种方式


1. 老接口(上线使用-测试用button先获取用户信息)

 1   // 登录
 2  wx.login({  3       success: res => {  4         // 发送 res.code 到后台换取 openId, sessionKey, unionId
 5         // 也就是发送到后端,后端通过接口发送到前端,前端接收用户信息等....
 6         wx.setStorageSync('code', res.code);  7         console.log(wx.getStorageSync('code'))  8         
 9         // 获取用户信息
10  wx.getSetting({ 11           success: res => { 12             if (res.authSetting['scope.userInfo']) { 13               // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
14  wx.getUserInfo({ 15                 success: res => { 16                   // 可以将 res 发送给后台解码出 unionId
17                   this.globalData.userInfo = res.userInfo 18 
19                   // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
20                   // 所以此处加入 callback 以防止这种情况
21                   if (this.userInfoReadyCallback) { 22                     this.userInfoReadyCallback(res) 23  } 24  } 25  }) 26  } 27  } 28  }) 29  } 30     })

 

2. button - 官方示例

 

wxml

 1 <!--index.wxml-->
 2 <view class="container">
 3   <view class="userinfo">
 4     <block wx:if="{{!hasUserInfo && canIUse}}" class='show-author'>
 5       <button open-type="getUserInfo" class='show-author' bindgetuserinfo="getUserInfo">
 6 
 7       <!--随意定制 -->
 8         <view class='get-userinfo'>获取用户信息</view>
 9       </button>
10     </block>
11     <block wx:else>
12       <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
13       <text class="userinfo-nickname">{{userInfo.nickName}}</text>
14     </block>
15   </view>
16 </view>

 

wxss

 1 .show-author {
 2  position: absolute;
 3  top: 0;
 4  bottom: 0;
 5  left: 0;
 6  right: 0;
 7  z-index: 99;
 8  background: #000;
 9  opacity: 0.8;
10 }
11 
12 .show-author>.get-userinfo {
13  color: #fff;
14  background-color: #f00;
15  border-radius: 10rpx;
16  top: 50%;
17  margin-top: 70%;
18 }

 

后面的app.js和index.js均是官方示例(或者直接点击拉取Github示例,哈哈)

 

 

 

3. 当然是发送code到后端,我们接收用户信息就OK了


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM