|
| 1 | +/** |
| 2 | + * Stripe Webhook Endpoint |
| 3 | + * Handles Stripe webhook events with signature verification and idempotency |
| 4 | + * _需求: 6.4_ |
| 5 | + */ |
| 6 | + |
| 7 | +import { NextRequest, NextResponse } from 'next/server'; |
| 8 | +import { StripeAdapter } from '@/server/payment/stripe-adapter'; |
| 9 | +import { |
| 10 | + processWebhookWithIdempotency, |
| 11 | + extractInvoiceIdFromEvent, |
| 12 | + isPaymentSuccessEvent, |
| 13 | + isPaymentFailedEvent, |
| 14 | +} from '@/server/payment/webhook.service'; |
| 15 | +import { |
| 16 | + handlePaymentSuccess, |
| 17 | + handlePaymentFailure, |
| 18 | +} from '@/server/payment/webhook.handlers'; |
| 19 | +import { PaymentError, PaymentErrorCodes } from '@/server/payment/types'; |
| 20 | + |
| 21 | +/** |
| 22 | + * POST /api/webhooks/stripe |
| 23 | + * Receives and processes Stripe webhook events |
| 24 | + */ |
| 25 | +export async function POST(request: NextRequest) { |
| 26 | + try { |
| 27 | + // Get raw body for signature verification |
| 28 | + const rawBody = await request.text(); |
| 29 | + const signature = request.headers.get('stripe-signature'); |
| 30 | + |
| 31 | + if (!signature) { |
| 32 | + console.error('[Stripe Webhook] Missing stripe-signature header'); |
| 33 | + return NextResponse.json( |
| 34 | + { error: 'Missing signature' }, |
| 35 | + { status: 400 } |
| 36 | + ); |
| 37 | + } |
| 38 | + |
| 39 | + // Get webhook secret from environment |
| 40 | + const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET; |
| 41 | + if (!webhookSecret) { |
| 42 | + console.error('[Stripe Webhook] STRIPE_WEBHOOK_SECRET not configured'); |
| 43 | + return NextResponse.json( |
| 44 | + { error: 'Webhook not configured' }, |
| 45 | + { status: 500 } |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + // Create Stripe adapter for webhook verification |
| 50 | + const stripeAdapter = new StripeAdapter({ |
| 51 | + provider: 'stripe', |
| 52 | + apiKey: process.env.STRIPE_SECRET_KEY || '', |
| 53 | + webhookSecret, |
| 54 | + }); |
| 55 | + |
| 56 | + // Verify webhook signature and parse event |
| 57 | + let event; |
| 58 | + try { |
| 59 | + event = await stripeAdapter.verifyWebhook(rawBody, signature); |
| 60 | + } catch (error) { |
| 61 | + if (error instanceof PaymentError && error.code === PaymentErrorCodes.WEBHOOK_VERIFICATION_FAILED) { |
| 62 | + console.error('[Stripe Webhook] Signature verification failed:', error.message); |
| 63 | + return NextResponse.json( |
| 64 | + { error: 'Invalid signature' }, |
| 65 | + { status: 400 } |
| 66 | + ); |
| 67 | + } |
| 68 | + throw error; |
| 69 | + } |
| 70 | + |
| 71 | + console.log(`[Stripe Webhook] Received event: ${event.type} (${event.id})`); |
| 72 | + |
| 73 | + // Process with idempotency check |
| 74 | + const { alreadyProcessed } = await processWebhookWithIdempotency( |
| 75 | + 'stripe', |
| 76 | + event.id, |
| 77 | + async () => { |
| 78 | + // Extract invoice ID from event metadata |
| 79 | + const invoiceId = extractInvoiceIdFromEvent(event); |
| 80 | + |
| 81 | + if (!invoiceId) { |
| 82 | + console.log(`[Stripe Webhook] Event ${event.id} has no invoiceId in metadata, skipping`); |
| 83 | + return { skipped: true }; |
| 84 | + } |
| 85 | + |
| 86 | + // Handle payment success events |
| 87 | + if (isPaymentSuccessEvent(event.type)) { |
| 88 | + console.log(`[Stripe Webhook] Processing payment success for invoice ${invoiceId}`); |
| 89 | + const result = await handlePaymentSuccess(invoiceId, { |
| 90 | + pspProvider: 'stripe', |
| 91 | + pspPaymentId: event.data.paymentId, |
| 92 | + checkoutSessionId: event.data.checkoutSessionId, |
| 93 | + amount: event.data.amount, |
| 94 | + currency: event.data.currency, |
| 95 | + }); |
| 96 | + return result; |
| 97 | + } |
| 98 | + |
| 99 | + // Handle payment failure events |
| 100 | + if (isPaymentFailedEvent(event.type)) { |
| 101 | + console.log(`[Stripe Webhook] Processing payment failure for invoice ${invoiceId}`); |
| 102 | + const result = await handlePaymentFailure(invoiceId, { |
| 103 | + eventType: event.type, |
| 104 | + pspProvider: 'stripe', |
| 105 | + errorMessage: `Payment ${event.type.replace('_', ' ')}`, |
| 106 | + }); |
| 107 | + return result; |
| 108 | + } |
| 109 | + |
| 110 | + // Unhandled event type |
| 111 | + console.log(`[Stripe Webhook] Unhandled event type: ${event.type}`); |
| 112 | + return { skipped: true, reason: 'unhandled_event_type' }; |
| 113 | + } |
| 114 | + ); |
| 115 | + |
| 116 | + if (alreadyProcessed) { |
| 117 | + console.log(`[Stripe Webhook] Event ${event.id} already processed, skipping`); |
| 118 | + } |
| 119 | + |
| 120 | + // Always return 200 to acknowledge receipt |
| 121 | + return NextResponse.json({ received: true }); |
| 122 | + } catch (error) { |
| 123 | + console.error('[Stripe Webhook] Error processing webhook:', error); |
| 124 | + |
| 125 | + // Return 500 for unexpected errors (Stripe will retry) |
| 126 | + return NextResponse.json( |
| 127 | + { error: 'Internal server error' }, |
| 128 | + { status: 500 } |
| 129 | + ); |
| 130 | + } |
| 131 | +} |
0 commit comments