app.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // app.ts
  2. import { api_login, api_queryUserInfo } from './api/login';
  3. const config = require("./config");
  4. App<IAppOption>({
  5. globalData: {
  6. // 在客服页面使用
  7. top: 0, // 初始的上偏移
  8. baseUrl: config?.baseUrl,
  9. appId: '',
  10. deviceNum: '', // 设备信息
  11. isLogin: false, // 是否登录
  12. userInfo: {} as any
  13. },
  14. onLaunch() {
  15. // 展示本地存储能力
  16. // const logs = wx.getStorageSync('logs') || []
  17. // logs.unshift(Date.now())
  18. // wx.setStorageSync('logs', logs)
  19. this.setAppId();
  20. // 登录
  21. wx.login({
  22. success: async (res) => {
  23. this.onLogin(res.code)
  24. },
  25. })
  26. },
  27. setAppId() {
  28. //获取当前小程序appId
  29. const accountInfo = wx.getAccountInfoSync();
  30. this.globalData.appId = accountInfo.miniProgram.appId;
  31. // wxRequest.config.appid = accountInfo.miniProgram.appId;
  32. //先设置appid再引入接口文件,防止appid未更新问题
  33. // require("./utils/request/api.js");
  34. // 获取设备信息
  35. const deviceInfo = wx.getDeviceInfo()
  36. // 品牌 设备型号 操作系统及版本 客户端平台
  37. const deviceNum = deviceInfo.brand + '-' + deviceInfo.model + '-' + deviceInfo.platform + '-' + deviceInfo.system
  38. this.globalData.deviceNum = deviceNum
  39. // 设置客服初始位置
  40. const systemInfo = wx.getWindowInfo();
  41. this.globalData.top = systemInfo.windowHeight - 180
  42. },
  43. // userInfoReadyCallback(result) {
  44. // console.log(result, 'result')
  45. // }
  46. /** 微信登录 */
  47. async onLogin(code: string) {
  48. wx.showLoading({
  49. mask: true,
  50. title: "加载中...",
  51. });
  52. try {
  53. // 开始登录
  54. const { data } = await api_login({
  55. autoRegister: false,
  56. client_id: 'cooleshow-student-wxlite',
  57. client_secret: 'cooleshow-student-wxlite',
  58. deviceNum: this.globalData.deviceNum,
  59. extra: '',
  60. grant_type: 'password',
  61. loginType: 'WECHAT_MA',
  62. multiUser: false,
  63. username: this.globalData.appId,
  64. password: code
  65. })
  66. if(data.code === 200) {
  67. const userToken = data.data.token_type + " " + data.data.access_token;
  68. wx.setStorageSync("token", userToken);
  69. this.globalData.isLogin = true;
  70. const users = await api_queryUserInfo({ wxAppId: this.globalData.appId })
  71. if(users.data.code === 200) {
  72. this.globalData.userInfo = users.data.data
  73. } else {
  74. wx.removeStorageSync("token");
  75. this.globalData.isLogin = false
  76. }
  77. // console.log(users)
  78. } else {
  79. this.globalData.isLogin = false;
  80. }
  81. } catch {}
  82. wx.hideLoading()
  83. }
  84. })