app.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // app.js
  2. const { utils } = require('./utils/api.js');
  3. App({
  4. onLaunch() {
  5. // 展示本地存储能力
  6. const logs = wx.getStorageSync('logs') || []
  7. // logs.unshift(Date.now())
  8. // wx.setStorageSync('logs', logs)
  9. // 微信登录获取token
  10. this.wxLogin()
  11. },
  12. // 微信登录方法
  13. wxLogin() {
  14. wx.login({
  15. success: (res) => {
  16. if (res.code) {
  17. console.log('微信登录获取code成功:', res.code)
  18. // 调用登录接口
  19. this.callLoginApi(res.code)
  20. } else {
  21. console.error('微信登录失败:', res.errMsg)
  22. }
  23. },
  24. fail: (error) => {
  25. console.error('微信登录调用失败:', error)
  26. }
  27. })
  28. },
  29. // 调用登录接口
  30. callLoginApi(code) {
  31. wx.request({
  32. url: 'https://sit-kelamayi.4dage.com/api/museum/wxMini/login',
  33. method: 'GET',
  34. data: {
  35. code: code
  36. },
  37. header: {
  38. 'content-type': 'application/x-www-form-urlencoded'
  39. },
  40. success: (response) => {
  41. console.log('登录接口调用成功:', response.data)
  42. if (response.data && response.data.code === 0) {
  43. // 存储基本用户信息(微信用户)
  44. const basicUserInfo = {
  45. nickName: '微信用户',
  46. avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
  47. isWxUser: true
  48. }
  49. const token = response.data.data.token
  50. this.globalData.userInfo = basicUserInfo
  51. wx.setStorageSync('userInfo', basicUserInfo)
  52. // 存储token到全局数据
  53. this.globalData.token = token
  54. // 也存储到本地存储
  55. wx.setStorageSync('token', token)
  56. console.log('token获取成功:', token)
  57. // 登录成功后获取token
  58. this.getAccessToken()
  59. } else {
  60. console.error('登录失败:', response.data.message || '未知错误')
  61. }
  62. },
  63. fail: (error) => {
  64. console.error('登录接口调用失败:', error)
  65. }
  66. })
  67. },
  68. // 获取访问token
  69. getAccessToken() {
  70. wx.request({
  71. url: 'https://sit-kelamayi.4dage.com/api/museum/wxMini/getAccessToken',
  72. method: 'GET',
  73. header: {
  74. 'content-type': 'application/x-www-form-urlencoded'
  75. },
  76. success: (response) => {
  77. console.log('获取accessToken接口调用成功:', response.data)
  78. if (response.data && response.data.code === 0) {
  79. const accessToken = response.data.data
  80. // 存储token到全局数据
  81. this.globalData.accessToken = accessToken
  82. // 也存储到本地存储
  83. wx.setStorageSync('accessToken', accessToken)
  84. console.log('accessToken获取成功:', accessToken)
  85. } else {
  86. console.error('获取token失败:', response.data.message || '未知错误')
  87. }
  88. },
  89. fail: (error) => {
  90. console.error('获取token接口调用失败:', error)
  91. }
  92. })
  93. },
  94. globalData: {
  95. userInfo: null,
  96. token: null
  97. }
  98. })