payload-bookings-payments
Skill0 starsChanged 13 days agoMITView on GitHub
Consultation booking with a server-side slot hold and online payment for Payload CMS 3 and Next.js 16. Gateways are Paymob, Kashier, Fawry, Stripe, PayPal, and Tap, plus Google Calendar with Google Meet and an ICS confirmation email. Use when adding a bookable service, checkout, payment webhook, slot availability, a booking hold, or a refund after a missed slot.
- Reads credentials
In this repository20 other files it gives its agents.
- AGENTS.mdAGENTS.md
- agent-guardrailsSkill
- creative-frontendSkill
- figma-handoffSkill
- payload-admin-brandingSkill
- payload-auth-rbacSkill
- payload-bootstrapSkill
- payload-deploy-vercelSkill
- payload-forms-crmSkill
- payload-integrationsSkill
- payload-legal-trustSkill
- payload-live-previewSkill
- payload-localizationSkill
- payload-mcpSkill
- payload-mediaSkill
- payload-performanceSkill
- payload-project-kickoffSkill
- payload-seo-geoSkill
- payload-testingSkill
- project-architectureSkill
The file
We split this skill into the rules it gives an agent
11 rules. About 0 are common, 2 are distinctive, and 9 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
9
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 13
Do not add transactionOptions to @payloadcms/db-sqlite.
- Very specific: line 17
Ask before enabling a provider.
- Distinctive: line 34
Follow references/booking-model.md.
- Very specific: line 37
Add global booking-settings: IANA timezone, weekly hours, slot length, buffer, minimum lead time, max days ahead, blackout dates, default …
- Very specific: line 38
Add collection bookings with slotKey (unique), status union, publicToken, money fields, and provider fields.
- Very specific: line 39
Add collection payment-events with unique providerEventId.
- Very specific: line 57
Follow references/provider-interface.md.
- Very specific: line 62
Verify the signature. Compare with timingSafeEqual.
- Distinctive: line 71
Follow references/google-calendar.md.
- Very specific: line 120
Add the names the enabled providers need to .env.example.
- Very specific: line 164
Stop and write the question under ## Questions in PROJECT.md when any of these is missing:
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Payload bookings and payments
One consultant calendar, paid online before the slot is confirmed. The browser return URL never confirms a booking. A verified webhook does, through a compare-and-set on pending_payment.
Do not add transactionOptions to @payloadcms/db-sqlite. libSQL has no safe concurrent transactions. Uniqueness is a unique index. Confirmation is payload.update with a where on the expected status. Money is integer minor units. Never log secrets, raw webhook bodies, or card data.
Step 1: Choose gateways
Ask before enabling a provider. Record the choice in PROJECT.md.
| Gateway | Use when | Settlement the client must confirm | Test mode | Amount sent to the gateway |
| Paymob | Egypt cards and wallets (EGP). Regional accounts exist for UAE, KSA, and Oman | Paymob merchant account, payout currency | Secret key prefix and integration id must both be test | Integer minor units (amount in cents) |
| Kashier | Egypt cards and wallets (EGP) | Kashier merchant, payout currency | test-api.kashier.io plus test keys | Decimal string in the session body. The order hash coerces 20.00 to 20 |
| Fawry | Egypt cards (EGP) through the charge API with 3DS | FawryPay merchant | atfawry.fawrystaging.com | Signature uses a two-decimal string. JSON amount matches that value |
| Stripe | International cards. Currencies the Stripe account has enabled | Stripe account country and payout currency | sk_test_ and a test webhook secret | Integer minor units (unit_amount) |
| PayPal | Buyer PayPal balance or card, where PayPal supports the currency | PayPal business account | api-m.sandbox.paypal.com | Decimal string ("10.00") |
| Tap | Gulf cards (SAR, AED, QAR, KWD, BHD, OMR, and others Tap enables) | Tap merchant and payout currency | Secret key starting sk_test_ | Major-unit decimal on the charge. The webhook hash uses a fixed number of decimals |
Details, endpoints, and signature field order: references/paymob.md, references/kashier.md, references/fawry.md, references/stripe.md, references/paypal.md, references/tap.md.
Enable only providers the client has credentials for. One default provider on the form is enough; extra providers are a select list fed by booking-settings.enabledProviders.
Step 2: Data model
Follow references/booking-model.md. Summary:
- On
services, keeppriceMinorfrom thepayload-bootstrapskill. If an existing collection still has major-unitprice, replace it withpriceMinorand do not keep both. KeepcurrencyanddurationMinutes. - Add global
booking-settings: IANA timezone, weekly hours, slot length, buffer, minimum lead time, max days ahead, blackout dates, default currency, enabled providers, hold minutes, calendar resource id. - Add collection
bookingswithslotKey(unique), status union,publicToken, money fields, and provider fields. - Add collection
payment-eventswith uniqueproviderEventId. Store ids, amount, currency, and outcome only. - Access follows the matrix in the
payload-auth-rbacskill. Public create happens only in the route handler, which uses the Local API.createon the collection stays closed. - Run
pnpm generate:types.
Currency exponents and toMinor / toMajor live in that reference. Use them for every gateway. Stripe's current currency guide does not document a three-decimal rounding rule; see the Stripe reference before charging KWD, BHD, OMR, or JOD.
Step 3: Slots, hold, return page, cron
Follow references/availability-and-holds.md.
GET /api/bookings/slotscomputes slots in the business timezone from settings, confirmed bookings, unexpired holds, and Google Calendar freebusy.Cache-Control: no-store. The client uses TanStack Query withstaleTime: 0.POST /api/bookingsvalidates with the shared Zod schema, creates the hold, and returns{ redirectUrl }. A unique violation onslotKeyfrees an expired hold once via compare-and-set, then retries once. Any other occupant returns 409.- Stripe Checkout
expires_atmust be 30 minutes to 24 hours after creation. When Stripe is enabled, the hold is at least 30 minutes and the Checkout expiry is that same timestamp. GET /api/bookings/status?token=is the only status the return page trusts. Poll withrefetchIntervaluntil a final status, then stop and show a timeout message.GET /api/cron/expire-holdsflips stale holds toexpiredand tombstonesslotKey. Hobby cron runs at most once per day. Availability already treats an expired hold as free, so this job is cleanup.
Step 4: Providers and webhooks
Follow references/provider-interface.md. One server-only PaymentProvider with an exhaustive switch. Each provider file lives in src/features/payments/providers/.
Webhook route: src/app/api/webhooks/<provider>/route.ts.
await request.text()before any JSON parse.- Verify the signature. Compare with
timingSafeEqual. A failed check returns 401 and writes nothing. - A
failedorexpiredevent returns 200 and writes nothing. Arefundedevent is stored, then compare-and-setsconfirmedtorefunded. Apaidevent is stored inpayment-events. A duplicateproviderEventIdreturns 200 with no side effects, except the recovery case in the provider reference. - Require the amount and currency to match the booking. A mismatch moves the booking to
needs_refundand does not confirm it. - Compare-and-set
pending_paymenttoconfirmed. Schedule calendar and email only when that update changed one document. - A payment for an expired hold confirms only if the slot is still free. Otherwise set
needs_refundand email admins once. after()fromnext/serverruns the side effects so the handler can return 200 first.
Step 5: Calendar, Meet, and email
Follow references/google-calendar.md. Ask which Google account type before writing auth.
Send the confirmation through the email helper defined by payload-integrations, in booking.locale, with an ics attachment. Do not add a second email client.
Step 6: Localization and pages
Pages, not business logic:
src/app/(frontend)/[locale]/book/page.tsxsrc/app/(frontend)/[locale]/book/return/page.tsx
API routes stay outside [locale], under src/app/api/, so the proxy from the payload-localization skill does not rewrite them. Format every visitor-facing date with Intl.DateTimeFormat and timeZone set to the business timezone. Weekday and hour labels use the page locale. Emails use booking.locale, not the webhook's locale.
The booking form uses React Hook Form, zodResolver, and useMutation. The schema uses z.email(), z.e164(), z.iso.datetime(), and z.iso.date(). The route parses the same schema.
Step 7: Invalidation
bookings and payment-events are private. Do not register a revalidation hook on them.
booking-settings renders on /book only. Service pages render priceMinor from the service document, so a settings save does not touch them. The service's own publish hook (see the payload-performance skill) already regenerates a service page when its price changes.
import type { GlobalAfterChangeHook } from 'payload'
import { applyRevalidation, localizedPaths } from '@/utilities/revalidation'
export const revalidateBookingSettings: GlobalAfterChangeHook = ({ doc, req }) => {
if (req.context.disableRevalidate) return doc
// Regenerates /book for each locale. Service pages do not read this global.
applyRevalidation(
{ reason: 'booking-settings', paths: localizedPaths('/book'), tags: [] },
req.payload,
)
return doc
}Copy these rows into the PROJECT.md invalidation map. Do not add a second services row. A price change already rides that collection's publish row. Paths use <locale> so the trace spec can expand them. Two locales are shown in the writes column.
| Collection or global | Trigger | Paths (per locale) | Tags | Writes per save |
| bookings | any | none | none | 0 |
| payment-events | any | none | none | 0 |
| booking-settings | update | /<locale>/book | none | 1 x locales |
Batch seed writes pass context: { disableRevalidate: true }.
Environment variables
Add the names the enabled providers need to .env.example. Leave values empty. Real values stay in .env and the host dashboard.
CRON_SECRET=
PAYMOB_SECRET_KEY=
PAYMOB_PUBLIC_KEY=
PAYMOB_HMAC_SECRET=
PAYMOB_INTEGRATION_IDS=
PAYMOB_API_BASE=
PAYMOB_CHECKOUT_BASE=
KASHIER_MERCHANT_ID=
KASHIER_SECRET_KEY=
KASHIER_API_KEY=
KASHIER_MODE=test
FAWRY_MERCHANT_CODE=
FAWRY_SECURE_KEY=
FAWRY_MODE=sandbox
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
PAYPAL_CLIENT_ID=
PAYPAL_CLIENT_SECRET=
PAYPAL_WEBHOOK_ID=
PAYPAL_MODE=sandbox
TAP_SECRET_KEY=
GOOGLE_AUTH_MODE=service-account
GOOGLE_CALENDAR_AUTH_MODE=oauth
GOOGLE_OAUTH_CLIENT_ID=
GOOGLE_OAUTH_CLIENT_SECRET=
GOOGLE_OAUTH_REFRESH_TOKEN=
GOOGLE_CALENDAR_OAUTH_CLIENT_ID=
GOOGLE_CALENDAR_OAUTH_CLIENT_SECRET=
GOOGLE_CALENDAR_OAUTH_REFRESH_TOKEN=
GOOGLE_CLIENT_EMAIL=
GOOGLE_PRIVATE_KEY=
GOOGLE_CALENDAR_CLIENT_EMAIL=
GOOGLE_CALENDAR_PRIVATE_KEY=
GOOGLE_CALENDAR_OWNER_EMAIL=
GOOGLE_CALENDAR_ID=PAYMOB_INTEGRATION_IDS is a comma-separated list of integration ids whose mode matches the secret key. GOOGLE_AUTH_MODE is service-account or oauth for Sheets, Drive, and Search Console. GOOGLE_CALENDAR_AUTH_MODE is the same pair of values and is independent: a site can use a service account for the sheet and OAuth for a personal calendar, or the other way around. Fill only the credential pair for the mode you chose. Calendar override variables stay empty when calendar uses the same account as Sheets. GOOGLE_CLIENT_EMAIL and GOOGLE_PRIVATE_KEY are the same names as in the payload-integrations skill.
Stop and ask
Stop and write the question under ## Questions in PROJECT.md when any of these is missing:
- Which providers and currencies, and the settlement currency of each merchant account
- Prices, duration, timezone, weekly hours, lead time, blackout dates, and hold minutes
- API keys, webhook secrets, and sandbox versus live
- Google account type: personal Gmail or Workspace
- Whether a kiosk method (Pay at Fawry) is required. That flow pays hours later and needs a long hold the client must accept
- Refund policy text (the public policy page belongs to
payload-legal-trust) - A Stripe, PayPal, or Tap currency the account cannot charge
Diagnosis
| Symptom | Cause | Fix |
| Two bookings for one slot | slotKey not unique, or the retry freed a live hold | Hold reference |
| Webhook 401 for a real payment | Field order, amount formatting, or raw body re-serialized | That provider's reference |
Booking stays pending_payment after payment | Return URL was trusted, or the webhook is not the server notification | Status poll and webhook route |
| Second email or second Meet link | Side effects ran when compare-and-set changed 0 documents | Provider reference |
| Slot still blocked after the hold | Query treats holdExpiresAt in the past as busy | Availability reference |
| Cron deploy fails on Hobby | Schedule runs more than once per day | Daily expression only |
| Stripe session create rejected | expires_at under 30 minutes or over 24 hours | Stripe reference |
Done when
pnpm generate:typessucceeds withbookings,payment-events, andbooking-settings- Two browsers posting the same slot: one hold, one 409, and one
bookingsrow with thatslotKey - Replaying one verified webhook confirms once: one
payment-eventsrow, one confirmation email, one calendar event - A tampered signature returns 401 or 400 and does not change
bookingsorpayment-events - After
holdExpiresAt, that slot is offered again before the cron runs - The return page reaches
confirmedonly after the webhook, not from gateway query parameters - A sandbox payment completes for each enabled provider
- Saving
booking-settingslogsrevalidate (booking-settings)with only the localized/bookpaths - Saving a booking or a payment event logs no
revalidateline
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

