Add booking checkout and webhook flow

This commit is contained in:
2026-05-24 23:55:43 +00:00
parent dbdca5c023
commit 090741e6ad
10 changed files with 879 additions and 24 deletions

View File

@@ -0,0 +1,14 @@
import { NextResponse } from 'next/server';
import { simulateCompletedPayment } from '@/lib/payments';
type RouteParams = {
params: Promise<{
bookingId: string;
}>;
};
export async function POST(request: Request, { params }: RouteParams) {
const { bookingId } = await params;
await simulateCompletedPayment(bookingId);
return NextResponse.redirect(new URL(`/bookings/${bookingId}?checkout=success&source=dev`, request.url), 303);
}

View File

@@ -0,0 +1,29 @@
import { NextResponse } from 'next/server';
import { createBookingCheckout } from '@/lib/payments';
export async function POST(request: Request) {
const body = (await request.json()) as Record<string, unknown>;
try {
const result = await createBookingCheckout({
propertySlug: String(body.propertySlug || ''),
arrivalDate: body.arrivalDate ? String(body.arrivalDate) : undefined,
departureDate: body.departureDate ? String(body.departureDate) : undefined,
adults: Number(body.adults ?? 2),
children: Number(body.children ?? 0),
pets: Number(body.pets ?? 0),
location: body.location ? String(body.location) : undefined,
firstName: String(body.firstName || ''),
lastName: String(body.lastName || ''),
email: String(body.email || ''),
phone: body.phone ? String(body.phone) : undefined,
specialRequests: body.specialRequests ? String(body.specialRequests) : undefined,
termsAccepted: Boolean(body.termsAccepted),
});
return NextResponse.json({ ok: true, ...result });
} catch (error) {
const message = error instanceof Error ? error.message : 'Checkout failed';
return NextResponse.json({ ok: false, error: message }, { status: 400 });
}
}

View File

@@ -0,0 +1,14 @@
import { NextResponse } from 'next/server';
import { handleStripeWebhookBody } from '@/lib/payments';
export async function POST(request: Request) {
try {
const rawBody = await request.text();
const signature = request.headers.get('stripe-signature');
const result = await handleStripeWebhookBody(rawBody, signature);
return NextResponse.json({ ok: true, ...result });
} catch (error) {
const message = error instanceof Error ? error.message : 'Webhook failed';
return NextResponse.json({ ok: false, error: message }, { status: 400 });
}
}

View File

@@ -0,0 +1,108 @@
import type { Metadata } from 'next';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { Section } from '@/components/Section';
import { formatPoundsFromCents } from '@/lib/booking';
import { getBookingCheckoutContext } from '@/lib/payments';
import { site } from '@/lib/site';
type CheckoutPageProps = {
params: Promise<{
bookingId: string;
}>;
};
export async function generateMetadata({ params }: { params: Promise<{ bookingId: string }> }): Promise<Metadata> {
const { bookingId } = await params;
return {
title: `Checkout ${bookingId} | ${site.name}`,
description: 'Checkout handoff page for the booking flow.',
};
}
export default async function BookingCheckoutPage({ params }: CheckoutPageProps) {
const { bookingId } = await params;
const booking = await getBookingCheckoutContext(bookingId);
if (!booking) {
notFound();
}
return (
<>
<section className="page-hero">
<p className="brand-kicker">Checkout</p>
<h2>Finish payment for {booking.property.title}</h2>
<p>
Review the quote, then continue to Stripe if the session is configured or use the local simulation path in
development.
</p>
</section>
<div className="page-layout">
<Section
eyebrow="Quote"
title="Booking summary"
description="This page is the last step before the Stripe session or the local dev fallback."
>
<div className="admin-summary-grid">
<article className="admin-card">
<p className="footer-label">Stay</p>
<h3>{booking.property.title}</h3>
<p className="mb-0">
{booking.arrivalDate.toISOString().slice(0, 10)} to {booking.departureDate.toISOString().slice(0, 10)}
</p>
</article>
<article className="admin-card">
<p className="footer-label">Total</p>
<h3>{formatPoundsFromCents(booking.totalCents)}</h3>
<p className="mb-0">Current payment state: {booking.payment?.status ?? 'REQUIRES_PAYMENT'}</p>
</article>
</div>
<article className="content-card" style={{ marginTop: '1rem' }}>
<h3>What happens next</h3>
<ul>
<li>Stripe Checkout collects payment when keys are configured.</li>
<li>The webhook finalises the payment and booking state.</li>
<li>Email notifications are composed from the payment outcome.</li>
</ul>
</article>
<article className="content-card" style={{ marginTop: '1rem' }}>
<h3>Development fallback</h3>
<p>
If Stripe is not configured in this environment, open the booking status page and use the simulation
button to trigger the same webhook finalisation path.
</p>
<Link className="btn btn-dark" href={`/bookings/${booking.id}`}>
Open booking status
</Link>
</article>
</Section>
<aside className="content-sidebar">
<article className="content-card">
<p className="footer-label">Guest</p>
<p className="mb-0">
{booking.firstName} {booking.lastName}
<br />
{booking.email}
</p>
</article>
<article className="content-card">
<h3>Navigation</h3>
<ul className="link-list">
<li>
<Link href="/">Back to home</Link>
</li>
<li>
<Link href="/admin">Open admin console</Link>
</li>
</ul>
</article>
</aside>
</div>
</>
);
}

View File

@@ -0,0 +1,125 @@
import type { Metadata } from 'next';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { Section } from '@/components/Section';
import { formatPoundsFromCents } from '@/lib/booking';
import { getBookingCheckoutContext } from '@/lib/payments';
import { site } from '@/lib/site';
type BookingPageProps = {
params: Promise<{
bookingId: string;
}>;
searchParams: Promise<{
checkout?: string;
session_id?: string;
source?: string;
}>;
};
export async function generateMetadata({ params }: { params: Promise<{ bookingId: string }> }): Promise<Metadata> {
const { bookingId } = await params;
return {
title: `Booking ${bookingId} | ${site.name}`,
description: 'Booking confirmation and payment status page.',
};
}
export default async function BookingPage({ params, searchParams }: BookingPageProps) {
const { bookingId } = await params;
const query = await searchParams;
const booking = await getBookingCheckoutContext(bookingId);
if (!booking) {
notFound();
}
const paymentStatus = booking.payment?.status ?? 'REQUIRES_PAYMENT';
return (
<>
<section className="page-hero">
<p className="brand-kicker">Booking status</p>
<h2>{booking.property.title}</h2>
<p>
{booking.firstName} {booking.lastName} {booking.arrivalDate.toISOString().slice(0, 10)} to{' '}
{booking.departureDate.toISOString().slice(0, 10)}
</p>
</section>
<div className="page-layout">
<Section
eyebrow="Truth source"
title="Booking and payment state are tracked separately"
description="The browser return page is informational only. The payment record and booking record tell the real story."
>
<div className="admin-summary-grid">
<article className="admin-card">
<p className="footer-label">Booking status</p>
<h3>{booking.status}</h3>
<p className="mb-0">Hold expires at {booking.holdExpiresAt?.toISOString() ?? 'not set'}</p>
</article>
<article className="admin-card">
<p className="footer-label">Payment status</p>
<h3>{paymentStatus}</h3>
<p className="mb-0">Total {formatPoundsFromCents(booking.totalCents)}</p>
</article>
</div>
{query.checkout === 'success' ? (
<article className="content-card" style={{ marginTop: '1rem' }}>
<h3>Return from checkout</h3>
<p className="mb-0">
The checkout return says success, but the booking is only final once the payment record shows a completed webhook event.
</p>
</article>
) : null}
{booking.payment?.status !== 'COMPLETED' ? (
<article className="content-card" style={{ marginTop: '1rem' }}>
<h3>Development fallback</h3>
<p>
If Stripe checkout is not configured in this environment, use the local simulation button to finish
the booking and trigger the notification path.
</p>
<form action={`/api/bookings/${booking.id}/simulate-success`} method="post">
<button className="btn btn-dark" type="submit">
Simulate successful payment
</button>
</form>
</article>
) : (
<article className="content-card" style={{ marginTop: '1rem' }}>
<h3>Payment verified</h3>
<p className="mb-0">
The webhook has confirmed payment and the booking is now safe to display as confirmed.
</p>
</article>
)}
</Section>
<aside className="content-sidebar">
<article className="content-card">
<p className="footer-label">Guest details</p>
<p className="mb-0">
{booking.email}
<br />
{booking.phone || 'No phone provided'}
</p>
</article>
<article className="content-card">
<h3>Actions</h3>
<ul className="link-list">
<li>
<Link href="/">Back to home</Link>
</li>
<li>
<Link href="/admin">Open admin console</Link>
</li>
</ul>
</article>
</aside>
</div>
</>
);
}

View File

@@ -0,0 +1,143 @@
import type { Metadata } from 'next';
import { redirect } from 'next/navigation';
import { Section } from '@/components/Section';
import { bookingCatalog } from '@/lib/booking';
import { createBookingCheckout } from '@/lib/payments';
import { site } from '@/lib/site';
export const metadata: Metadata = {
title: `Book a stay | ${site.name}`,
description: 'Start a holiday property booking, check the live quote core, and continue to checkout.',
};
async function startBooking(formData: FormData) {
'use server';
const result = await createBookingCheckout({
propertySlug: String(formData.get('propertySlug') || ''),
arrivalDate: String(formData.get('arrivalDate') || ''),
departureDate: String(formData.get('departureDate') || ''),
adults: Number(formData.get('adults') || 2),
children: Number(formData.get('children') || 0),
pets: Number(formData.get('pets') || 0),
location: undefined,
firstName: String(formData.get('firstName') || ''),
lastName: String(formData.get('lastName') || ''),
email: String(formData.get('email') || ''),
phone: String(formData.get('phone') || ''),
specialRequests: String(formData.get('specialRequests') || ''),
termsAccepted: formData.get('termsAccepted') === 'on',
});
redirect(result.checkoutUrl);
}
export default function NewBookingPage() {
return (
<>
<section className="page-hero">
<p className="brand-kicker">Booking</p>
<h2>Check availability and start the booking flow</h2>
<p>
This form uses the shared availability and pricing core, creates a booking record before payment, and
hands off to Stripe Checkout or the local dev fallback.
</p>
</section>
<div className="page-layout">
<Section
eyebrow="Booking form"
title="Create a booking hold"
description="Enter the stay details and guest information needed before checkout."
>
<form className="contact-form" action={startBooking}>
<label>
<span>Property</span>
<select name="propertySlug" defaultValue={bookingCatalog[0]?.slug}>
{bookingCatalog.map((property) => (
<option key={property.slug} value={property.slug}>
{property.name}
</option>
))}
</select>
</label>
<div className="metric-grid">
<label>
<span>Arrival</span>
<input type="date" name="arrivalDate" required />
</label>
<label>
<span>Departure</span>
<input type="date" name="departureDate" required />
</label>
</div>
<div className="metric-grid">
<label>
<span>Adults</span>
<input type="number" name="adults" min={1} defaultValue={2} />
</label>
<label>
<span>Children</span>
<input type="number" name="children" min={0} defaultValue={0} />
</label>
</div>
<div className="metric-grid">
<label>
<span>Pets</span>
<input type="number" name="pets" min={0} defaultValue={0} />
</label>
<label>
<span>Phone</span>
<input type="tel" name="phone" placeholder="Optional phone number" />
</label>
</div>
<div className="metric-grid">
<label>
<span>First name</span>
<input type="text" name="firstName" required />
</label>
<label>
<span>Last name</span>
<input type="text" name="lastName" required />
</label>
</div>
<label>
<span>Email</span>
<input type="email" name="email" required />
</label>
<label className="contact-form-message">
<span>Special requests</span>
<textarea name="specialRequests" rows={5} placeholder="Arrival notes, accessibility requests, or questions." />
</label>
<label style={{ display: 'flex', gap: '0.6rem', alignItems: 'center' }}>
<input type="checkbox" name="termsAccepted" required />
<span>I accept the terms and understand the booking hold starts before checkout.</span>
</label>
<button className="btn btn-dark" type="submit">
Continue to checkout
</button>
</form>
</Section>
<aside className="content-sidebar">
<article className="content-card">
<p className="footer-label">Flow</p>
<ul className="admin-bullet-list">
<li>Availability is checked before payment starts.</li>
<li>The booking record is created first.</li>
<li>Stripe Checkout finalises payment truth.</li>
<li>The webhook is the source of truth for confirmation.</li>
</ul>
</article>
<article className="content-card">
<h3>What happens next</h3>
<p className="mb-0">
If Stripe is configured, you will be redirected there. Otherwise the booking status page opens with a
local simulation path for development.
</p>
</article>
</aside>
</div>
</>
);
}

View File

@@ -70,9 +70,9 @@ export default function HomePage() {
<input aria-label={field.label} defaultValue={field.value} />
</label>
))}
<button className="btn btn-dark" type="button">
<Link className="btn btn-dark" href="/bookings/new">
Check availability
</button>
</Link>
</form>
<div className="quote-panel" aria-label="Booking quote preview">

412
src/lib/payments.ts Normal file
View File

@@ -0,0 +1,412 @@
import Stripe from 'stripe';
import { BookingStatus, PaymentStatus } from '@prisma/client';
import { prisma } from '@/lib/prisma';
import {
bookingCatalog,
formatPoundsFromCents,
quoteStay,
type BookingQuote,
type BookingSearchInput,
} from '@/lib/booking';
export type BookingCheckoutInput = BookingSearchInput & {
firstName: string;
lastName: string;
email: string;
phone?: string;
specialRequests?: string;
termsAccepted: boolean;
};
export type BookingCheckoutResult = {
bookingId: string;
paymentId: string;
checkoutUrl: string;
checkoutMode: 'stripe' | 'mock';
quote: BookingQuote;
};
type PaymentEventResult = {
bookingId: string;
paymentId: string;
status: BookingStatus;
notification: NotificationTemplate | null;
};
export type NotificationTemplate = {
subject: string;
preview: string;
lines: string[];
};
const stripeKey = process.env.STRIPE_SECRET_KEY?.trim();
const stripeWebhookSecret = process.env.STRIPE_WEBHOOK_SECRET?.trim();
const stripeClient = stripeKey ? new Stripe(stripeKey) : null;
function getSiteUrl() {
return (process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000').replace(/\/$/, '');
}
function findProperty(propertySlug: string) {
return bookingCatalog.find((property) => property.slug === propertySlug);
}
async function ensureDbProperty(propertySlug: string) {
const property = findProperty(propertySlug);
if (!property) {
throw new Error('Unknown property');
}
return prisma.property.upsert({
where: { slug: property.slug },
create: {
slug: property.slug,
title: property.name,
summary: property.summary,
longDescription: property.summary,
locationText: property.area,
sleeps: property.sleeps,
bedrooms: property.bedrooms,
bathrooms: property.bathrooms,
petsAllowed: property.petsAllowed,
published: true,
featured: false,
minStayNights: property.minStayNights,
},
update: {
title: property.name,
summary: property.summary,
longDescription: property.summary,
locationText: property.area,
sleeps: property.sleeps,
bedrooms: property.bedrooms,
bathrooms: property.bathrooms,
petsAllowed: property.petsAllowed,
published: true,
minStayNights: property.minStayNights,
},
});
}
function normalizeRequiredString(value: unknown, field: string) {
if (typeof value !== 'string') {
throw new Error(`${field} is required`);
}
const trimmed = value.trim();
if (!trimmed) {
throw new Error(`${field} is required`);
}
return trimmed;
}
function normalizeBoolean(value: unknown, field: string) {
if (typeof value !== 'boolean') {
throw new Error(`${field} is required`);
}
return value;
}
function normalizeNumber(value: unknown, field: string) {
const parsed = typeof value === 'string' ? Number(value) : Number(value);
if (!Number.isFinite(parsed)) {
throw new Error(`${field} must be a number`);
}
return parsed;
}
function getBookingHoldMinutes() {
const parsed = Number(process.env.BOOKING_HOLD_MINUTES || '30');
return Number.isFinite(parsed) && parsed > 0 ? parsed : 30;
}
function getCheckoutUrls(bookingId: string) {
const baseUrl = getSiteUrl();
return {
successUrl: `${baseUrl}/bookings/${bookingId}?checkout=success&session_id={CHECKOUT_SESSION_ID}`,
cancelUrl: `${baseUrl}/bookings/${bookingId}?checkout=cancelled`,
fallbackUrl: `${baseUrl}/bookings/${bookingId}/checkout`,
};
}
async function buildNotificationForBooking(bookingId: string, success: boolean): Promise<NotificationTemplate | null> {
const booking = await prisma.booking.findUnique({
where: { id: bookingId },
include: { property: true, payment: true },
});
if (!booking) return null;
if (success) {
return {
subject: `Booking confirmed: ${booking.property.title}`,
preview: `${booking.firstName} ${booking.lastName} is now confirmed for ${formatPoundsFromCents(booking.totalCents)}.`,
lines: [
`${booking.property.title} is confirmed.`,
`Guest: ${booking.firstName} ${booking.lastName} <${booking.email}>`,
`Dates: ${booking.arrivalDate.toISOString().slice(0, 10)} to ${booking.departureDate.toISOString().slice(0, 10)}`,
`Total: ${formatPoundsFromCents(booking.totalCents)}`,
`Payment status: ${booking.payment?.status ?? 'unknown'}`,
],
};
}
return {
subject: `Payment issue for ${booking.property.title}`,
preview: `The booking for ${booking.firstName} ${booking.lastName} did not complete payment.`,
lines: [
`Booking: ${booking.property.title}`,
`Guest: ${booking.firstName} ${booking.lastName} <${booking.email}>`,
`Dates: ${booking.arrivalDate.toISOString().slice(0, 10)} to ${booking.departureDate.toISOString().slice(0, 10)}`,
`Current booking state: ${booking.status}`,
`Current payment state: ${booking.payment?.status ?? 'unknown'}`,
],
};
}
async function recordNotification(bookingId: string, success: boolean) {
const notification = await buildNotificationForBooking(bookingId, success);
if (!notification) return null;
console.info('[booking-notification]', JSON.stringify(notification, null, 2));
return notification;
}
async function createStripeSession(bookingId: string, amountCents: number, email: string) {
if (!stripeClient) return null;
const urls = getCheckoutUrls(bookingId);
const session = await stripeClient.checkout.sessions.create({
mode: 'payment',
customer_email: email,
success_url: urls.successUrl,
cancel_url: urls.cancelUrl,
line_items: [
{
quantity: 1,
price_data: {
currency: 'gbp',
product_data: {
name: `Holiday Property Booking ${bookingId.slice(0, 8)}`,
description: 'Booking deposit and reservation payment',
},
unit_amount: amountCents,
},
},
],
metadata: {
bookingId,
},
});
return session;
}
export async function createBookingCheckout(input: BookingCheckoutInput): Promise<BookingCheckoutResult> {
const property = findProperty(input.propertySlug);
if (!property) {
throw new Error('Unknown property');
}
const quote = quoteStay(property, input);
if (!quote.available) {
throw new Error(quote.reasons.join(' '));
}
const firstName = normalizeRequiredString(input.firstName, 'firstName');
const lastName = normalizeRequiredString(input.lastName, 'lastName');
const email = normalizeRequiredString(input.email, 'email');
const termsAccepted = normalizeBoolean(input.termsAccepted, 'termsAccepted');
const adults = normalizeNumber(input.adults, 'adults');
const children = normalizeNumber(input.children, 'children');
const pets = normalizeNumber(input.pets, 'pets');
const holdMinutes = getBookingHoldMinutes();
const holdExpiresAt = new Date(Date.now() + holdMinutes * 60 * 1000);
const dbProperty = await ensureDbProperty(property.slug);
const booking = await prisma.booking.create({
data: {
propertyId: dbProperty.id,
firstName,
lastName,
email,
phone: input.phone?.trim() || null,
arrivalDate: new Date(`${quote.arrivalDate}T00:00:00.000Z`),
departureDate: new Date(`${quote.departureDate}T00:00:00.000Z`),
adults,
children,
pets,
specialRequests: input.specialRequests?.trim() || null,
termsAccepted,
holdExpiresAt,
totalCents: quote.totalCents,
currency: 'GBP',
status: BookingStatus.PENDING_PAYMENT,
},
});
const payment = await prisma.payment.create({
data: {
bookingId: booking.id,
amountCents: quote.totalCents,
currency: 'GBP',
status: PaymentStatus.REQUIRES_PAYMENT,
},
});
const session = await createStripeSession(booking.id, quote.totalCents, email);
if (session) {
await prisma.payment.update({
where: { id: payment.id },
data: {
stripeCheckoutSessionId: session.id,
},
});
return {
bookingId: booking.id,
paymentId: payment.id,
checkoutUrl: session.url || getCheckoutUrls(booking.id).fallbackUrl,
checkoutMode: 'stripe',
quote,
};
}
return {
bookingId: booking.id,
paymentId: payment.id,
checkoutUrl: getCheckoutUrls(booking.id).fallbackUrl,
checkoutMode: 'mock',
quote,
};
}
async function updatePaymentOutcome(bookingId: string, status: PaymentStatus, bookingStatus: BookingStatus, eventId: string, stripeIds: { checkoutSessionId?: string | null; paymentIntentId?: string | null } = {}) {
const [payment, booking] = await prisma.$transaction([
prisma.payment.update({
where: { bookingId },
data: {
status,
stripeEventId: eventId,
stripeCheckoutSessionId: stripeIds.checkoutSessionId ?? undefined,
stripePaymentIntentId: stripeIds.paymentIntentId ?? undefined,
},
}),
prisma.booking.update({
where: { id: bookingId },
data: {
status: bookingStatus,
},
}),
]);
return { payment, booking };
}
export async function handleStripeWebhookEvent(rawEvent: unknown): Promise<PaymentEventResult> {
const event = rawEvent as { id?: string; type?: string; data?: { object?: Record<string, unknown> } };
const eventId = event.id ?? `dev-${Date.now()}`;
const eventType = event.type ?? 'unknown';
const object = event.data?.object ?? {};
const metadata = (object.metadata ?? {}) as Record<string, string>;
const bookingId = metadata.bookingId;
if (!bookingId) {
throw new Error('Webhook payload did not include booking metadata');
}
if (eventType === 'checkout.session.completed' || eventType === 'payment_intent.succeeded') {
const result = await updatePaymentOutcome(
bookingId,
PaymentStatus.COMPLETED,
BookingStatus.CONFIRMED,
eventId,
{
checkoutSessionId: typeof object.id === 'string' ? object.id : null,
paymentIntentId: typeof object.payment_intent === 'string' ? object.payment_intent : null,
},
);
const notification = await recordNotification(bookingId, true);
return {
bookingId,
paymentId: result.payment.id,
status: BookingStatus.CONFIRMED,
notification,
};
}
if (eventType === 'checkout.session.expired' || eventType === 'payment_intent.payment_failed') {
const result = await updatePaymentOutcome(
bookingId,
PaymentStatus.FAILED,
BookingStatus.FAILED,
eventId,
{
checkoutSessionId: typeof object.id === 'string' ? object.id : null,
paymentIntentId: typeof object.payment_intent === 'string' ? object.payment_intent : null,
},
);
const notification = await recordNotification(bookingId, false);
return {
bookingId,
paymentId: result.payment.id,
status: BookingStatus.FAILED,
notification,
};
}
return {
bookingId,
paymentId: 'unknown',
status: BookingStatus.PENDING_PAYMENT,
notification: null,
};
}
export async function handleStripeWebhookBody(rawBody: string, signature: string | null) {
if (stripeClient && stripeWebhookSecret && signature) {
const event = stripeClient.webhooks.constructEvent(rawBody, signature, stripeWebhookSecret);
return handleStripeWebhookEvent(event);
}
const parsed = JSON.parse(rawBody) as unknown;
return handleStripeWebhookEvent(parsed);
}
export async function simulateCompletedPayment(bookingId: string) {
return handleStripeWebhookEvent({
id: `sim-${bookingId}`,
type: 'checkout.session.completed',
data: {
object: {
id: `cs_sim_${bookingId.slice(0, 8)}`,
payment_intent: `pi_sim_${bookingId.slice(0, 8)}`,
metadata: {
bookingId,
},
},
},
});
}
export async function getBookingCheckoutContext(bookingId: string) {
const booking = await prisma.booking.findUnique({
where: { id: bookingId },
include: {
property: true,
payment: true,
},
});
return booking;
}
export { stripeWebhookSecret };