import { authOrigin } from '@/app/lib/lumen-auth'; import { commerceDb } from '@/app/lib/commerce-db'; import { PRODUCTS, sizeLabel } from '@/app/lib/pricing'; import { stripe } from '@/app/lib/stripe'; import { StudioError } from '@/app/lib/studio-media'; import { stageApprovedPrint } from '../persistence'; import { PRINT_HEADERS, PRINT_SHIPPING_COUNTRY, PRINT_WORKFLOW, printArtwork, printError, readPrintForm, requirePrintCustomer, unavailable, verifyPrintQuote } from '../protocol'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export const maxDuration = 60; export async function POST(req: Request) { try { const user = await requirePrintCustomer(req); const form = await readPrintForm(req, ['image', 'quoteToken', 'approved', 'termsAccepted']); if (form.get('approved') !== 'true' || form.get('termsAccepted') !== 'true') { throw new StudioError('print_approval_required', 400, 'Approve this final print and accept the print terms before paying.'); } const quote = verifyPrintQuote(form.get('quoteToken'), user.id); const artwork = await printArtwork(form.get('image'), quote.selection); if (artwork.sha256 !== quote.artworkSha256 || artwork.mime !== quote.mime) { throw new StudioError('print_changed', 409, 'The artwork changed. Get a new quote and approve the final image again.'); } const { orderId, stripeSessionId, approval, selection } = await stageApprovedPrint(quote, artwork, user.email); const stripeClient = stripe(); const origin = authOrigin(); const metadata = { orderId, workflow: PRINT_WORKFLOW, generationId: approval.generationId, artworkSha256: approval.artworkSha256, configSha256: approval.configSha256, }; let session; if (stripeSessionId) { session = await stripeClient.checkout.sessions.retrieve(stripeSessionId); } else { session = await stripeClient.checkout.sessions.create({ mode: 'payment', client_reference_id: orderId, payment_method_types: ['card'], line_items: [{ price_data: { currency: 'usd', unit_amount: approval.amountCents, tax_behavior: 'exclusive', product_data: { name: PRODUCTS[selection.productId].label, description: sizeLabel(selection.productId, selection.size, selection.orientation), tax_code: 'txcd_99999999', }, }, quantity: 1, }], customer_email: user.email, shipping_address_collection: { allowed_countries: [PRINT_SHIPPING_COUNTRY] }, automatic_tax: { enabled: true }, adaptive_pricing: { enabled: false }, metadata, payment_intent_data: { metadata }, success_url: `${origin}/orders/${orderId}`, cancel_url: `${origin}/studio?print=cancelled`, }, { idempotencyKey: `lumen-print-checkout-v1-${orderId}` }); } if (session.client_reference_id !== orderId || session.metadata?.workflow !== PRINT_WORKFLOW || session.metadata.orderId !== orderId || session.metadata.generationId !== approval.generationId || session.metadata.artworkSha256 !== approval.artworkSha256 || session.metadata.configSha256 !== approval.configSha256 || session.amount_subtotal !== approval.amountCents || session.currency !== 'usd') throw unavailable(); if (session.status !== 'open' || !session.url) { throw new StudioError('print_payment_unavailable', 409, 'This checkout is no longer open. Check your orders before starting another.'); } if (new URL(session.url).origin !== 'https://checkout.stripe.com') throw unavailable(); if (!stripeSessionId) { const db = commerceDb(); // Retrying the Stripe request with the same quote gets the same // Session. Only persist that exact ID on this unchanged order. const saved = await db.from('orders').update({ stripe_session_id: session.id }) .eq('id', orderId).eq('user_id', user.id).eq('status', 'pending_payment') .eq('current_generation_id', approval.generationId).select('stripe_session_id').maybeSingle(); if (saved.error || saved.data?.stripe_session_id !== session.id) throw unavailable(); } return Response.json({ orderId, url: session.url }, { headers: PRINT_HEADERS }); } catch (error) { return printError(error); } }