微信小程序授權登錄---“允許”或“拒絕”等等操作


由於最新的微信公眾平台官方文檔將不再出現以前默認的授權彈窗,因為官方修改了wx.getUserInfo接口,所以需要我們自定義一個授權窗口。

1、思路
第一步:用戶在進入微信小程序首頁時,需要調用wx.getSetting()方法判斷用戶是否授權了。
第二步:1、如果上面的方法判斷用戶已經授權了,則繼續小程序的正常操。2、如果未被授權,則跳轉到自定義的授權頁面。
第三步:點擊自定義授權頁面的授權按鈕,出現授權彈窗,彈窗中包括“拒絕”與“允許”兩種操作 。當我們點擊“拒絕”時,說明我們拒絕授權了,繼續保留自定義的授權提示頁面,不允許繼續跳到小程序其他頁面,直到你允許授權為止。當點擊“允許”按鈕時,則跳到小程序首頁。

2、大致界面

3、源碼
index.js(判斷用戶有沒有授權)

Page({
data: {
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
},
onLoad: function () {
var that = this;
// 判斷是否已經授權
wx.getSetting({
success: (res) => {
if (res.authSetting['scope.userInfo']) {//授權了,可以獲取用戶信息了
wx.getUserInfo({
success: (res) => {
console.log(res)
}
})
}else{//未授權,跳到授權頁面
wx.redirectTo({
url: '../authorize/authorize',//授權頁面
})
}
}
})
},
})
authorize.wxml (自定義授權頁面,這里只是用來展示功能,頁面樣式可以根據自己喜好自由發揮,但一定要記得授權按鈕時必須有的)

<!--授權頁面-->
<view wx:if="{{canIUse}}">
<view class='header'>
<image src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1541568049159&di=2a7c5f20a198ec9bf72c9a84deb9c0db&imgtype=0&src=http%3A%2F%2Fwww.sj520.cn%2Fsc%2Fima%2Fweixin_sj520_25.jpg'></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>
authorize.wxss(授權樣式)

/* pages/authorize/authorize.wxss */
.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;
}
authorize.json(授權配置頁面)

{
"navigationBarTitleText": "授權登錄"
}
authorize.js(授權操作)

// pages/authorize/authorize.js
import requestUrl from '../../utils/util.js'
var globalOpenId = getApp().globalData.openId;
Page({

/**
* 頁面的初始數據
*/
data: {
// 判斷小程序的API,回調,參數,組件等是否在當前版本可用。
canIUse: wx.canIUse('button.open-type.getUserInfo')//獲取用戶信息是否在當前版本可用
},

/**
* 生命周期函數--監聽頁面加載
*/
onLoad: function (options) {

},
bindGetUserInfo: function (e) {//點擊的“拒絕”或者“允許
if(e.detail.userInfo){//點擊了“允許”按鈕,
var that=this;
requestUrl.requestUrl({//將用戶信息傳給后台數據庫
url: "/QXEV/xxx/xxx",
params: {
openId: globalOpenId,//用戶的唯一標識
nickName: e.detail.userInfo.nickName,//微信昵稱
avatarUrl: e.detail.userInfo.avatarUrl,//微信頭像
province: e.detail.userInfo.province,//用戶注冊的省
city: e.detail.userInfo.city//用戶注冊的市
},
method: "post",
})
.then((data) => {//then接收一個參數,是函數,並且會拿到我們在requestUrl中調用resolve時傳的的參數
console.log("允許授權了");
})
.catch((errorMsg) => {
console.log(errorMsg)
})
wx.switchTab({
url: '../VehicleIndex/VehicleIndex',
})
}
}
})
說明一:如果出現 getApp().globalData.openId為undefined或者其他取不到值的情況,說明你全局沒有配置這個數據,根據自己的項目需求,如果不需要這個openid,可以刪除。以下是我自己的全局配置過程,通過wx.login()從后台獲取的openid,然后我將其存在了全局變量中。
app.js

//app.js
import requestUrl from './utils/util.js'
App({
onLaunch: function () {
// 登錄;用戶打開小程序時,會調用wx.login獲取code,將code發送到后台獲取openid。后台保存opendi並返回用戶信息
//(首次登錄信息為空,非首次登錄信息存在)
wx.login({
success: res => {
// 發送 res.code 到后台換取 openId, sessionKey, unionId
if(res.code){
requestUrl.requestUrl({
url: "/QXEV/xxx/xxx",
params:{
code:res.code
},
method:"post",
})
.then((data)=> {//then接收一個參數,是函數,並且會拿到我們在requestUrl中調用resolve時傳的的參數
console.log(data);//返回openId
this.globalData.openId = res.openId;
})
.catch((errorMsg)=>{
console.log(errorMsg)
})
}
}
})
},
globalData: {
userInfo: "",//用戶信息
openId:"",//登錄用戶的唯一標識
appid: 'wx242f88b4c25643c2',//appid
secret: 'e0dassda466b98dd75bac9ad5b760218075b0577def2424234209bwXXXXXXXXXXXXXX',//secret秘鑰
},
onHide:function(){//小程序退出時觸發的事件
console.log("小程序完全退出了")
}
})
說明二:報requestUrl is not defined錯誤,出現這個錯誤,是因為我自己封裝了一個wx.request(),你可以改成自己封裝的請求方法或者用官網文檔自帶的請求方法。以下是我自己封裝的可以參考,哪里不足希望可以提出來,我會進一步優化。

util.js

/* 公共request 方法 */
const requestUrl=({
url,
params,
success,
method="post"
})=>{
wx.showLoading({
title: '加載中',
});
let server = 'http://xxxxxxxxxx';//正式域名
// let server = 'http://dxxx.xxxxxxxxxx.cn';//測試域名
let sessionId=wx.getStorageSync("sid"),
that=this;
if (sessionId != "" && sessionId !=null){
var header = { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'sid=' + sessionId }
}else{
var header = { 'content-type': 'application/x-www-form-urlencoded'}
}
return new Promise((resolve, reject) =>{
wx.request({
url: server + url,
method: method,
data: params,
header: header,
success: (res) => {
wx.hideLoading();
if (sessionId == "" || sessionId == null) {
wx.setStorageSync('sid', res.data.info.sessionId)// 如果本地沒有就說明第一次請求 把返回的 sessionId 存入本地
}
if (res['statusCode'] == 200){
resolve(res)//異步成功之后執行的函數
}else{
wx.showToast({
title: res.data.msg || '請求出錯',
icon: 'none',
duration: 2000,
mask: true
})
reject(res.ErrorMsg);
}
},
fail: (res)=> {
wx.hideLoading();
wx.showToast({
title: res.data.msg || '',
icon: 'none',
duration: 2000,
mask: true
})
reject('網絡出錯');
},
complete: function () {
wx.hideLoading()
}
})
})
}
module.exports = {
requestUrl: requestUrl


免責聲明!

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



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