前言
當微信小程序項目中涉及到獲取用戶信息并實現用戶登錄時,可以通過微信官方提供的登錄能力方便地獲取微信的用戶身份標識,快速建立小程序內的用戶體系。官方文檔只是提供如何去調用授權登錄,如果直接原封不動的照搬文檔來進行代碼編寫,這樣勢必會造成代碼的維護性差,所以本篇著重介紹如果更優雅的處理微信小程序的授權登錄。
授權登錄的基本流程
上圖是微信小程序官網提供的授權登錄基本流程圖,這里我只從前端開發的角度來講解一下該流程。
- 通過wx.login()獲取臨時登錄憑證code。
- 通過調用服務端提供的接口把code傳遞給服務端,然后服務端會返回給前端openid和sesstion_key。這就代表已經成功完成授權登錄了,至于openid和sesstion_key的用途,后面再進行講解。
大體的登錄流程搞清楚之后,就可以進行代碼的編寫了。因為微信提供的api接口調用不利于代碼維護,所以我借助了promise進行封裝處理(不了解的可以看ES6文檔,里面有詳細介紹),這樣做的好處就是以后可以鏈式調用接口,也可以結合async/await(ES6語法)將異步接口進行同步處理。
get/post 接口的封裝處理
在根目錄中創建service文件夾,用于存放與接口相關的代碼,在service文件夾創建一個myRequest.js文件并對小程序的get/post請求進行封裝處理,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
//get請求封裝(跳頁判斷) //通過全局函數getApp可以獲取全局變量,需要全局的數據可以在根目錄下的app.js進行設置 let app=getApp(); const myGet = (url, data)=>{ return new Promise((resolve, reject)=>{ wx.request({ url: `${app.globalData.HTTP}${url}`, data:data, method: "GET" , //這個authorization就是含有openid和sesstion_key信息的值 header: { 'authorization' : app.globalData.authorization}, //獲取全局變量中的用戶信息,并放入到請求頭中 success:(res)=>{ if (res.data.code == 409) { //409代表用戶未進行登錄,強制跳到寫好的登錄頁 wx.navigateTo({ url: '../login/login' }) } else { resolve(res.data); } }, fail:(res)=>{ reject(); } }) }) } //post請求封裝(跳頁判斷) const myPost = (url, data) => { return new Promise((resolve, reject) => { wx.request({ url: `${app.globalData.HTTP}${url}`, data: data, method: "POST" , header: { 'authorization' : app.globalData.authorization}, success: (res) => { if (res.data.code == 409){ wx.navigateTo({ url: '../login/login' }) } else { resolve(res.data); } }, fail: (res) => { reject(); } }) }) } module.exports = { myGet, myPost, } |
全局變量配置app.js代碼如下(注意全局變量數據會在刷新頁面或是重新進入小程序之后初始化,并不能永久保存當前的數據狀態):
1
2
3
4
5
6
7
8
9
10
11
|
//app.js App({ onLaunch: function () { //這里可以根據項目實際需求寫一些項目初始化需要執行的代碼 }, globalData: { HTTP: "https://shop.yamecent.com/" , //我們獲取openid和sesstion_key之后,會把它存放到小程序內存的authorization中,這樣數據不會丟失,除非刪除該小程序 authorization: wx.getStorageSync( 'authorization' ) || "" , //獲取存儲在小程序內存中的authorization } }) |
授權登錄接口封裝
這部分封裝會用到async/await,將異步接口進行同步處理,不了解的可以參看ES6文檔說明,在service文件夾下創建login.js代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
const myRequest = require( './myRequest.js' ); const app = getApp(); const HTTP = app.globalData.HTTP; //微信login接口獲取code封裝 const myLogin=()=>{ return new Promise((resolve, reject)=>{ wx.login({ success:(res)=>{ resolve(res.code); }, fail:(res)=>{ reject(res.errMsg); console.log( "微信登錄獲取code失敗" ); } }) }) } //獲取openid和session_key接口封裝 const getUserMsg=(myUrl,myData)=>{ return new Promise((resolve,reject)=>{ wx.request({ url: myUrl, method: "POST" , data: myData, success:(res)=>{ if (res.data.code==500){ //獲取失敗 wx.showToast({ title: res.data.msg, icon: 'none' , duration: 2000, mask: true , }) resolve(500); //失敗是返回500 } else { resolve(res.data.data); } }, fail:(res)=>{ reject(res.data.msg); console.log( "獲取openid和session_key接口失敗" ); } }) }) } //封裝存儲(注意:這里的存儲過程是異步的) const mySetStorage=(key,val)=>{ return new Promise((resolve, reject) => { wx.setStorage({ key: key, data: val, success: () => { resolve( true ); }, fail: () => { reject( false ); } }) }) } //封裝獲取存儲 const myGetStorage=(key)=>{ return new Promise((resolve,reject)=>{ wx.getStorage({ key: 'key' , success: (res)=>{ resolve(res.data); }, fail:()=>{ reject( "獲取存儲失敗" ); } }) }) } //授權方法封裝 //sendData是通過授權按鈕獲取到的用戶信息,這里要作為參數傳遞給后臺來保存用戶的信息 //cb是授權登錄成功之后所要執行的函數,具體是什么功能的函數,要根據項目需求而定,也可能不需要 const myAuthorize = (sendData,cb= "" ) => { async function accredit() { wx.showLoading({ title: '認證中' , mask: true }) let code = await myLogin(); //微信登陸獲取code接口 sendData.code=code; let author = await getUserMsg(`${HTTP}auth`, sendData); //獲取后臺openid sesstion_key接口 wx.hideLoading(); if (author==500){ return ; } await mySetStorage( "authorization" , author.Authorization); //存到內存中,進入小程序中獲取并存入app.globalData中 app.globalData.authorization = author.Authorization; typeof cb == "function" && cb(author); //回調所需要用的登陸狀態參數 //這里可以補充一下其它業務邏輯,如tabbar用戶購物車數量等邏輯 wx.showToast({ title: '成功授權' , icon: 'success' , duration: 2000, mask: true }); } accredit(); } module.exports = { myAuthorize, mySetStorage, myGetStorage } |
授權登錄封裝好了之后再看看如何在項目中如何使用,由于微信小程序授權只能通過button來觸發,所以使用 button 組件,并將 open-type 指定為 getUserInfo 類型,獲取用戶基本信息。login.wxml代碼如下:
1
|
< button class = 'btn' open-type = "getUserInfo" bindgetuserinfo = 'gotoLogin' >立即登錄</ button > |
login.js代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
// pages/login/login.js const myRequest = require( '../../common/script/myRequest.js' ); const login = require( '../../common/script/login.js' ); const app = getApp(); const HTTP = app.globalData.HTTP; Page({ /** * 頁面的初始數據 */ data: { }, gotoLogin: function (e) { let sendOjb={}; //用于存放用戶信息 if (e.detail.errMsg == "getUserInfo:ok" ){ sendOjb = { avatar: e.detail.userInfo.avatarUrl, nickname: e.detail.userInfo.nickName, sex: e.detail.userInfo.gender, province: e.detail.userInfo.province, city: e.detail.userInfo.city}; login.myAuthorize(sendOjb,()=>{ wx.navigateBack(); //成功之后返回之前的頁面,也可以根據項目需求寫一些其它的邏輯 }) } else { } }, /** * 生命周期函數--監聽頁面加載 */ onLoad: function (options) { }, }) |
結束語
以上代碼復制粘貼到自己的微信小程序項目中就能夠正常運行,如有錯誤或需要改進的地方還請與我聯系,我將及時進行改正。
到此這篇關于微信小程序授權登錄的優雅處理方式的文章就介紹到這了,更多相關微信小程序授權登錄內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://juejin.cn/post/6920072471022567431