You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

99 lines
2.9 KiB

  1. const request = require('./utils/request')
  2. import { timestampToTime } from './utils/util'
  3. App({
  4. globalData: {
  5. },
  6. onLaunch() {
  7. const that = this
  8. // 登录
  9. wx.login({
  10. success: res => {
  11. // 发送 res.code 到后台换取 openId, sessionKey, unionId
  12. console.log(res, 'wx.login')
  13. doLogin(res.code)
  14. },
  15. })
  16. // 获取小程序AccessToken
  17. const getWxToken = secret => {
  18. const data = {
  19. grant_type: 'client_credential',
  20. appid: 'wxf288a9b8167ff2ca',
  21. secret: secret
  22. }
  23. wx.request({
  24. url: 'https://api.weixin.qq.com/cgi-bin/stable_token',
  25. header: {
  26. "Content-Type": "application/json;charset=UTF-8",
  27. },
  28. data: data,
  29. method: "POST",
  30. success: res => {
  31. console.log(res, 'getWxToken');
  32. wx.setStorageSync('AccessToken', res.data.access_token)
  33. },
  34. fail: err => { }
  35. });
  36. }
  37. /**
  38. * @description 登录
  39. * @param {*} loginData {code , appid}
  40. * @returns token , sessionKey , openId
  41. */
  42. const doLogin = code => {
  43. const data = {
  44. code,
  45. appId: request.appId
  46. }
  47. request.post({
  48. url: '/api/user/login',
  49. data
  50. }).then(res => {
  51. console.log(res, 'loginSuccess');
  52. // 存储数据
  53. request.setHead(res.data.token, res.data.tenantId)
  54. wx.setStorageSync('sessionKey', res.data.sessionKey)
  55. that.globalData.sessionKey = res.data.sessionKey
  56. wx.setStorageSync('openId', res.data.openId)
  57. that.globalData.openId = res.data.openId
  58. wx.setStorageSync('token', res.data.token)
  59. that.globalData.token = res.data.token
  60. // 检查用户信息
  61. checkUserInfo()
  62. }).catch(err => {
  63. console.log(err);
  64. wx.showToast({
  65. title: '网络错误,请稍后再试',
  66. icon: 'none'
  67. })
  68. })
  69. }
  70. /**
  71. * @description 检查用户信息
  72. * @returns userInfo
  73. */
  74. const checkUserInfo = () => {
  75. const that = this
  76. request.get({
  77. url: '/api/user/userinfo'
  78. }).then(res => {
  79. console.log(res, 'userinfo');
  80. res.data.createDate = res.data.createDate ? timestampToTime(res.data.createDate, 'YYYY-MM-DD hh:mm:ss') : ''
  81. res.data.updateDate = res.data.updateDate ? timestampToTime(res.data.updateDate, 'YYYY-MM-DD hh:mm:ss') : ''
  82. res.data.validStartTime = res.data.validStartTime ? timestampToTime(res.data.validStartTime, 'YYYY-MM-DD hh:mm:ss') : ''
  83. res.data.validEndTime = res.data.validEndTime ? timestampToTime(res.data.validEndTime, 'YYYY-MM-DD hh:mm:ss') : ''
  84. const userInfo = res.data
  85. that.globalData.userInfo = userInfo
  86. // getWxToken(res.data.secret)
  87. // 请求完成后的回调,在index.js中调用防止异步
  88. that.userInfoCallback(res)
  89. }).catch(err => {
  90. console.log(err, 'err');
  91. })
  92. }
  93. },
  94. })