Introducing a new way to review your PRs.

Read the announcement

calicastle / cali.so

Personal website for Cali Castle

View on GitHub

21 documents · Updated Sep 21, 2026

docs / ama-external-integrations

AMA payment and calendar integrations

AMA connects a paid Booking to external payment, calendar, meeting, and email services. Stripe confirms payment, Google Calendar supplies availability and event records, a selected meeting provider supplies the session link, and Resend sends guest messages. Durable work joins these services so a provider outage does not change the Booking's payment result. This page extends the AMA booking platform overview.

Integration model

The integration model keeps the Booking record as the system's source of truth while external systems provide payment proof or session artifacts. Provider work runs after the payment event and can be retried without creating duplicate charges, calendar events, meetings, or emails.

The main service relationships are:

SystemRole in AMABooking effect
StripeHosts Checkout and verifies payment through a signed webhookConverts a Slot Hold into a Booking or marks it needs_reschedule when a late payment loses the time
Google CalendarReads owner free/busy time and writes the invitationControls whether public availability is usable and stores the event and optional Google Meet link
Google MeetA calendar conference optionSupplies the meeting link when the guest selects google-meet
Tencent MeetingCreates a room through the configured server bridgeSupplies the meeting link when the guest selects tencent-meeting
ResendSends transactional emailDelivers confirmation, change, cancellation, and reminder messages
Durable operationsRuns provider work with leases and retry limitsKeeps paid Bookings in finalizing until their artifacts and messages are ready

Payment integration

Stripe provides the hosted payment step and the payment record that authorizes a Booking. AMA creates one Checkout Session for each Slot Hold, then treats the signed Stripe webhook as the only authoritative payment confirmation; the browser return only displays the current server state.

The payment flow moves through these stages:

flowchart LR
    A[Active Slot Hold] --> B[Stripe Checkout Session]
    B --> C{Signed Stripe webhook}
    C -->|Paid| D[Convert hold to Booking]
    C -->|Late payment conflict| E[Booking needs_reschedule]
    D --> F[Durable finalization]
    E --> G[Guest picks another time]
    B -->|Expired| H[Release Slot Hold]

The Checkout Session carries opaque hold and intent identifiers. AMA uses an idempotency key derived from the hold, so retries and repeated clicks reuse the same payment session. Stripe event identifiers are stored before event effects are applied, which makes duplicate and out-of-order deliveries safe. A paid Booking can therefore remain a Finalizing Booking while calendar, meeting, or email work waits for recovery.

Stripe also handles eligible refunds after cancellation. Refund requests use a Booking-specific idempotency key. A provider outage is retryable; a rejected refund is a terminal issue that needs owner action.

References: lib/…/service.ts• L326-385 lib/…/service.ts• L387-554 lib/…/client.ts• L95-199 lib/…/webhook.ts• L22-76 app/…/route.ts• L8-23

Calendar integration

Google Calendar serves two related purposes: it removes the owner's busy periods from public availability and it stores the event for a confirmed Booking. The owner connects one primary calendar through an authenticated admin flow. AMA refreshes the stored Google access when it needs to read free/busy data or change an event.

Google access requires the calendar events and free/busy permissions. The connection can be disconnected, denied, expired, revoked, or unavailable. When access is not usable, availability does not pretend that the calendar is clear; the public slot result becomes unavailable instead.

For a confirmed Booking, AMA creates an event with the guest as an attendee and sends calendar updates. A Google Meet conference is requested only when the guest selected Google Meet. The event uses a stable id based on the Booking and its start time, so a retry finds the existing event instead of creating a second invitation.

Calendar changes follow the Booking lifecycle:

Booking actionGoogle Calendar action
FinalizeCreate an event and send the invitation
Reschedule a Google Meet BookingMove the existing event and send the update
Reschedule a Tencent Meeting BookingRemove the old event and create a new one
CancelDelete the event; an already missing event is treated as complete

See AMA availability for how free/busy data combines with the owner's schedule. See AMA booking lifecycle for the order of payment, artifact creation, and guest changes.

References: lib/…/service.ts• L123-286 lib/…/client.ts• L10-13 lib/…/client.ts• L338-483 lib/…/booking-calendar.ts• L66-163 lib/…/calendar.ts• L6-49 app/…/route.ts• L8-17 app/…/route.ts• L8-17 app/…/route.ts• L8-17

Meeting provider integration

The guest selects a meeting provider during intake. AMA creates the meeting as part of finalization, then places the resulting link in the Booking, the calendar event, and the guest email. This keeps the provider choice tied to the Booking rather than to a global server setting.

Google Meet is created as part of the Google Calendar event. Tencent Meeting is created through a server-only MCP bridge. The Tencent adapter discovers the bridge's available meeting tools and accepts only a valid Tencent or VooV meeting URL. Tencent rooms do not guarantee cancellation or time changes, so a Tencent reschedule removes the old artifacts on a best-effort basis and creates new artifacts for the new time.

Provider differences are visible to the lifecycle rather than hidden:

ProviderLink sourceReschedule behaviorCancellation behavior
Google MeetGoogle Calendar conference dataMove the calendar eventDelete the calendar event
Tencent MeetingTencent meeting creation resultRecreate the room and calendar eventTry the provider's cancel tool; the provider may report unsupported

References: lib/…/types.ts• L3-44 lib/…/tencent.ts• L242-435 lib/…/handlers.ts• L110-165 lib/…/handlers.ts• L337-402

Email integration

Resend delivers the guest-facing messages that complete a Booking's external experience. AMA builds bilingual text and HTML messages from the Booking's current time, guest time zone, provider, meeting link, and private Manage Link.

The system sends these message types:

  • Confirmation after artifacts are ready.
  • Reschedule notice after the new artifacts are ready.
  • A new-time request when payment succeeded but the original time was taken.
  • Cancellation notice with the refund result when relevant.
  • Reminders 24 hours and 1 hour before the session.

Each logical message has an idempotency key. A retry therefore asks Resend to deliver the same message rather than treating the retry as a new message. If a meeting link is not ready, the message explains that the link will arrive in a calendar update instead of claiming that the session is ready.

References: lib/…/types.ts• L1-34 lib/…/resend.ts• L5-65 lib/…/templates.ts• L3-15 lib/…/templates.ts• L148-296 lib/…/handlers.ts• L167-237 lib/…/handlers.ts• L417-475

Webhook and background work

The Stripe webhook is the inbound provider boundary. It reads the raw request body, checks the Stripe signature and its five-minute freshness window, and passes only a valid event to the Booking service. A failed event response asks Stripe to deliver the event again.

Provider side effects run through durable operations. The webhook starts an inline drain after it creates a Booking, while the scheduled worker releases expired Slot Holds and drains work that is due. Each operation has a lease, bounded retry backoff, and a terminal failed state for owner recovery.

sequenceDiagram
    participant Stripe
    participant Webhook as Stripe webhook
    participant DB as Booking records
    participant Worker as Durable worker
    participant Providers as Calendar, meeting, and email providers

    Stripe->>Webhook: Signed payment event
    Webhook->>DB: Record event and create Booking once
    Webhook->>Worker: Start due operation drain
    Worker->>Providers: Create or update external artifacts
    Providers-->>Worker: Result or provider error
    Worker->>DB: Complete, retry, or park operation
    Webhook-->>Stripe: 200 on handled event or 503 for redelivery

The scheduled endpoint is /api/internal/ama/work. Vercel runs it every 30 minutes and protects it with CRON_SECRET. The worker is the recovery path for provider outages and interrupted requests; it does not replace the persisted Booking state.

References: lib/…/webhook.ts• L22-76 lib/…/http.ts• L252-292 lib/…/server.ts• L240-267 lib/…/repository.ts• L49-239 lib/…/runner.ts• L48-139 app/…/route.ts• L4-16 vercel.json• L6-14

Secrets and server environment

AMA keeps provider credentials and Booking security material on the server. Environment parsing validates the required core values and treats each optional provider as one complete credential pair. A half-configured provider is a startup error; an absent provider is disabled and its routes fail closed without calling provider code.

The main environment groups are:

GroupVariablesEnables
Core data and identityDATABASE_URL, ADMIN_EMAIL, SITE_URLDatabase access, owner identity, canonical links, provider return URLs, and same-origin checks
SecurityAMA_ENCRYPTION_KEY, RATE_LIMIT_HASH_KEYSecret encryption, Manage Link derivation, and pseudonymous rate limits
StripeSTRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRETCheckout, payment verification, and refunds
GoogleGOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRETFree/busy reads, calendar events, and Google Meet conferences
EmailRESEND_API_KEY, AMA_EMAIL_FROMBooking finalization and transactional email
TencentTENCENT_MEETING_MCP_URL, TENCENT_MEETING_MCP_TOKENTencent Meeting creation and best-effort cancellation
Work and rate limitsCRON_SECRET, Redis or KV credentials, rate-limit settingsScheduled work and deployment-appropriate public mutation limits

AMA_ENCRYPTION_KEY is a 32-byte base64 key. AMA uses it to seal Google refresh tokens and OAuth PKCE verifiers with authenticated encryption. The database stores encrypted envelopes, while the raw Google tokens remain server-only. RATE_LIMIT_HASH_KEY turns client and audit identifiers into stable pseudonyms without storing the raw address in the rate-limit key.

Provider credentials are cached in the server service graph for the process lifetime. Change them through the deployment environment and restart the server so the new feature state is loaded. Production uses a Redis-compatible rate-limit pair; preview uses the database; local development uses process memory.

References: lib/…/server-env-schema.ts• L47-79 lib/…/server-env-schema.ts• L106-151 lib/…/server-env-schema.ts• L194-319 lib/…/server-env.ts• L9-20 lib/…/secrets.ts• L5-71 lib/…/server.ts• L106-171 lib/…/server.ts• L213-231

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the Stripe Checkout metadata, webhook lookup, provider-event dedupe, and Booking uniqueness rules aligned. A mismatch can create an orphaned paid session or a second Booking.
  • Keep the Google OAuth callback origin, SITE_URL, and the registered Google redirect URI aligned across production and preview deployments.
  • Keep meeting provider names consistent across intake validation, Booking data, calendar artifact creation, email templates, and provider capability handling.
  • Keep durable-operation dedupe keys tied to the Booking's current start time. Reschedules must not let old finalization or reminder work update the new time.
  • Keep optional provider credentials as complete pairs. Do not add a route that assumes a provider exists when its feature flag is false.
  • Keep external provider changes behind the durable operation path so retries remain safe and owner recovery can see terminal failures.

Important failure modes

TriggerConsequenceGuard
Stripe signature is missing, stale, or invalidPayment event is rejected and no Booking is createdVerify the raw body and signature before parsing the event
Stripe sends a paid event after the Slot Hold expires and another guest has the timeThe paid Booking enters needs_rescheduleReclaim the interval only when it is still free; otherwise preserve payment and ask for a new time
Google access is revoked or lacks required scopeAvailability becomes unavailable and calendar work is retried or parkedRecord the connection status and require the owner to reconnect Google Calendar
Meeting creation returns no valid linkBooking remains finalizing and guest delivery waitsValidate the provider result and retry durable finalization
Resend or Stripe is unavailableEmail or refund work stays pending for retryUse provider error classes, idempotency keys, and bounded backoff
A provider credential pair is only partly configuredServer environment validation fails at startupConfigure both values or remove both values
Scheduled worker stops during an operationThe leased operation is reclaimed after lease expiryRun operations under leases and keep the scheduled sweep active

Key files

FileWhy to read it
lib/…/service.tsConnects Slot Holds, Stripe Checkout, webhook payment proof, and Booking creation
lib/…/server.tsAssembles the active Stripe, Google, Tencent, email, and durable-work services
lib/…/webhook.tsDefines the trust boundary for inbound Stripe events
lib/…/service.tsDefines the owner Google connection and free/busy lifecycle
lib/…/booking-calendar.tsMaps Booking artifact actions to calendar event writes
lib/…/tencent.tsDefines the Tencent Meeting server bridge and its provider limits
lib/…/handlers.tsCoordinates meetings, calendar events, email, refunds, and recovery
lib/…/runner.tsDefines leases, retries, and terminal operation handling
lib/…/templates.tsShows the guest messages produced from current Booking facts
lib/…/server-env-schema.tsDefines provider credential pairs and deployment environment rules
lib/…/secrets.tsDefines encryption for server-held Google OAuth secrets
app/…/route.tsExposes the scheduled recovery worker
vercel.jsonDefines the production schedule for the AMA worker