|
| 1 | +import { NextRequest, NextResponse } from 'next/server'; |
| 2 | +import Decimal from 'decimal.js'; |
| 3 | +import { prisma } from '@/lib/prisma'; |
| 4 | +import { validatePaymentToken } from '@/server/payment/payment-link'; |
| 5 | +import { getPSPCredentials } from '@/server/payment/credentials'; |
| 6 | +import { getPaymentGateway } from '@/server/payment/gateway-factory'; |
| 7 | +import type { Currency } from '@prisma/client'; |
| 8 | + |
| 9 | +/** |
| 10 | + * POST /api/pay/[token]/checkout |
| 11 | + * Creates a Stripe Checkout session and returns the redirect URL |
| 12 | + * _需求: 6.2_ |
| 13 | + */ |
| 14 | +export async function POST( |
| 15 | + request: NextRequest, |
| 16 | + { params }: { params: Promise<{ token: string }> } |
| 17 | +) { |
| 18 | + try { |
| 19 | + const { token } = await params; |
| 20 | + const body = await request.json(); |
| 21 | + const { method } = body; |
| 22 | + |
| 23 | + if (!token) { |
| 24 | + return NextResponse.json( |
| 25 | + { error: 'Invalid payment token' }, |
| 26 | + { status: 400 } |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + if (method !== 'card') { |
| 31 | + return NextResponse.json( |
| 32 | + { error: 'Only card payment is currently supported' }, |
| 33 | + { status: 400 } |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + // Validate the payment token and get invoice |
| 38 | + const result = await validatePaymentToken(token); |
| 39 | + |
| 40 | + if (!result.valid) { |
| 41 | + const errorMessages: Record<string, string> = { |
| 42 | + not_found: 'Invoice not found', |
| 43 | + expired: 'Payment link has expired', |
| 44 | + already_paid: 'Invoice has already been paid', |
| 45 | + cancelled: 'Invoice has been cancelled', |
| 46 | + }; |
| 47 | + return NextResponse.json( |
| 48 | + { error: errorMessages[result.error] || 'Invalid payment link' }, |
| 49 | + { status: 400 } |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + const { invoice } = result; |
| 54 | + |
| 55 | + // Check if card payment is allowed |
| 56 | + if (!invoice.allowCardPayment) { |
| 57 | + return NextResponse.json( |
| 58 | + { error: 'Card payment is not enabled for this invoice' }, |
| 59 | + { status: 400 } |
| 60 | + ); |
| 61 | + } |
| 62 | + |
| 63 | + // Get the invoice owner's user ID to fetch PSP credentials |
| 64 | + const invoiceRecord = await prisma.invoice.findFirst({ |
| 65 | + where: { paymentToken: token }, |
| 66 | + select: { userId: true }, |
| 67 | + }); |
| 68 | + |
| 69 | + if (!invoiceRecord) { |
| 70 | + return NextResponse.json( |
| 71 | + { error: 'Invoice not found' }, |
| 72 | + { status: 404 } |
| 73 | + ); |
| 74 | + } |
| 75 | + |
| 76 | + // Get PSP credentials for the invoice owner |
| 77 | + const credentials = await getPSPCredentials(invoiceRecord.userId); |
| 78 | + |
| 79 | + if (!credentials) { |
| 80 | + return NextResponse.json( |
| 81 | + { error: 'Payment is not configured for this merchant' }, |
| 82 | + { status: 400 } |
| 83 | + ); |
| 84 | + } |
| 85 | + |
| 86 | + // Create payment gateway |
| 87 | + const gateway = getPaymentGateway(credentials); |
| 88 | + |
| 89 | + // Build success and cancel URLs |
| 90 | + const baseUrl = process.env.NEXT_PUBLIC_APP_URL || request.nextUrl.origin; |
| 91 | + const successUrl = `${baseUrl}/pay/${token}/success`; |
| 92 | + const cancelUrl = `${baseUrl}/pay/${token}`; |
| 93 | + |
| 94 | + // Create checkout session |
| 95 | + const session = await gateway.createCheckoutSession({ |
| 96 | + invoiceId: invoice.id, |
| 97 | + amount: new Decimal(invoice.total), |
| 98 | + currency: invoice.currency as Currency, |
| 99 | + customerEmail: invoice.client.email, |
| 100 | + successUrl, |
| 101 | + cancelUrl, |
| 102 | + metadata: { |
| 103 | + invoiceId: invoice.id, |
| 104 | + invoiceNumber: invoice.invoiceNumber, |
| 105 | + paymentToken: token, |
| 106 | + }, |
| 107 | + }); |
| 108 | + |
| 109 | + // Store the checkout session ID for later verification |
| 110 | + await prisma.payment.upsert({ |
| 111 | + where: { invoiceId: invoice.id }, |
| 112 | + create: { |
| 113 | + invoiceId: invoice.id, |
| 114 | + type: 'fiat', |
| 115 | + amount: invoice.total, |
| 116 | + currency: invoice.currency as Currency, |
| 117 | + status: 'pending', |
| 118 | + metadata: { checkoutSessionId: session.id }, |
| 119 | + fiatPayment: { |
| 120 | + create: { |
| 121 | + pspProvider: credentials.provider, |
| 122 | + checkoutSessionId: session.id, |
| 123 | + }, |
| 124 | + }, |
| 125 | + }, |
| 126 | + update: { |
| 127 | + status: 'pending', |
| 128 | + metadata: { checkoutSessionId: session.id }, |
| 129 | + fiatPayment: { |
| 130 | + upsert: { |
| 131 | + create: { |
| 132 | + pspProvider: credentials.provider, |
| 133 | + checkoutSessionId: session.id, |
| 134 | + }, |
| 135 | + update: { |
| 136 | + checkoutSessionId: session.id, |
| 137 | + }, |
| 138 | + }, |
| 139 | + }, |
| 140 | + }, |
| 141 | + }); |
| 142 | + |
| 143 | + return NextResponse.json({ url: session.url }); |
| 144 | + } catch (error) { |
| 145 | + console.error('Checkout error:', error); |
| 146 | + return NextResponse.json( |
| 147 | + { error: 'Failed to create checkout session' }, |
| 148 | + { status: 500 } |
| 149 | + ); |
| 150 | + } |
| 151 | +} |
0 commit comments