lrj
19 小时以前 9f8395fab13ca4b230a0f7d62636e209745c91d4
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
// 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:', this.globalData.baseUrl)
    console.log('设备信息:', deviceInfo)
    console.log('请求参数:', requestData)
    console.log('请求开始时间:', new Date().toISOString())
    
    wx.request({
      url: this.globalData.baseUrl,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        query: `
          mutation wxLogin($input: WxLoginRequest!) {
            wxLogin(input: $input) {
              token
              userInfo {
                userId
                name
                phone
                wxOpenid
              }
              isNewUser
              loginRecordId
              sessionKey
            }
          }
        `,
        variables: {
          input: 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.errors) {
          console.error('❌ GraphQL错误:', res.data.errors)
          wx.showToast({
            title: '登录失败',
            icon: 'error'
          })
          return
        }
        
        if (res.data.data && res.data.data.wxLogin) {
          const loginResult = res.data.data.wxLogin
          
          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('❌ 响应数据格式错误,缺少wxLogin字段')
          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) => {
      wx.request({
        url: this.globalData.baseUrl,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': this.globalData.token ? `Bearer ${this.globalData.token}` : ''
        },
        data: {
          query: query,
          variables: variables
        },
        success: (res) => {
          console.log('GraphQL响应:', res.data)
          if (res.data.errors) {
            console.error('GraphQL错误:', res.data.errors)
            reject(res.data.errors)
          } else if (res.data.data) {
            resolve(res.data.data)
          } else {
            console.error('GraphQL响应异常:', res.data)
            reject('请求失败')
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  }
})