Sfoglia il codice sorgente

更新支付相关逻辑,调整支付通知接口为GET请求,修改参数验证方式;优化收入记录查询逻辑,确保返回null而非抛出错误;在支付服务中简化支付通知处理流程,增强错误处理和日志记录。

wuyi 3 mesi fa
parent
commit
f21630ba1d

+ 1 - 0
src/app.ts

@@ -29,6 +29,7 @@ const options: FastifyEnvOptions = {
 export const createApp = async () => {
   const app = fastify({
     disableRequestLogging: true,
+    trustProxy: true,
     logger: {
       level: process.env.NODE_ENV === 'development' ? 'debug' : 'info',
       transport: {

+ 2 - 2
src/controllers/payment.controller.ts

@@ -34,9 +34,9 @@ export class PaymentController {
     }
   }
 
-  async notifyOrder(request: FastifyRequest<{ Body: PaymentNotifyParams }>, reply: FastifyReply) {
+  async notifyOrder(request: FastifyRequest<{ Querystring: PaymentNotifyParams }>, reply: FastifyReply) {
     try {
-      await this.paymentService.handlePaymentNotify(request.body)
+      await this.paymentService.handlePaymentNotify(request.query)
       return reply.send('success')
     } catch (error) {
       return reply.code(500).send('Failed to handle payment notification')

+ 1 - 1
src/routes/payment.routes.ts

@@ -12,7 +12,7 @@ export default async function paymentRoutes(fastify: FastifyInstance) {
   )
 
   // 支付结果通知
-  fastify.post<{ Body: PaymentNotifyParams }>('/notify', paymentController.notifyOrder.bind(paymentController))
+  fastify.get<{ Querystring: PaymentNotifyParams }>('/notify', paymentController.notifyOrder.bind(paymentController))
 
   // 查询订单
   fastify.get('/query', paymentController.queryOrder.bind(paymentController))

+ 6 - 2
src/services/income-records.service.ts

@@ -101,8 +101,12 @@ export class IncomeRecordsService {
     }
   }
 
-  async findByOrderNo(orderNo: string): Promise<IncomeRecords> {
-    return this.incomeRecordsRepository.findOneOrFail({ where: { orderNo } })
+  async findByOrderNo(orderNo: string): Promise<IncomeRecords | null> {
+    const record = await this.incomeRecordsRepository.findOne({ where: { orderNo } })
+    if (!record) {
+      return null
+    }
+    return record
   }
 
   async update(data: UpdateIncomeRecordBody): Promise<IncomeRecords> {

+ 35 - 35
src/services/payment.service.ts

@@ -110,40 +110,39 @@ export class PaymentService {
   }
 
   async handlePaymentNotify(params: PaymentNotifyParams): Promise<void> {
-    try {
-      if (!this.verifyNotifySign(params)) {
-        throw new Error('Verify notify sign failed')
+    if (!this.verifyNotifySign(params)) {
+      throw new Error('Verify notify sign failed')
+    }
+
+    if (params.trade_status === 'TRADE_SUCCESS') {
+      this.app.log.info('Payment success, start processing')
+
+      const incomeRecord = await this.incomeRecordsService.findByOrderNo(params.trade_no)
+      if (!incomeRecord) {
+        throw new Error('Failed to find corresponding income record')
       }
 
-      if (params.trade_status === 'TRADE_SUCCESS') {
-        this.app.log.info('Payment success, out_trade_no: ' + params.out_trade_no)
-
-        try {
-          const incomeRecord = await this.incomeRecordsService.findByOrderNo(params.out_trade_no)
-          if (incomeRecord) {
-            // 更新收入记录状态
-            await this.incomeRecordsService.update({
-              id: incomeRecord.id,
-              status: true
-            })
-            this.app.log.info('Updated income record status success', incomeRecord.id)
-
-            // 更新会员等级
-            await this.memberService.updateVipLevel(
-              incomeRecord.userId,
-              this.getVipLevelByOrderType(incomeRecord.orderType)
-            )
-            this.app.log.info('Updated member level success', incomeRecord.userId)
-          }
-        } catch (error) {
-          this.app.log.error('Failed to process payment success:', error)
-        }
-      } else {
-        this.app.log.warn('Payment failed, out_trade_no: ' + params.out_trade_no + ', trade_no: ' + params.trade_no)
+      await this.incomeRecordsService.update({
+        id: incomeRecord.id,
+        status: true
+      })
+
+      // 更新会员等级
+      const vipLevel = this.getVipLevelByOrderType(incomeRecord.orderType)
+
+      const member = await this.memberService.findByUserId(incomeRecord.userId)
+      if (!member) {
+        throw new Error('Failed to find corresponding member record')
       }
-    } catch (error) {
-      this.app.log.error('Failed to handle payment notification:', error)
-      throw error
+      await this.memberService.updateVipLevel(member.id, vipLevel)
+      this.app.log.info('Member level updated successfully')
+      this.app.log.info('Payment processing completed')
+    } else {
+      this.app.log.warn('支付失败', {
+        out_trade_no: params.out_trade_no,
+        trade_status: params.trade_status
+      })
+      throw new Error('支付失败')
     }
   }
 
@@ -175,15 +174,16 @@ export class PaymentService {
         pid: Number(this.pid),
         type: 'alipay',
         out_trade_no,
-        notify_url: `http://${this.app.config.HOST}:${this.app.config.PORT}/payment/notify`,
-        return_url: `https://www.baidu.com/`,
+        notify_url: `https://9g15.vip/api/payment/notify`,
+        return_url: `https://yz1df.cc/account`,
         name: `${params.type} 订单`,
         money: price,
         client_ip: params.ip
       }
+      console.log('paymentParams:', paymentParams)
 
       const result = await this.createOrder(paymentParams)
-      console.log(result)
+      console.log('result:', result)
 
       // 创建收入记录
       try {
@@ -222,7 +222,7 @@ export class PaymentService {
         })
       } catch (incomeError) {
         this.app.log.error('Failed to create income record:', incomeError)
-        throw new Error('创建记录失败')
+        throw new Error('Failed to create income record')
       }
 
       return {