app.ts 2.4 KB

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