微信小程序button授權


前瞻:

 

 

微信小程序授權方式改為只能通過button按鈕點擊觸發,拋棄原來的模態框授權模式;

 

  

實現思路:

  實現地方在小程序全局app.js里面觸發,但app.js中無法實現dom操作.故唯一方式就是當獲取到新用戶的時候利用跳轉路由方法,跳轉至一個新的頁面去進行授權操作.

  

案例難點:

  1.app.js中 當驗證授權是 通過wx.getSetting 中的res.authSetting['scope.userInfo'] 判斷是否為新用戶在此做跳轉;

  2.當授權成功時跳轉回首頁,數據無法重新加載,應在app.js中添加一個函數來監控狀態值當授權成功時調用配合數據刷新重新獲取數據;

  3.跳轉的時候運用redirectTo 這樣能實現不授權禁止訪問的需求;

頁面:

 

 

代碼片段:

login.wxml

 

<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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

 

代碼片段直接上了 大佬的 個人因為項目保密


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM