app.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. App({
  2. globalData: {
  3. userInfo: null,
  4. token: null,
  5. isLoggedIn: false,
  6. baseUrl: 'https://familial.yunzhixue.cn/manager'
  7. },
  8. onLaunch: function () {
  9. this.checkLoginStatus();
  10. },
  11. checkLoginStatus: function () {
  12. const token = wx.getStorageSync('token');
  13. const userInfo = wx.getStorageSync('userInfo');
  14. if (token && userInfo) {
  15. this.globalData.token = token;
  16. this.globalData.userInfo = userInfo;
  17. this.globalData.isLoggedIn = true;
  18. }
  19. },
  20. login: function (callback) {
  21. wx.login({
  22. success: (res) => {
  23. if (res.code) {
  24. wx.request({
  25. url: `${this.globalData.baseUrl}/api/wechat/login`,
  26. method: 'POST',
  27. data: {
  28. code: res.code
  29. },
  30. success: (response) => {
  31. if (response.data.success) {
  32. this.globalData.token = response.data.token;
  33. this.globalData.userInfo = response.data.user;
  34. this.globalData.isLoggedIn = true;
  35. wx.setStorageSync('token', response.data.token);
  36. wx.setStorageSync('userInfo', response.data.user);
  37. if (callback) callback(null, response.data);
  38. } else {
  39. if (callback) callback(new Error(response.data.message));
  40. }
  41. },
  42. fail: (err) => {
  43. if (callback) callback(err);
  44. }
  45. });
  46. } else {
  47. if (callback) callback(new Error('登录失败'));
  48. }
  49. },
  50. fail: (err) => {
  51. if (callback) callback(err);
  52. }
  53. });
  54. },
  55. logout: function () {
  56. this.globalData.token = null;
  57. this.globalData.userInfo = null;
  58. this.globalData.isLoggedIn = false;
  59. wx.removeStorageSync('token');
  60. wx.removeStorageSync('userInfo');
  61. }
  62. });