
1、前言
微信官方對getUserInfo接口做了修改,授權窗口無法直接彈出,而取而代之是需要創建一個button,將其open-type屬性綁定getUseInfo方法。在參考了網路上各種方案之后,實現了用戶在授權之后跳轉到小程序首頁的授權登錄頁面。
2、實現效果
3、實現思路
在進入小程序時先對授權情況進行判斷,若已經過授權則直接跳轉到首頁,若還未經過授權則進入授權頁面,點擊頁面的授權按鈕會彈出選擇框,選擇“拒絕”則不進行跳轉,選擇“允許“則進行授權并跳轉到小程序首頁。
4、實現代碼
<!--login.wxml--> <view wx:if="{{canIUse}}"> <view class='header'> <image src='/assets/tasks_icon/check.png'></image> </view> <view class='content'> <view>申請獲取以下權限</view> <text>獲得你的公開信息(昵稱,頭像等)</text> </view> <button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="bindGetUserInfo"> 授權登錄 </button> </view> <view wx:else>請升級微信版本</view> 復制代碼
//login.wxss .header { margin: 90rpx 0 90rpx 50rpx; border-bottom: 1px solid #ccc; text-align: center; width: 650rpx; height: 300rpx; } .header image { width: 200rpx; height: 200rpx; } .content { margin-left: 50rpx; margin-bottom: 90rpx; } .content text { display: block; color: #9d9d9d; margin-top: 40rpx; } .bottom { border-radius: 80rpx; margin: 70rpx 50rpx; font-size: 35rpx; } 復制代碼
//login.js Page({ data: { //判斷小程序的API,回調,參數,組件等是否在當前版本可用。 canIUse: wx.canIUse('button.open-type.getUserInfo') }, onLoad: function () { var that = this; // 查看是否授權 wx.getSetting({ success: function (res) { if (res.authSetting['scope.userInfo']) { wx.getUserInfo({ success: function (res) { // 用戶已經授權過,調用微信的 wx.login 接口,從而獲取code,再直接跳轉到主頁 wx.login({ success: res => { // 獲取到用戶的 code 之后:res.code console.log("用戶的code:" + res.code); } }); wx.switchTab({ url: '/pages/home/home', //這里填入要跳轉目的頁面的url success: (result) => { console.log("跳轉到首頁"); }, fail: () => {} }); } }); } else { // 用戶沒有授權,顯示授權頁面,這里不進行操作 } } }); }, bindGetUserInfo: function (e) { if (e.detail.userInfo) { //用戶按了允許授權按鈕 var that = this; // 獲取到用戶的信息了,打印到控制臺上看下 console.log("用戶的信息如下:"); console.log(e.detail.userInfo); //授權成功后,跳轉頁面 wx.switchTab({ url: '/pages/home/home', //這里填入要跳轉目的頁面的url success: (result) => { console.log("跳轉到首頁"); }, fail: () => {} }); } else { //用戶按了拒絕按鈕 wx.showModal({ title: '警告', content: '您拒絕了授權,將無法進入小程序,請授權之后再進入!', showCancel: false, confirmText: '返回', success: function (res) { // 用戶沒有授權成功,不需要改變 isHide 的值 if (res.confirm) { console.log('用戶點擊了“返回”'); } } }); } } }) 復制代碼
最后在app.json文件中將login設置為第一個頁面即可。
//app.json { "pages": [ "pages/login/login", "pages/home/home" ] }