beta
This commit is contained in:
parent
a45ddf13d5
commit
bcd986e3f7
46 changed files with 6166 additions and 454 deletions
84
miniprogram-example/services/auth.js
Normal file
84
miniprogram-example/services/auth.js
Normal file
|
@ -0,0 +1,84 @@
|
|||
// auth.js - 认证相关服务
|
||||
|
||||
import request from '../utils/request';
|
||||
|
||||
/**
|
||||
* 微信登录
|
||||
* 1. 调用wx.login获取code
|
||||
* 2. 发送code到服务端换取token和openid
|
||||
* 3. 保存token和openid到本地存储
|
||||
*/
|
||||
export const wxLogin = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
wx.login({
|
||||
success: (res) => {
|
||||
if (res.code) {
|
||||
// 发送code到服务端
|
||||
request({
|
||||
url: '/login',
|
||||
method: 'POST',
|
||||
data: {
|
||||
code: res.code
|
||||
}
|
||||
}).then(response => {
|
||||
// 保存token和openid
|
||||
if (response.data && response.data.token && response.data.openid) {
|
||||
wx.setStorageSync('token', response.data.token);
|
||||
wx.setStorageSync('openid', response.data.openid);
|
||||
resolve(response.data);
|
||||
} else {
|
||||
reject(new Error('登录失败,服务器返回数据格式错误'));
|
||||
}
|
||||
}).catch(err => {
|
||||
reject(err);
|
||||
});
|
||||
} else {
|
||||
reject(new Error('登录失败,获取code失败: ' + res.errMsg));
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
reject(new Error('微信登录失败: ' + err.errMsg));
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 检查登录状态
|
||||
* 1. 检查本地是否有token和openid
|
||||
* 2. 如果有,验证token是否有效
|
||||
* 3. 如果无效,清除本地存储并返回false
|
||||
*/
|
||||
export const checkLoginStatus = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const token = wx.getStorageSync('token');
|
||||
const openid = wx.getStorageSync('openid');
|
||||
|
||||
if (!token || !openid) {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 验证token有效性
|
||||
request({
|
||||
url: '/verify-token',
|
||||
method: 'POST'
|
||||
}).then(() => {
|
||||
resolve(true);
|
||||
}).catch(() => {
|
||||
// token无效,清除本地存储
|
||||
wx.removeStorageSync('token');
|
||||
wx.removeStorageSync('openid');
|
||||
resolve(false);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
*/
|
||||
export const logout = () => {
|
||||
wx.removeStorageSync('token');
|
||||
wx.removeStorageSync('openid');
|
||||
return Promise.resolve();
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue