|
| 1 | +/** |
| 2 | + * PayPal order-capture return route. |
| 3 | + * |
| 4 | + * Orders v2 does NOT auto-capture: after the buyer approves on PayPal, they are |
| 5 | + * redirected here (`?token=<orderId>&next=<final success URL>`) and we capture |
| 6 | + * the approved order server-side, dispatch `payment.succeeded` through the |
| 7 | + * shared billing dispatcher (flips the pending transaction → `enroll_user`), |
| 8 | + * and redirect on to the checkout success page. |
| 9 | + * |
| 10 | + * Security notes: |
| 11 | + * - No session requirement: like a webhook, authority comes from the capture |
| 12 | + * API call itself (only an approved order capturable with OUR credentials |
| 13 | + * succeeds) plus the owner-binding custom_id metadata enforced by |
| 14 | + * dispatchBillingEvent — never from the redirect query string. |
| 15 | + * - `next` is only followed when it targets this request's own origin |
| 16 | + * (open-redirect guard); anything else falls back to /checkout/success. |
| 17 | + * - Refresh/replay safe: an already-captured order (ORDER_ALREADY_CAPTURED) is |
| 18 | + * re-read via getOrder and re-dispatched — the dispatcher's pending-status |
| 19 | + * guard makes that a no-op. The PAYMENT.CAPTURE.COMPLETED webhook backstops a |
| 20 | + * capture made here whose dispatch failed; an order the buyer abandons after |
| 21 | + * approval is never captured and simply expires at PayPal. |
| 22 | + */ |
| 23 | + |
| 24 | +import { NextRequest, NextResponse } from 'next/server' |
| 25 | +import { createClient } from '@supabase/supabase-js' |
| 26 | +import { getPaymentProvider } from '@/lib/payments' |
| 27 | +import { PayPalPaymentProvider } from '@/lib/payments/paypal-provider' |
| 28 | +import { dispatchBillingEvent } from '@/lib/payments/webhook-dispatch' |
| 29 | + |
| 30 | +export const runtime = 'nodejs' |
| 31 | + |
| 32 | +function getSupabaseAdmin() { |
| 33 | + const url = process.env.NEXT_PUBLIC_SUPABASE_URL |
| 34 | + const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY |
| 35 | + if (!url || !serviceKey) { |
| 36 | + throw new Error('Supabase environment variables not set') |
| 37 | + } |
| 38 | + return createClient(url, serviceKey) |
| 39 | +} |
| 40 | + |
| 41 | +/** Resolve this request's own origin (tenant subdomain aware, like checkout). */ |
| 42 | +function requestOrigin(req: NextRequest): string { |
| 43 | + const forwardedHost = req.headers.get('x-forwarded-host') |
| 44 | + return process.env.NODE_ENV === 'development' |
| 45 | + ? req.nextUrl.origin |
| 46 | + : forwardedHost |
| 47 | + ? `https://${forwardedHost}` |
| 48 | + : req.nextUrl.origin |
| 49 | +} |
| 50 | + |
| 51 | +/** Follow `next` only when it points back at our own origin. */ |
| 52 | +function safeRedirectTarget(next: string | null, origin: string, fallback: string): string { |
| 53 | + if (!next) return fallback |
| 54 | + try { |
| 55 | + const url = new URL(next, origin) |
| 56 | + if (url.origin === origin) return url.toString() |
| 57 | + } catch { |
| 58 | + // fall through to fallback |
| 59 | + } |
| 60 | + return fallback |
| 61 | +} |
| 62 | + |
| 63 | +export async function GET(req: NextRequest) { |
| 64 | + const orderId = req.nextUrl.searchParams.get('token') // PayPal appends ?token=<orderId> |
| 65 | + const next = req.nextUrl.searchParams.get('next') |
| 66 | + const origin = requestOrigin(req) |
| 67 | + const fallback = `${origin}/checkout/success` |
| 68 | + |
| 69 | + if (!orderId) { |
| 70 | + return NextResponse.redirect(safeRedirectTarget(next, origin, fallback)) |
| 71 | + } |
| 72 | + |
| 73 | + let provider: PayPalPaymentProvider |
| 74 | + try { |
| 75 | + provider = getPaymentProvider('paypal') as PayPalPaymentProvider |
| 76 | + } catch (err) { |
| 77 | + console.error('[paypal/capture] provider not configured:', err) |
| 78 | + return NextResponse.redirect(safeRedirectTarget(next, origin, fallback)) |
| 79 | + } |
| 80 | + |
| 81 | + let captureId: string | undefined |
| 82 | + let reference: string | undefined |
| 83 | + let metadata: Record<string, string> | undefined |
| 84 | + |
| 85 | + try { |
| 86 | + const captured = await provider.captureOrder(orderId) |
| 87 | + captureId = captured.captureId |
| 88 | + reference = captured.reference |
| 89 | + metadata = captured.metadata |
| 90 | + } catch (err) { |
| 91 | + const message = err instanceof Error ? err.message : String(err) |
| 92 | + if (message.includes('ORDER_ALREADY_CAPTURED')) { |
| 93 | + // Refresh / duplicate return: read the existing capture and fall through |
| 94 | + // to the (idempotent) dispatch below. |
| 95 | + try { |
| 96 | + const order = await provider.getOrder(orderId) |
| 97 | + captureId = order.captureId |
| 98 | + reference = order.reference |
| 99 | + metadata = order.metadata |
| 100 | + } catch (readErr) { |
| 101 | + console.error('[paypal/capture] failed to read already-captured order:', readErr) |
| 102 | + } |
| 103 | + } else { |
| 104 | + console.error('[paypal/capture] capture failed:', err) |
| 105 | + const target = new URL(safeRedirectTarget(next, origin, fallback)) |
| 106 | + target.searchParams.set('paypal', 'capture_failed') |
| 107 | + return NextResponse.redirect(target) |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + if (captureId && reference) { |
| 112 | + try { |
| 113 | + await dispatchBillingEvent( |
| 114 | + { |
| 115 | + type: 'payment.succeeded', |
| 116 | + providerEventId: `paypal-capture:${captureId}`, |
| 117 | + providerPaymentId: captureId, |
| 118 | + reference, |
| 119 | + metadata, |
| 120 | + raw: { source: 'paypal-capture-route', orderId, captureId }, |
| 121 | + }, |
| 122 | + { provider: 'paypal', admin: getSupabaseAdmin() }, |
| 123 | + ) |
| 124 | + } catch (err) { |
| 125 | + // Payment IS captured — never strand the buyer on an error page for a |
| 126 | + // dispatch hiccup; the PAYMENT.CAPTURE.COMPLETED webhook retries the flip. |
| 127 | + console.error('[paypal/capture] dispatch failed (webhook will retry):', err) |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + return NextResponse.redirect(safeRedirectTarget(next, origin, fallback)) |
| 132 | +} |
0 commit comments