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

51
package-lock.json generated
View File

@@ -12,7 +12,8 @@
"bootstrap": "^5.3.3", "bootstrap": "^5.3.3",
"next": "^15.0.0", "next": "^15.0.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0" "react-dom": "^19.0.0",
"stripe": "^17.7.0"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.60.0", "@playwright/test": "^1.60.0",
@@ -1876,7 +1877,6 @@
"version": "20.17.6", "version": "20.17.6",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.17.6.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.17.6.tgz",
"integrity": "sha512-VEI7OdvK2wP7XHnsuXbAJnEpEkF6NjSN45QJlL4VGqZSXsnicpesdTWsg9RISeSdYd3yeRj/y3k5KGjUXYnFwQ==", "integrity": "sha512-VEI7OdvK2wP7XHnsuXbAJnEpEkF6NjSN45QJlL4VGqZSXsnicpesdTWsg9RISeSdYd3yeRj/y3k5KGjUXYnFwQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"undici-types": "~6.19.2" "undici-types": "~6.19.2"
@@ -2885,7 +2885,6 @@
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"es-errors": "^1.3.0", "es-errors": "^1.3.0",
@@ -2899,7 +2898,6 @@
"version": "1.0.4", "version": "1.0.4",
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"call-bind-apply-helpers": "^1.0.2", "call-bind-apply-helpers": "^1.0.2",
@@ -3243,7 +3241,6 @@
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"call-bind-apply-helpers": "^1.0.1", "call-bind-apply-helpers": "^1.0.1",
@@ -3355,7 +3352,6 @@
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 0.4" "node": ">= 0.4"
@@ -3365,7 +3361,6 @@
"version": "1.3.0", "version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 0.4" "node": ">= 0.4"
@@ -3403,7 +3398,6 @@
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"es-errors": "^1.3.0" "es-errors": "^1.3.0"
@@ -4111,7 +4105,6 @@
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"dev": true,
"license": "MIT", "license": "MIT",
"funding": { "funding": {
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
@@ -4162,7 +4155,6 @@
"version": "1.3.0", "version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"call-bind-apply-helpers": "^1.0.2", "call-bind-apply-helpers": "^1.0.2",
@@ -4187,7 +4179,6 @@
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"dunder-proto": "^1.0.1", "dunder-proto": "^1.0.1",
@@ -4293,7 +4284,6 @@
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 0.4" "node": ">= 0.4"
@@ -4358,7 +4348,6 @@
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 0.4" "node": ">= 0.4"
@@ -4387,7 +4376,6 @@
"version": "2.0.3", "version": "2.0.3",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz",
"integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"function-bind": "^1.1.2" "function-bind": "^1.1.2"
@@ -5053,7 +5041,6 @@
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 0.4" "node": ">= 0.4"
@@ -5288,7 +5275,6 @@
"version": "1.13.4", "version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 0.4" "node": ">= 0.4"
@@ -5716,6 +5702,21 @@
], ],
"license": "MIT" "license": "MIT"
}, },
"node_modules/qs": {
"version": "6.15.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",
"integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.1.0"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/queue-microtask": { "node_modules/queue-microtask": {
"version": "1.2.3", "version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
@@ -6159,7 +6160,6 @@
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"es-errors": "^1.3.0", "es-errors": "^1.3.0",
@@ -6179,7 +6179,6 @@
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"es-errors": "^1.3.0", "es-errors": "^1.3.0",
@@ -6196,7 +6195,6 @@
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"call-bound": "^1.0.2", "call-bound": "^1.0.2",
@@ -6215,7 +6213,6 @@
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"call-bound": "^1.0.2", "call-bound": "^1.0.2",
@@ -6397,6 +6394,19 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/stripe": {
"version": "17.7.0",
"resolved": "https://registry.npmjs.org/stripe/-/stripe-17.7.0.tgz",
"integrity": "sha512-aT2BU9KkizY9SATf14WhhYVv2uOapBWX0OFWF4xvcj1mPaNotlSc2CsxpS4DS46ZueSppmCF5BX1sNYBtwBvfw==",
"license": "MIT",
"dependencies": {
"@types/node": ">=8.1.0",
"qs": "^6.11.0"
},
"engines": {
"node": ">=12.*"
}
},
"node_modules/styled-jsx": { "node_modules/styled-jsx": {
"version": "5.1.6", "version": "5.1.6",
"resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz", "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz",
@@ -6696,7 +6706,6 @@
"version": "6.19.8", "version": "6.19.8",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz",
"integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/unrs-resolver": { "node_modules/unrs-resolver": {

View File

@@ -17,7 +17,8 @@
"bootstrap": "^5.3.3", "bootstrap": "^5.3.3",
"next": "^15.0.0", "next": "^15.0.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0" "react-dom": "^19.0.0",
"stripe": "^17.7.0"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.60.0", "@playwright/test": "^1.60.0",

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} /> <input aria-label={field.label} defaultValue={field.value} />
</label> </label>
))} ))}
<button className="btn btn-dark" type="button"> <Link className="btn btn-dark" href="/bookings/new">
Check availability Check availability
</button> </Link>
</form> </form>
<div className="quote-panel" aria-label="Booking quote preview"> <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 };