yangyin
2024-07-04 685c4651fef543474a812e44e4646a2793178517
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import weappJwt from './weapp-jwt.js';
const utils = require('../utils/util.js')
let Constant = require('../utils/constant.js')
let app = getApp()
let ACCESS_TOKEN_KEY = 'AccessToken'
let API = (params) => {
  
  let tokenInfo = wx.getStorageSync(ACCESS_TOKEN_KEY)
  
  let currentDateTime = new Date().getTime()
  if (!tokenInfo) {
    wx.reLaunch({
      url: '/login/login/index',
    })
    return
  }
 
  const token = tokenInfo.Token;
  const refresh_token = tokenInfo.RefreshToken
 
  if (!refresh_token) {
    wx.reLaunch({
      url: '/login/login/index',
    })
    return
  }
 
  //解析token
  const jwt_token = decryptJWT(token);
  // 获取token失效时间
  const exp_token = getJWTDate(jwt_token.exp).getTime();
  // token失效状态
  const isExpireByToken = currentDateTime >= exp_token
 
  //解析refreshtoken
  const jwt_refresh_token = decryptJWT(refresh_token);
  // 获取refreshToken失效时间
  const exp_refresh_token = getJWTDate(jwt_refresh_token.exp).getTime();
  // refreshToken失效状态
  const isExpireByRefreshToken = currentDateTime >= exp_refresh_token
 
  // console.log(utils.formatTime(new Date()), utils.formatTime(getJWTDate(jwt_token.exp)), utils.formatTime(getJWTDate(jwt_refresh_token.exp)), 22)
  // console.log(new Date().getTime() > getJWTDate(jwt.exp).getTime(), 22)
 
 
  // 判断 token和refreshToken是否都失效,都失效则跳转登录
  if ((isExpireByToken && isExpireByRefreshToken) && tokenInfo.isNeedToken) {
    wx.reLaunch({
      url: '/login/login/index',
    })
    return
  }
 
  // 判断 token 失效但refreshToken没失效
  if ((!isExpireByToken && isExpireByRefreshToken) && tokenInfo.isNeedToken) {
    tokenInfo.Token = refresh_token
    wx.setStorageSync(ACCESS_TOKEN_KEY, tokenInfo)
  }
 
  let defaultParams = {
    url: '',
    method: "GET",
    data: "",
    header: {
      'content-type': 'application/json'
    },
    success: function () {},
    fail: function () {},
    complete: function () {}
  }
 
  let requestParam = Object.assign(defaultParams, params)
  // 判断是否要添加token
  if (tokenInfo.isNeedToken == true) {
    requestParam.header.Authorization = 'Bearer ' + tokenInfo.Token
  }
  wx.request({
    url: requestParam.url,
    method: requestParam.method,
    data: requestParam.data,
    header: requestParam.header,
    success: res => {
      let result = res.data
      if (result.Data != undefined && result.Data == 401) {
        RefreshToken()
        return
      }
      if (result.Code && result.Code != 0) {
     if(result.Code==-3){
      wx.showModal({
        title: result.Message,
        complete: (res) => {
          if (res.cancel) {
            
          }
      
          if (res.confirm) {
            
          }
        }
      })
 
     }
     else{
      wx.showToast({
        title: result.Message,
        icon: 'error',
        duration: 1500
      })
      RefreshToken()
      return
     }
      }
      requestParam.success(res)
    },
    fail: err => {
      requestParam.fail(err)
    },
    complete: () => {
      requestParam.complete()
    }
  })
 
}
const RefreshToken = () => {
  wx.reLaunch({
    url: '/login/login/index',
  })
  return
 
  // 获取账户信息
  // let accountInfo = JSON.parse(wx.getStorageSync("AccountInfo"))
 
  // console.log(accountInfo,60)
  // 获取登录的用户信息
  // let userInfo = wx.getStorageSync("LoginUserInfo");
  // let sysInfo = app.globalData.sysInfo;
  // console.log('打印userInfo', userInfo)
  // let data = {
  //   SoftType: Constant.SoftType,
  //   SoftTag: Constant.SoftTag,
  //   LoginName: accountInfo.LoginName,
  //   LoginPwd: accountInfo.LoginPwd,
  //   CorpID: Constant.CorpID,
  //   WxCode: accountInfo.WxCode,
  //   UJsCode: accountInfo.UJsCode, //是否就是jsCode有待确认
  //   UAvatarUrl: userInfo == null ? "" : userInfo.avatarUrl,
  //   UCity: userInfo == null ? "" : userInfo.city,
  //   UProvince: userInfo == null ? "" : userInfo.province,
  //   UNickName: userInfo == null ? "" : userInfo.nickName,
  //   UGender: userInfo == null ? "" : userInfo.gender + "",
  //   SBrand: sysInfo.brand,
  //   SModel: sysInfo.model,
  //   SPlatform: sysInfo.platform,
  //   SVersion: sysInfo.version
  // }
  // console.log(JSON.stringify(data),110)
  // wx.request({
  //   url: Constant.BASE_SERVER_URL + "User/UserLogin/FromCorpWechatApplet@V1.0",
  //   method: 'POST',
  //   data: data,
  //   header: {
  //     'content-type': 'application/json'
  //   },
  //   fail: function (err) { //请求失败
  //     wx.showModal({
  //       content: '网络信号不好',
  //       showCancel: false,
  //       confirmColor: "#39b5de"
  //     });
  //   },
  //   success: function (res) {
  //     console.log(res, "新的token信息")
 
  //     var result = res.data;
  //     // console.log(result);
  //     if (result.Code != 0) {
  //       wx.showToast({
  //         title: 'token获取失败,请重新登录',
  //         icon: "none",
  //         duration: 2000
  //       })
  //       return;
  //     }
 
  //     var return_data = result.Data;
  //     if (return_data.Status != 0) {
  //       wx.showToast({
  //         title: 'token获取失败,请重新登录',
  //         icon: "none",
  //         duration: 2000
  //       })
  //       return;
  //     }
  //     let Token = return_data.Token
  //     let isNeedToken = false //是否需要Token 当Token失效的时候 判断是否跳转登录
  //     if (Token) {
  //       isNeedToken = true
  //     }
  //     let ExpreTime = new Date().getTime() //获取当前时间戳
 
  //     wx.setStorageSync('AccessToken', {
  //       Token: Token,
  //       ExpreTime: ExpreTime,
  //       isNeedToken: isNeedToken
  //     })
  //     wx.setStorageSync("AccountInfo", JSON.stringify(data))
  //     // 获取新的token后重新调用接口
  //     apiCb(params)
  //   }
  // });
}
 
//解密 JWT token 的信息
function decryptJWT(token) {
 
  token = weappJwt(token)
  return token
}
 
//将 JWT 时间戳转换成 Date
function getJWTDate(timestamp) {
  return new Date(timestamp * 1000);
}
export default API