Branchwell

Lumen & Gesso / website · lumengesso.com / app / api / studio / print / checkout / route.ts

1import { authOrigin } from '@/app/lib/lumen-auth';
2import { commerceDb } from '@/app/lib/commerce-db';
3import { PRODUCTS, sizeLabel } from '@/app/lib/pricing';
4import { stripe } from '@/app/lib/stripe';
5import { StudioError } from '@/app/lib/studio-media';
6import { stageApprovedPrint } from '../persistence';
7import { PRINT_HEADERS, PRINT_SHIPPING_COUNTRY, PRINT_WORKFLOW, printArtwork, printError, readPrintForm, requirePrintCustomer, unavailable, verifyPrintQuote } from '../protocol';
8
9export const runtime = 'nodejs';
10export const dynamic = 'force-dynamic';
11export const maxDuration = 60;
12
13export async function POST(req: Request) {
14 try {
15 const user = await requirePrintCustomer(req);
16 const form = await readPrintForm(req, ['image', 'quoteToken', 'approved', 'termsAccepted']);
17 if (form.get('approved') !== 'true' || form.get('termsAccepted') !== 'true') {
18 throw new StudioError('print_approval_required', 400, 'Approve this final print and accept the print terms before paying.');
19 }
20 const quote = verifyPrintQuote(form.get('quoteToken'), user.id);
21 const artwork = await printArtwork(form.get('image'), quote.selection);
22 if (artwork.sha256 !== quote.artworkSha256 || artwork.mime !== quote.mime) {
23 throw new StudioError('print_changed', 409, 'The artwork changed. Get a new quote and approve the final image again.');
24 }
25 const { orderId, stripeSessionId, approval, selection } = await stageApprovedPrint(quote, artwork, user.email);
26 const stripeClient = stripe();
27 const origin = authOrigin();
28 const metadata = {
29 orderId, workflow: PRINT_WORKFLOW, generationId: approval.generationId,
30 artworkSha256: approval.artworkSha256, configSha256: approval.configSha256,
31 };
32 let session;
33 if (stripeSessionId) {
34 session = await stripeClient.checkout.sessions.retrieve(stripeSessionId);
35 } else {
36 session = await stripeClient.checkout.sessions.create({
37 mode: 'payment',
38 client_reference_id: orderId,
39 payment_method_types: ['card'],
40 line_items: [{
41 price_data: {
42 currency: 'usd', unit_amount: approval.amountCents, tax_behavior: 'exclusive',
43 product_data: {
44 name: PRODUCTS[selection.productId].label,
45 description: sizeLabel(selection.productId, selection.size, selection.orientation),
46 tax_code: 'txcd_99999999',
47 },
48 },
49 quantity: 1,
50 }],
51 customer_email: user.email,
52 shipping_address_collection: { allowed_countries: [PRINT_SHIPPING_COUNTRY] },
53 automatic_tax: { enabled: true },
54 adaptive_pricing: { enabled: false },
55 metadata,
56 payment_intent_data: { metadata },
57 success_url: `${origin}/orders/${orderId}`,
58 cancel_url: `${origin}/studio?print=cancelled`,
59 }, { idempotencyKey: `lumen-print-checkout-v1-${orderId}` });
60 }
61 if (session.client_reference_id !== orderId || session.metadata?.workflow !== PRINT_WORKFLOW
62 || session.metadata.orderId !== orderId || session.metadata.generationId !== approval.generationId
63 || session.metadata.artworkSha256 !== approval.artworkSha256 || session.metadata.configSha256 !== approval.configSha256
64 || session.amount_subtotal !== approval.amountCents || session.currency !== 'usd') throw unavailable();
65 if (session.status !== 'open' || !session.url) {
66 throw new StudioError('print_payment_unavailable', 409, 'This checkout is no longer open. Check your orders before starting another.');
67 }
68 if (new URL(session.url).origin !== 'https://checkout.stripe.com') throw unavailable();
69 if (!stripeSessionId) {
70 const db = commerceDb();
71 // Retrying the Stripe request with the same quote gets the same
72 // Session. Only persist that exact ID on this unchanged order.
73 const saved = await db.from('orders').update({ stripe_session_id: session.id })
74 .eq('id', orderId).eq('user_id', user.id).eq('status', 'pending_payment')
75 .eq('current_generation_id', approval.generationId).select('stripe_session_id').maybeSingle();
76 if (saved.error || saved.data?.stripe_session_id !== session.id) throw unavailable();
77 }
78 return Response.json({ orderId, url: session.url }, { headers: PRINT_HEADERS });
79 } catch (error) { return printError(error); }
80}