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了