微信小程序登陆 + 基于JWT的Token 验证 + 内部用户登陆系统
公司需要做一个用于内部员工的培训系统的小程序,之前只是了解过,但是并没有自己动手做过小程序,以下是记录自己这次的开发过程。
文档层解析
微信官方登陆文档
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
1、微信小程序端调用wx.login 获取一个code(这个code是变化的,即每次调用都会不同,导致session_key也会变化,所以不要频繁调用这个,一定要在登陆态过期再掉。怎么校验登陆态是否过期呢可以用wx.checkSession(Object object) 去检验当前session_key是否过期)
2、在服务器端可以调用auth.code2Session的接口去获取openid和session_key和unionid
3、妥善保存session_key 这个session_key在之后解密中可以用的到。用jwt 带上session_key和openid生成token(登陆态) 返回小程序
4、小程序端把token存入缓存中 wx.setStorageSync(string key, any data)
5、所有wx.request发送请求到后端的接口中,都把这个登陆态token 放入请求头中。
在app.js 封装一个 wx.request的公共方法用来像后端发请求.在这里统一把token取出来放到请求头中
6、后端做全局拦截器,处理token
代码层解析
1、在小程序index.js的onLoad方法中 做登陆检测
例子:
const app = getApp()
const {
http } = getApp()
onLoad: function() {
var _this = this
wx.checkSession({
success: (res) => {
// 判断是否有token,有token 说明通过了 学院 内部用户的验证
var token = wx.getStorageSync('accessToken')
if(token===null || token===undefined || token ==='') {
// 不含有token
_this.loginNoPhoneNumber()
}
},
fail: (res) => {
console.log("未登陆")
_this.loginNoPhoneNumber()
},
})
},
loginNoPhoneNumber () {
var _this = this
wx.login({
success (res) {
if (res.code) {
console.log(res.code)
//发起网络请求
http({
url:'client/weChatLogin',
data:{
code:res.code,
},
}).then(res => {
if (res.data.code === 1) {
let openId = res.data.data.openId
wx.setStorageSync('openId',openId)
if(res.data.data.accessToken) {
// 说明登陆成功
wx.setStorageSync('accessToken', res.data.data.accessToken)
} else {
// 获取手机号的弹窗
_this.setData({
show : true
})
}
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
},
getphonenumberMethod (e) {
console.log(e.detail.errMsg)
console.log(e.detail.iv)
console.log(e.detail.encryptedData)
var this_ = this
this_.setData({
iv : e.detail.iv,
encryptedData : e.detail.encryptedData
})
// 用手机号登陆
var openId_ = wx.getStorageSync('openId')
http({
url:'client/weChatLoginByPhoneNumber',
data:{
openId:openId_,
encryptedData:e.detail.encryptedData,
iv:e.detail.iv,
},
}).then(res => {
console.log(res.data)
if (res.data.code === 1) {
wx.setStorageSync('accessToken', res.data.data.accessToken)
this_.setData({
show:false
})
} else{
this_.setData({
show:false,
notInnerUser:true
})
}
})
},
index.wxml中代码
<van-popup show="{
{ show }}" closeable
close-icon="close" bind:close="onClose" custom-style="width:600rpx;height:500rpx;text-align:center">
<View className='bg'>
<view class="bg_authorization">
<text class="header-title">
需要您的授权登录
</text>
</view>
<View class="bg_require">
<text>由于您是第一次登陆,所以我\n们需要获取到您的手机号,\n请点击下方按钮来获取手机号</text>
</View>
<view class="button" >