Codex Assistant
22 小时以前 0a48616045ddce1562584543a0e89e5144051fde
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// app.js
App({
  globalData: {
    userInfo: null,
    token: null,
    sessionKey: null, // 微信会话密钥,用于解密手机号等敏感数据
    baseUrl: 'http://localhost:8080/api/graphql', // 后台GraphQL接口地址
    hasPhoneAuth: false, // 是否已授权手机号
    rejectPhone: false, // 是否拒绝过手机号授权
    cos: {
      secretId: 'AKIDfSG2e3Gev1xgBTaVDiz2rTr790d3FH8l',
      secretKey: 'VmqgIh1B9aopcCYklbBdsthaHkeS3RbY',
      bucket: 'ryc-1379367838',
      region: 'ap-chengdu'
    }
  },
 
  onLaunch() {
    console.log('小程序启动')
    
    // 检查是否拒绝过手机号授权
    const rejectPhone = wx.getStorageSync('rejectPhone')
    if (rejectPhone) {
      this.globalData.rejectPhone = true
    }
 
    // 先恢复本地用户数据到globalData
    this.restoreUserData()
    
    // 始终调用登录流程,获取最新的微信code
    this.login()
  },
 
  onShow() {
    console.log('小程序显示')
  },
 
  onHide() {
    console.log('小程序隐藏')
  },
 
  onError(msg) {
    console.error('小程序错误:', msg)
  },
 
  // 检查登录状态
  // 从本地存储恢复用户数据到globalData(仅用于数据恢复,不做登录判断)
  restoreUserData() {
    console.log('=== 恢复本地用户数据 ===')
    
    try {
      const token = wx.getStorageSync('token')
      const userInfo = wx.getStorageSync('userInfo')
      const sessionKey = wx.getStorageSync('sessionKey')
      
      console.log('本地存储token存在:', !!token)
      console.log('本地存储userInfo存在:', !!userInfo)
      console.log('本地存储sessionKey存在:', !!sessionKey)
      
      if (token) {
        console.log('Token长度:', token.length)
        this.globalData.token = token
      }
      
      if (userInfo) {
        console.log('用户信息:', {
          userId: userInfo.userId,
          name: userInfo.name,
          phone: userInfo.phone || '未授权'
        })
        this.globalData.userInfo = userInfo
      }
      
      if (sessionKey) {
        console.log('SessionKey长度:', sessionKey.length)
        this.globalData.sessionKey = sessionKey
      }
      
      console.log('✅ 本地用户数据恢复完成')
    } catch (err) {
      console.error('❌ 恢复本地用户数据时发生错误:', err)
      // 清除可能损坏的本地存储数据
      try {
        wx.removeStorageSync('token')
        wx.removeStorageSync('userInfo')
        wx.removeStorageSync('sessionKey')
        console.log('已清除损坏的本地存储数据')
      } catch (clearErr) {
        console.error('清除本地存储失败:', clearErr)
      }
    }
  },
 
  // 微信登录
  login() {
    console.log('=== 开始微信登录流程 ===')
    console.log('当前时间:', new Date().toISOString())
    console.log('小程序版本:', wx.getAccountInfoSync().miniProgram.version || 'develop')
    
    wx.login({
      success: (res) => {
        if (res.code) {
          console.log('✅ 获取微信登录code成功')
          console.log('登录code:', res.code)
          console.log('code长度:', res.code.length)
          console.log('准备调用后端wxLogin接口...')
          this.wxLogin(res.code)
        } else {
          console.error('❌ 获取微信登录code失败')
          console.error('错误信息:', res.errMsg)
          console.error('完整响应:', res)
        }
      },
      fail: (err) => {
        console.error('❌ 微信登录API调用失败')
        console.error('错误详情:', err)
        console.error('错误类型:', typeof err)
        wx.showToast({
          title: '登录失败,请重试',
          icon: 'error'
        })
      }
    })
  },
 
  // 调用后台wxLogin接口
  wxLogin(code) {
    const that = this
    const deviceInfo = this.getDeviceInfo()
    const requestData = {
      code: code,
      loginIp: '127.0.0.1', // 小程序无法获取真实IP,使用默认值
      deviceInfo: deviceInfo
    }
    
    console.log('=== 准备调用后端wxLogin接口 ===')
    console.log('请求URL:', 'http://localhost:8080/api/auth/wx-login')
    console.log('设备信息:', deviceInfo)
    console.log('请求参数:', requestData)
    console.log('请求开始时间:', new Date().toISOString())
    
    wx.request({
      url: 'http://localhost:8080/api/auth/wx-login',
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: requestData,
      success: (res) => {
        console.log('=== 后端wxLogin接口响应 ===')
        console.log('响应时间:', new Date().toISOString())
        console.log('HTTP状态码:', res.statusCode)
        console.log('响应头:', res.header)
        console.log('响应数据:', JSON.stringify(res.data, null, 2))
        
        if (res.statusCode !== 200) {
          console.error('❌ HTTP请求失败,状态码:', res.statusCode)
          wx.showToast({
            title: '服务器错误',
            icon: 'error'
          })
          return
        }
        
        // 检查是否有错误信息(适配不同的错误响应格式)
        if (res.data.error || res.data.message || res.data.success === false) {
          const errorMsg = res.data.error || res.data.message || '登录失败'
          console.error('❌ 登录失败:', errorMsg)
          wx.showToast({
            title: errorMsg,
            icon: 'error'
          })
          return
        }
        
        // 检查响应数据格式:支持直接返回WxLoginResponse或包装格式
        let loginResult = null
        if (res.data.token && res.data.userInfo) {
          // 直接返回WxLoginResponse格式
          loginResult = res.data
        } else if (res.data.success && res.data.data) {
          // 包装格式 {success: true, data: WxLoginResponse}
          loginResult = res.data.data
        }
        
        if (loginResult) {
          
          console.log('✅ 登录成功!')
          console.log('用户ID:', loginResult.userInfo.userId)
          console.log('用户名:', loginResult.userInfo.name)
          console.log('手机号:', loginResult.userInfo.phone || '未授权')
          console.log('是否新用户:', loginResult.isNewUser)
          console.log('登录记录ID:', loginResult.loginRecordId)
          console.log('Token长度:', loginResult.token ? loginResult.token.length : 0)
          console.log('SessionKey长度:', loginResult.sessionKey ? loginResult.sessionKey.length : 0)
          
          // 保存登录信息
          try {
            wx.setStorageSync('token', loginResult.token)
            wx.setStorageSync('userInfo', loginResult.userInfo)
            if (loginResult.sessionKey) {
              wx.setStorageSync('sessionKey', loginResult.sessionKey)
            }
            console.log('✅ 登录信息已保存到本地存储')
          } catch (storageErr) {
            console.error('❌ 保存登录信息到本地存储失败:', storageErr)
          }
          
          that.globalData.token = loginResult.token
          that.globalData.userInfo = loginResult.userInfo
          that.globalData.sessionKey = loginResult.sessionKey
          
          // 如果是新用户且未拒绝过手机号授权,弹出手机号授权
          if (loginResult.isNewUser && !that.globalData.rejectPhone) {
            console.log('🔔 新用户,准备显示手机号授权弹窗')
            that.showPhoneAuthModal()
          } else {
            console.log('ℹ️ 老用户或已拒绝手机号授权,跳过授权弹窗')
          }
        } else {
          console.error('❌ 响应数据格式错误,缺少必要字段(token或userInfo)')
          console.error('实际响应:', res.data)
          wx.showToast({
            title: '登录数据格式错误',
            icon: 'error'
          })
        }
      },
      fail: (err) => {
        console.error('=== 后端wxLogin接口请求失败 ===')
        console.error('失败时间:', new Date().toISOString())
        console.error('错误详情:', err)
        console.error('错误类型:', typeof err)
        console.error('错误代码:', err.errMsg || 'unknown')
        
        wx.showToast({
          title: '网络错误,请检查网络连接',
          icon: 'error',
          duration: 3000
        })
      }
    })
  },
 
  // 获取设备信息
  getDeviceInfo() {
    try {
      const systemInfo = wx.getSystemInfoSync()
      return `${systemInfo.brand} ${systemInfo.model} ${systemInfo.system}`
    } catch (e) {
      return 'Unknown Device'
    }
  },
 
  // 显示手机号授权弹窗
  showPhoneAuthModal() {
    wx.showModal({
      title: '手机号授权',
      content: '为了更好的服务体验,建议您授权手机号',
      confirmText: '授权',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 用户点击授权,跳转到授权页面或触发授权流程
          console.log('用户同意授权手机号')
        } else {
          // 用户取消授权,记录到本地存储
          wx.setStorageSync('rejectPhone', true)
          this.globalData.rejectPhone = true
          console.log('用户拒绝授权手机号')
        }
      }
    })
  },
 
  // GraphQL请求封装
  graphqlRequest(query, variables = {}) {
    return new Promise((resolve, reject) => {
      this._makeGraphQLRequest(query, variables, resolve, reject, false)
    })
  },
 
  // 内部GraphQL请求方法,支持重试机制
  _makeGraphQLRequest(query, variables, resolve, reject, isRetry = false) {
    // 确保token的一致性:优先使用globalData中的token,如果没有则从storage获取
    let token = this.globalData.token
    if (!token) {
      token = wx.getStorageSync('token')
      if (token) {
        this.globalData.token = token // 同步到globalData
      }
    }
 
    wx.request({
      url: this.globalData.baseUrl,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      },
      data: {
        query: query,
        variables: variables
      },
      success: (res) => {
        console.log('GraphQL响应:', res.data)
        
        // 检查HTTP状态码
        if (res.statusCode !== 200) {
          // 对于401状态码,可能是认证错误,需要检查响应内容
          if (res.statusCode === 401 && res.data && res.data.errors) {
            console.log('收到401状态码,检查是否为认证错误')
            // 继续处理,让下面的GraphQL错误检查逻辑处理认证错误
          } else {
            console.error('GraphQL HTTP错误:', res.statusCode)
            reject(new Error(`HTTP错误: ${res.statusCode}`))
            return
          }
        }
 
        // 检查GraphQL错误
        if (res.data && res.data.errors) {
          console.error('GraphQL错误:', res.data.errors)
          
          // 检查是否是认证错误(token过期或无效)
          const authErrors = res.data.errors.filter(error => 
            error.message && (
              error.message.includes('没有权限访问') ||
              error.message.includes('请先登录') ||
              error.message.includes('UNAUTHORIZED') ||
              error.extensions?.code === 'UNAUTHORIZED'
            )
          )
          
          if (authErrors.length > 0 && !isRetry) {
            console.log('🔄 检测到认证错误,尝试重新登录...')
            // 清除过期的认证信息
            this.globalData.token = null
            this.globalData.userInfo = null
            this.globalData.sessionKey = null
            wx.removeStorageSync('token')
            wx.removeStorageSync('userInfo')
            wx.removeStorageSync('sessionKey')
            
            // 重新登录
            wx.login({
              success: (loginRes) => {
                if (loginRes.code) {
                  console.log('🔄 重新获取微信code成功,调用后端登录...')
                  this._retryAfterLogin(loginRes.code, query, variables, resolve, reject)
                } else {
                  console.error('❌ 重新获取微信code失败')
                  reject(new Error('重新登录失败'))
                }
              },
              fail: (err) => {
                console.error('❌ 重新登录失败:', err)
                reject(new Error('重新登录失败'))
              }
            })
            return
          }
          
          reject(new Error(res.data.errors[0]?.message || 'GraphQL请求错误'))
          return
        }
 
        // 检查数据
        if (res.data.data !== undefined) {
          resolve(res.data.data)
        } else {
          console.error('GraphQL响应异常:', res.data)
          reject(new Error('GraphQL响应数据异常'))
        }
      },
      fail: (err) => {
        console.error('GraphQL网络请求失败:', err)
        reject(new Error('网络请求失败'))
      }
    })
  },
 
  // 重新登录后重试GraphQL请求
  _retryAfterLogin(code, query, variables, resolve, reject) {
    const that = this
    const deviceInfo = this.getDeviceInfo()
    const requestData = {
      code: code,
      loginIp: '127.0.0.1', // 小程序无法获取真实IP,使用默认值
      deviceInfo: deviceInfo
    }
    
    wx.request({
      url: 'http://localhost:8080/api/auth/wx-login',
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: requestData,
      success: (res) => {
        console.log('🔄 重新登录响应:', res.data)
        
        if (res.statusCode !== 200 || res.data.error) {
          console.error('❌ 重新登录失败:', res.data.error || res.data.message)
          reject(new Error('重新登录失败'))
          return
        }
        
        // 检查响应数据格式
        let loginResult = null
        if (res.data.token && res.data.userInfo) {
          loginResult = res.data
        } else if (res.data.success && res.data.data) {
          loginResult = res.data.data
        }
        
        if (loginResult && loginResult.token) {
          console.log('✅ 重新登录成功,更新token')
          
          // 保存新的登录信息
          try {
            wx.setStorageSync('token', loginResult.token)
            wx.setStorageSync('userInfo', loginResult.userInfo)
            if (loginResult.sessionKey) {
              wx.setStorageSync('sessionKey', loginResult.sessionKey)
            }
          } catch (storageErr) {
            console.error('❌ 保存重新登录信息失败:', storageErr)
          }
          
          that.globalData.token = loginResult.token
          that.globalData.userInfo = loginResult.userInfo
          that.globalData.sessionKey = loginResult.sessionKey
          
          // 使用新token重试原始请求
          console.log('🔄 使用新token重试GraphQL请求...')
          that._makeGraphQLRequest(query, variables, resolve, reject, true)
        } else {
          console.error('❌ 重新登录响应格式错误')
          reject(new Error('重新登录响应格式错误'))
        }
      },
      fail: (err) => {
        console.error('❌ 重新登录网络请求失败:', err)
        reject(new Error('重新登录网络请求失败'))
      }
    })
  }
})