# All files / modules/payment payment.controller.ts

0% Statements 0/186
0% Branches 0/1
0% Functions 0/1
0% Lines 0/186

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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

     import Router from '@koa/router';
    import { Context } from 'koa';
    import * as PaymentService from './payment.service';
    import { BadRequestError } from '../../middleware/errorHandler';
    import { authMiddleware } from '../../middleware/auth';
    import { prisma } from '../../models';
    import { safeParseInt } from '../../utils/safe-parse';

    const router = new Router();

    // 创建支付订单
    router.post('/create', authMiddleware, async (ctx: Context) => {
      const userId = safeParseInt(ctx.state.user.userId);
      const { planId, paymentMethod, period = 'monthly', returnUrl } = ctx.request.body as {
        planId: number;
        paymentMethod: 'alipay' | 'wechat' | 'mock';
        period?: 'monthly' | 'yearly';
        returnUrl?: string;
      };

      if (!planId) {
        throw new BadRequestError('请选择套餐');
      }

      if (!['alipay', 'wechat', 'mock'].includes(paymentMethod)) {
        throw new BadRequestError('请选择支付方式');
      }

      const result = await PaymentService.createPaymentOrder(userId, planId, paymentMethod, period, returnUrl);

      ctx.body = {
        code: 0,
        message: '订单创建成功',
        data: result
      };
    });

    // 模拟支付（仅开发环境）
    router.post('/mock', authMiddleware, async (ctx: Context) => {
      if (process.env.NODE_ENV === 'production') {
        throw new BadRequestError('生产环境不可用');
      }

      const userId = safeParseInt(ctx.state.user.userId);
      const { orderNo } = ctx.request.body as { orderNo: string };

      if (!orderNo) {
        throw new BadRequestError('订单号不能为空');
      }

      const result = await PaymentService.mockPaymentSuccess(orderNo, userId);

      ctx.body = {
        code: 0,
        message: result.message,
        data: result
      };
    });

    // 支付宝异步通知回调
    router.post('/alipay/notify', async (ctx: Context) => {
      const params = ctx.request.body as Record<string, string>;

      console.log('[Alipay Notify] 收到异步通知:', params);

      // 验证签名
      const signVerified = PaymentService.verifyAlipaySign(params);
      if (!signVerified) {
        console.error('[Alipay Notify] 签名验证失败');
        ctx.status = 400;
        ctx.body = 'fail';
        return;
      }

      const { out_trade_no, trade_status, trade_no } = params;

      try {
        if (trade_status === 'TRADE_SUCCESS' || trade_status === 'TRADE_FINISHED') {
          // 支付成功
          await PaymentService.handlePaymentCallback(out_trade_no, trade_no, 'success');
          console.log('[Alipay Notify] 订单支付成功:', out_trade_no);
          ctx.body = 'success';
        } else if (trade_status === 'WAIT_BUYER_PAY') {
          // 等待买家付款
          console.log('[Alipay Notify] 等待买家付款:', out_trade_no);
          ctx.body = 'success';
        } else {
          // 其他状态视为失败
          await PaymentService.handlePaymentCallback(out_trade_no, trade_no, 'failed');
          console.log('[Alipay Notify] 订单支付失败:', out_trade_no, trade_status);
          ctx.body = 'success';
        }
      } catch (error) {
        console.error('[Alipay Notify] 处理回调失败:', error);
        ctx.status = 500;
        ctx.body = 'fail';
      }
    });

    // 支付宝同步回调（用户从支付宝页面返回）
    router.get('/alipay/return', async (ctx: Context) => {
      const params = ctx.query as Record<string, string>;

      console.log('[Alipay Return] 收到同步返回:', params);

      // 验证签名
      const signVerified = PaymentService.verifyAlipaySign(params);
      if (!signVerified) {
        console.error('[Alipay Return] 签名验证失败');
        // 重定向到支付结果页面（失败）
        const failUrl = `${process.env.ALIPAY_RETURN_URL || '/#/pages/payment-result/index'}?status=failed&error_msg=签名验证失败`;
        ctx.redirect(failUrl);
        return;
      }

      const { out_trade_no, trade_status } = params;

      // 根据支付状态重定向
      if (trade_status === 'TRADE_SUCCESS' || trade_status === 'TRADE_FINISHED') {
        // 支付成功
        const successUrl = `${process.env.ALIPAY_RETURN_URL || '/#/pages/payment-result/index'}?status=success&orderNo=${out_trade_no}&trade_status=${trade_status}`;
        ctx.redirect(successUrl);
      } else {
        // 支付未完成
        const failUrl = `${process.env.ALIPAY_RETURN_URL || '/#/pages/payment-result/index'}?status=failed&orderNo=${out_trade_no}`;
        ctx.redirect(failUrl);
      }
    });

    // 微信支付回调
    router.post('/wechat/notify', async (ctx: Context) => {
      try {
        const body = ctx.request.body as any;
        console.log('[WeChat Notify] 收到回调:', JSON.stringify(body));

        const { out_trade_no, transaction_id, trade_state } = body;

        if (trade_state === 'SUCCESS') {
          await PaymentService.handlePaymentCallback(out_trade_no, transaction_id, 'success');
          console.log('[WeChat Notify] 订单支付成功:', out_trade_no);
        } else {
          await PaymentService.handlePaymentCallback(out_trade_no, transaction_id, 'failed');
          console.log('[WeChat Notify] 订单支付失败:', out_trade_no, trade_state);
        }

        ctx.body = { code: 'SUCCESS', message: '成功' };
      } catch (error) {
        console.error('[WeChat Notify] 处理回调失败:', error);
        ctx.status = 500;
        ctx.body = { code: 'FAIL', message: '处理失败' };
      }
    });

    // 查询微信支付订单状态
    router.get('/wechat/query/:orderNo', authMiddleware, async (ctx: Context) => {
      const { orderNo } = ctx.params;

      const result = await PaymentService.queryWechatOrder(orderNo);

      if (!result) {
        ctx.body = {
          code: -1,
          message: '未配置微信支付或查询失败',
          data: null
        };
        return;
      }

      ctx.body = {
        code: 0,
        message: 'success',
        data: result
      };
    });

    // 获取订单列表
    router.get('/orders', authMiddleware, async (ctx: Context) => {
      const userId = safeParseInt(ctx.state.user.userId);
      const { page = '1', pageSize = '20' } = ctx.query as { page?: string; pageSize?: string };

      const result = await PaymentService.getOrderList(
        userId,
        Number(page) || 1,
        Number(pageSize) || 20
      );

      ctx.body = {
        code: 0,
        message: 'success',
        data: result
      };
    });

    // 获取订单详情
    router.get('/orders/:orderNo', authMiddleware, async (ctx: Context) => {
      const userId = safeParseInt(ctx.state.user.userId);
      const { orderNo } = ctx.params;

      const result = await PaymentService.getOrderDetail(orderNo, userId);

      ctx.body = {
        code: 0,
        message: 'success',
        data: result
      };
    });

    // 生成支付宝扫码支付二维码
    router.post('/alipay/qrcode', authMiddleware, async (ctx: Context) => {
      const userId = parseInt(ctx.state.user.userId);
      const { planId } = ctx.request.body as { planId: number };

      if (!planId) {
        throw new BadRequestError('请选择套餐');
      }

      // 获取套餐信息
      const plan = await prisma.subscriptionPlan.findUnique({
        where: { id: planId }
      });

      if (!plan) {
        throw new BadRequestError('套餐不存在');
      }

      // 生成订单
      const orderNo = PaymentService.generateOrderNo();
      const amount = Number(plan.priceMonthly);

      // 创建订单记录
      await prisma.order.create({
        data: {
          userId,
          orderNo,
          planId,
          productType: 'monthly',
          amount,
          status: 'pending',
          paymentMethod: 'alipay',
        }
      });

      // 生成支付二维码链接
      const qrcodeUrl = await PaymentService.generateAlipayQrcode(orderNo, amount, plan.name);

      ctx.body = {
        code: 0,
        message: 'success',
        data: {
          orderNo,
          amount,
          planName: plan.name,
          qrcode: qrcodeUrl
        }
      };
    });

    export default router;