64 lines
2.6 KiB
TypeScript
64 lines
2.6 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import Stripe from 'stripe';
|
|
import { prisma } from '@/lib/prisma';
|
|
|
|
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
apiVersion: '2026-03-25.dahlia' as any,
|
|
});
|
|
|
|
export async function POST(request: Request) {
|
|
let body: Record<string, unknown>;
|
|
try {
|
|
body = await request.json();
|
|
} catch {
|
|
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
|
|
}
|
|
|
|
const { paymentIntentId } = body;
|
|
if (!paymentIntentId || typeof paymentIntentId !== 'string') {
|
|
return NextResponse.json({ error: 'Missing paymentIntentId' }, { status: 400 });
|
|
}
|
|
|
|
// Try to get authoritative data from Stripe, but don't block save if it fails
|
|
let stripeAmount: number | null = null;
|
|
let stripeCurrency: string | null = null;
|
|
let stripeStatus: string | null = null;
|
|
let stripeMetadata: Record<string, string> = {};
|
|
|
|
try {
|
|
const pi = await stripe.paymentIntents.retrieve(paymentIntentId);
|
|
stripeAmount = pi.amount;
|
|
stripeCurrency = pi.currency;
|
|
stripeStatus = pi.status;
|
|
stripeMetadata = (pi.metadata ?? {}) as Record<string, string>;
|
|
} catch {
|
|
// Stripe unreachable — save with client-submitted data
|
|
}
|
|
|
|
const m = stripeMetadata;
|
|
const data = {
|
|
amount: stripeAmount ?? (typeof body.amount === 'number' ? body.amount : 0),
|
|
currency: stripeCurrency ?? (typeof body.currency === 'string' ? body.currency : 'aed'),
|
|
status: stripeStatus ?? (typeof body.status === 'string' ? body.status : 'pending'),
|
|
customerName: (body.customerName as string | null) ?? m.customerName ?? null,
|
|
customerEmail: (body.customerEmail as string | null) ?? m.customerEmail ?? null,
|
|
customerPhone: (body.customerPhone as string | null) ?? m.customerPhone ?? null,
|
|
customerAddress: (body.customerAddress as string | null) ?? m.customerAddress ?? null,
|
|
customerCity: (body.customerCity as string | null) ?? m.customerCity ?? null,
|
|
customerCountry: (body.customerCountry as string | null) ?? m.customerCountry ?? null,
|
|
customerPostalCode: (body.customerPostalCode as string | null) ?? m.customerPostalCode ?? null,
|
|
persona: (body.persona as string | null) ?? m.persona ?? null,
|
|
color: (body.color as string | null) ?? m.color ?? null,
|
|
priceItems: (body.priceItems as string | null) ?? m.priceItems ?? null,
|
|
};
|
|
|
|
await prisma.order.upsert({
|
|
where: { paymentIntentId },
|
|
create: { paymentIntentId, ...data },
|
|
update: data,
|
|
});
|
|
|
|
return NextResponse.json({ saved: true });
|
|
}
|