微信小程序登录流程
前端使用Taro Vue3,后端服务器语言为Golang
1.本地验证Storage
小程序刚打开时获取storage中的userinfo
如果没有内容,则将默认游客数据存入。
如果有内容,则检查userinfo中hash3rd有无数据
如果存在hash3rd,服务端请求检测hash3rd是否有效
如果hash3rd有效,则直接将userinfo绑定
如果hash3rd无效,则先将userinfo清空,并存入游客数据
如果hash3rd为空,则证明为游客数据,直接绑定
wxchecksession = () => {
//验证本地储存的session3rd
var value = Taro.getStorageSync('userinfo')
if (value) {
if (value.hash3rd != "") {
Taro.request({
url: 'https://www.hugmeok.top/go_api/api/v2/checklogin?session3rd='+value.hash3rd,
header: {
'content-type': 'application/json'
},
success (res) {
if (res.data) {
//session有效,直接使用userinfo
console.log("session 有效!!!!!!!!!!!!!")
//绑定userinfo到前端
binduserinfo()
loading.value = false
}else{
//session过期,需要注册新session,先将storage清空,再将匿名用户加入storage
try {
Taro.clearStorageSync()
} catch(e) {
// Do something when catch error
console.log(e)
}
try {
Taro.setStorageSync('userinfo', {
"hash3rd":"",
"userinfo":{
"nickName":"游客",
"gender":1,
"city":"",
"province":"",
"country":"",
"avatarUrl":"https://www.hugmeok.top/image/pic/xing.jpg",
"language":"",
"watermark":{
"timestamp":0,
"appid":""
}
}
})
} catch (e) {
console.log(e)
}
binduserinfo() //vue中绑定修改的数据到前端函数
}
}
})
}
if(value.hash3rd == "") {
//storage中hash3rd为空,需要注册
console.log("storage中没有用户信息,需要注册");
binduserinfo()
}
}else{
//storage中没有userinfo
try {
Taro.setStorageSync('userinfo', {
"hash3rd":"",
"userinfo":{
"nickName":"游客",
"gender":1,
"city":"",
"province":"",
"country":"",
"avatarUrl":"https://www.hugmeok.top/image/pic/xing.jpg",
"language":"",
"watermark":{
"timestamp":0,
"appid":""
}
}
})
} catch (e) {
console.log(e)
}
binduserinfo() //vue中绑定修改的数据到前端函数
}
}
2.获取code、encryptedData、iv
wxGetUserProfile = () => {
return new Promise((resolve, reject) => {
Taro.getUserProfile({
lang: 'zh_CN',
desc: '用户登录',
success: (res) => {
binduserinfo()
resolve(res)
// res.encryptedData,
// res.iv
},
// 失败回调
fail: (err) => {
reject(err)
}
})
})
}
wxSilentLogin = () => {
return new Promise((resolve, reject) => {
Taro.login({
success (res) {
resolve(res.code)
},
fail (err) {
reject(err)
}
})
})
}
3.利用code换取session_key、openid
由于要规定wxSilentLogin函数与wxGetUserProfile函数的执行顺序,利用promise再wxLogin函数中规定,并携带code、encryptedData、iv请求自己的服务器的接口
特别需要注意的是,wxLogin函数中因为包含Taro.getUserProfile函数,前端要绑定为事件执行(按钮点击事件)
wxLogin = () => {
let p1 = wxSilentLogin()
let p2 = wxGetUserProfile()
Promise