個人博客上已經同步更新了文章,有目錄索引,閱讀起來比較方便,歡迎大家移步個人博客上讀閱~
個人博客地址:http://zwd596257180.gitee.io/blog/2019/04/15/wechat_applet_login/
微信小程序之授權登錄
一、前言
由於微信官方修改了 getUserInfo 接口,所以現在無法實現一進入微信小程序就彈出授權窗口,只能通過 button 去觸發。官方連接:https://developers.weixin.qq.com/community/develop/doc/0000a26e1aca6012e896a517556c01
二、實現思路
自己寫一個微信授權登錄頁面讓用戶實現點擊的功能,也就是實現了通過 button 組件去觸發 getUserInof 接口。在用戶進入微信小程序的時候,判斷用戶是否授權了,如果沒有授權的話就顯示授權頁面,讓用戶去執行授權的操作。如果已經授權了,則直接跳過這個頁面,進入首頁。
三、界面簡介
1.不帶 tabBar
2.帶 tabBar
四、源碼
1.index.wxml
<view wx:if="{{isHide}}">
<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>
</view>
<view wx:else>
<view>我的首頁內容</view>
</view>
2.index.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;
}
3.index.js
Page({
data: {
//判斷小程序的API,回調,參數,組件等是否在當前版本可用。
canIUse: wx.canIUse('button.open-type.getUserInfo'),
isHide: false
},
onLoad: function() {
var that = this;
// 查看是否授權
wx.getSetting({
success: function(res) {
if (res.authSetting['scope.userInfo']) {
wx.getUserInfo({
success: function(res) {
// 用戶已經授權過,不需要顯示授權頁面,所以不需要改變 isHide 的值
// 根據自己的需求有其他操作再補充
// 我這裏實現的是在用戶授權成功後,調用微信的 wx.login 接口,從而獲取code
wx.login({
success: res => {
// 獲取到用戶的 code 之後:res.code
console.log("用戶的code:" + res.code);
// 可以傳給後臺,再經過解析獲取用戶的 openid
// 或者可以直接使用微信的提供的接口直接獲取 openid ,方法如下:
// wx.request({
// // 自行補上自己的 APPID 和 SECRET
// url: 'https://api.weixin.qq.com/sns/jscode2session?appid=自己的APPID&secret=自己的SECRET&js_code=' + res.code + '&grant_type=authorization_code',
// success: res => {
// // 獲取到用戶的 openid
// console.log("用戶的openid:" + res.data.openid);
// }
// });
}
});
}
});
} else {
// 用戶沒有授權
// 改變 isHide 的值,顯示授權頁面
that.setData({
isHide: true
});
}
}
});
},
bindGetUserInfo: function(e) {
if (e.detail.userInfo) {
//用戶按了允許授權按鈕
var that = this;
// 獲取到用戶的信息了,打印到控制檯上看下
console.log("用戶的信息如下:");
console.log(e.detail.userInfo);
//授權成功後,通過改變 isHide 的值,讓實現頁面顯示出來,把授權頁面隱藏起來
that.setData({
isHide: false
});
} else {
//用戶按了拒絕按鈕
wx.showModal({
title: '警告',
content: '您點擊了拒絕授權,將無法進入小程序,請授權之後再進入!!!',
showCancel: false,
confirmText: '返回授權',
success: function(res) {
// 用戶沒有授權成功,不需要改變 isHide 的值
if (res.confirm) {
console.log('用戶點擊了“返回授權”');
}
}
});
}
}
})
關於 TabBar 的處理,只需要把上面寫好的頁面設置到 app.json 裏面即可。
4.github 下載
https://github.com/yyzheng1729/loginDemo
五、福利:微信小程序學習視頻資源分享
需要以下微信小程序項目教學視頻的,可以關注下面的公衆號,回覆 “小程序” 即可獲取百度雲分享鏈接!如果失效的話,可以在公衆號上面私信我。
六、同類文章推薦閱讀