前瞻:css
微信小程序受權方式改成只能經過button按鈕點擊觸發,拋棄原來的模態框受權模式;
實現思路:數據庫
實現地方在小程序全局app.js裏面觸發,但app.js中沒法實現dom操做.故惟一方式就是當獲取到新用戶的時候利用跳轉路由方法,跳轉至一個新的頁面去進行受權操做.json
案例難點:小程序
1.app.js中 當驗證受權是 經過wx.getSetting 中的res.authSetting['scope.userInfo'] 判斷是否爲新用戶在此作跳轉;微信小程序
2.當受權成功時跳轉回首頁,數據沒法從新加載,應在app.js中添加一個函數來監控狀態值當受權成功時調用配合數據刷新從新獲取數據;微信
3.跳轉的時候運用redirectTo 這樣能實現不受權禁止訪問的需求;app
頁面:dom
代碼片斷:函數
login.wxmlthis
<view wx:if="{{canIUse}}"> <view class='header'> <image src='/images/wx_login.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.wcss
.header { margin: 90rpx 0 90rpx 50rpx; border-bottom: 1px solid #ccc; text-align: center; width: 650rpx; height: 300rpx; line-height: 450rpx; } .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.json
{
"navigationBarTitleText": "受權登陸"
}
app.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) { //從數據庫獲取用戶信息 that.queryUsreInfo(); //用戶已經受權過 wx.switchTab({ url: '' }) } }); } } }) }, bindGetUserInfo: function (e) { if (e.detail.userInfo) { //用戶按了容許受權按鈕 var that = this; //插入登陸的用戶的相關信息到數據庫 wx.request({ url: getApp().globalData.urlPath + 'hstc_interface/insert_user', data: { openid: getApp().globalData.openid, nickName: e.detail.userInfo.nickName, avatarUrl: e.detail.userInfo.avatarUrl, province:e.detail.userInfo.province, city: e.detail.userInfo.city }, header: { 'content-type': 'application/json' }, success: function (res) { //從數據庫獲取用戶信息 that.queryUsreInfo(); console.log("插入小程序登陸用戶信息成功!"); } }); //受權成功後,跳轉進入小程序首頁 wx.switchTab({ url: '' }) } else { //用戶按了拒絕按鈕 wx.showModal({ title:'警告', content:'您點擊了拒絕受權,將沒法進入小程序,請受權以後再進入!!!', showCancel:false, confirmText:'返回受權', success:function(res){ if (res.confirm) { console.log('用戶點擊了「返回受權」') } } }) } }, //獲取用戶信息接口 queryUsreInfo: function () { wx.request({ url: getApp().globalData.urlPath + 'hstc_interface/queryByOpenid', data: { openid: getApp().globalData.openid }, header: { 'content-type': 'application/json' }, success: function (res) { console.log(res.data); getApp().globalData.userInfo = res.data; } }); }, })
補充:
---------------------
做者:csdn_小東
來源:CSDN
原文:https://blog.csdn.net/weidong_y/article/details/79636386
版權聲明:本文爲博主原創文章,轉載請附上博文連接!
代碼片斷直接上了 大佬的 我的由於項目保密