微信小程序授權登錄


目錄

 

 
自定義授權頁面

 

點擊授權登錄后出現微信自帶的授權登錄彈窗

 

<!--index.wxml-->

<!-- 授權界面 -->
< cover-view class= 'auth_wrap' wx:if= "{{hasUserInfo && canIUse}}">
< cover-view class= 'con'>
< cover-image class= 'logo' mode= "widthFix" src= '../../assets/mrys_logo.png'>
</ cover-image >
< cover-view class= 'txt'>XXXXXX小程序申請一下權限: </ cover-view >
< cover-view class= 'txt'>獲取你的公開信息(頭像和昵稱等) </ cover-view >
< button class= 'btn' type= 'primary' open-type= "getUserInfo" bindgetuserinfo= "getUserInfo"> 授權登錄 </ button >
</ cover-view >
</ cover-view >

 

//app.js
App({
onLaunch: function () {
},
globalData: {
'hasUserInfo': false,
'code': null,
'userInfo': null
}
})

 

//index.js
const app = getApp();
Page({
data: {
userInfo: {},
hasUserInfo: false, //未授權不顯示
canIUse: wx.canIUse( 'button.open-type.getUserInfo') //判斷小程序的API,回調,參數,組件等是否在當前版本可用。
},
onLoad: function () {
var self= this;
// 獲取用戶信息
wx.getSetting({
success: res => {
if (res.authSetting[ 'scope.userInfo']) {
wx.getUserInfo({
success: res => {
// 可以將 res 發送給后台解碼出 unionId
app.globalData.userInfo = res.userInfo
// console.log(app.globalData.userInfo);

// 登錄
wx.login({
success: res => {
// 發送 res.code 到后台換取 openId, sessionKey, unionId
getApp().globalData.code = res.code;
console.log(getApp().globalData.code);
wx.request({
url: 'https:xxxxxxxxxxxxxxxxxxxxxx',
data: {
'code': getApp().globalData.code,
},
method: 'POST',
success: function (res) {
console.log(res);
getApp().globalData.uid = res.data.data.uid;
console.log( 'uid====',getApp().globalData.uid);
}
})
 
}
})
}
})
} else {
// 用戶沒有授權
// 改變 hasUserInfo 的值,顯示授權頁面
self.setData({
hasUserInfo: true
});
}
}
})
},
getUserInfo: function (e) {
if (e.detail.userInfo) {
console.log(e.detail.userInfo);
//用戶按了允許授權按鈕
var self = this;
//授權成功后,通過改變 hasUserInfo 的值,讓實現頁面顯示出來,把授權頁面隱藏起來
self.setData({
userInfo: e.detail.userInfo,
hasUserInfo: false
});
 
} else {
//用戶按了拒絕按鈕
wx.showModal({
title: '警告',
content: '您點擊了拒絕授權,將無法進入小程序,請授權之后再進入!!!',
showCancel: false,
confirmText: '返回授權',
success: function (res) {
// 用戶沒有授權成功,不需要改變 isHide 的值
if (res.confirm) {
console.log( '用戶點擊了“返回授權”');
}
}
});
}
},


免責聲明!

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



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