Payments Integration
Charging money safely: hosted checkout, verified webhooks, idempotent event handling and reconciliation.
Before this: Background Jobs and Queues
Objective
Integrate a hosted payment provider's test mode end to end: server-created checkouts, signature-verified webhooks that survive duplicate deliveries, amounts decided only by the server, and a reconciliation habit that catches what automation missed.
Vocabulary
The words to use when directing your agent.
- payment provider
- A service that handles card details and money movement so you never touch raw card numbers.
- checkout session
- A server-created payment link the user completes on the provider's own pages.
- webhook
- The provider calling YOUR server to report real-world events like payments.
- signature verification
- Cryptographically checking a webhook truly came from the provider, unmodified.
- idempotency key
- A unique request marker so retrying never performs an action twice.
- reconciliation
- Periodically comparing your records against the provider's records for drift.
Understand it
The money path, drawn honestly
User clicks upgrade; your SERVER creates a checkout session with amount and currency it computes itself - never trusting any amount sent from the browser. User pays on provider-hosted pages. Provider sends webhooks to your endpoint; each one is verified against its signature, recorded, and processed idempotently by recording processed event ids. Only then does the account flip to pro. Every arrow in this path is a place amateurs leak money.
Duplicates, retries and reconciliation
Providers deliver webhooks at-least-once: expect duplicates and process them harmlessly by remembering which event ids already applied. Server crashes between receiving and processing must also recover - recording before acting or acting atomically with recording. And because no pipeline is perfect, schedule reconciliation: periodically compare your pro accounts against the provider's subscription list and investigate every mismatch.
Core concepts
Never touch card numbers
Card data has heavy compliance obligations you cannot shoulder as a beginner - or as most companies. Hosted checkout moves the sensitive collection onto the provider's pages; your system sees only references and outcomes. If code anywhere in your project could see a card number, the design is wrong.
The webhook is the source of truth
A success redirect is a rumor; the webhook is the fact. Browsers close, refreshes interrupt, but the provider's webhook arrives from their servers reporting what actually happened. Grant paid features ONLY on verified webhook evidence - never on client-side claims of success.
Examples
The forged-webhook probe
An attacker POSTs a fake 'payment succeeded' event to your webhook URL. Without signature verification this grants free pro access instantly. With verification, the forgery fails the signature check and gets a 400 plus a log entry. One middleware stands between you and free-product day.
Test mode discipline
Providers offer test modes with fake cards and separate test keys. Development happens entirely in test mode; keys live in environment variables - secret key server-side only. The moment a provider key appears in frontend code or git history, rotate it and treat the exposure as an incident.
Common mistakes
Common mistake
Trusting the browser redirect back from checkout to grant paid features.
Fix
Redirects are cosmetic. State changes ride on verified webhooks only. The client's 'success' page merely waits for the truth to arrive.
Common mistake
Accepting amounts, currencies or product ids from the client at checkout creation.
Fix
The server owns the price book. Client says WHICH thing they want; server says what it costs.
Working with your AI agent
Before implementation, make your agent draw the complete money path as text: every hop where amount originates, every state transition, every place a duplicate delivery could strike. Ask where the secret key lives and prove it appears nowhere else. Payments are where 'the agent said it works' becomes genuinely dangerous - verify like it is your money.
Build it
The module’s real project. Your agent builds; you direct and inspect.
Project: Paywall Gate
Add a Pro tier to the Ledger through a hosted provider's TEST mode: server-side checkout sessions, signature-verified idempotent webhooks flipping accounts to pro, one gated feature behind the paywall, and a documented reconciliation checklist.
Requirements
- Checkout session created server-side with price computed by the server; provider secret key from env, never committed
- Webhook endpoint verifies signatures; forged or unsigned requests rejected with 400 and logged
- Duplicate webhook deliveries produce exactly one account upgrade (processed-event ids recorded)
- One feature gated: pro users get unlimited exports, free users hit the export quota
- Events stored with type, id, timestamp and outcome - a queryable audit trail
- Reconciliation checklist documented: what to compare monthly against the provider's dashboard
Context for your agent
Integrate a hosted payment provider's TEST mode into my Expense Ledger as a Pro tier. Flow: upgrade button calls my server, server creates checkout session using its own price config; webhook endpoint verifies signatures before anything else, stores every event, processes upgrades idempotently via processed-event-id records; export feature gated by tier. All keys from env vars - test-mode only. Draw me the full money path first including failure points, then implement. Include a manual refund/cancel rehearsal in test mode.
Verify it - twice
Check every item yourself first. Then hand your agent the prompt and compare verdicts.
Verification prompt - paste into your AI agent
Conduct a hostile audit of my Paywall Gate - assume attackers get everything except my provider account and secret key. Attempt each and report PASS or FAIL against my DoD: (1) forge a payment-success webhook without a signature - did I get pro for free?, (2) replay a captured legitimate webhook multiple times - did I gain anything extra?, (3) tamper with checkout parameters client-side to name my own price - did the server honor my number?, (4) hunt my logs and repo for any trace of the secret key. Finally: trace one real test purchase end to end through every log line, and tell me where an auditor would still have questions.
Run this against “Payments Integration” after your own checklist pass. Where the agent and you disagree, investigate before moving on.
Review questions
Answer out loud. If you cannot, revisit before moving on.
Why is the success redirect untrustworthy while the webhook is authoritative?
Walk through how a duplicated webhook fails to double-upgrade anyone.
What does reconciliation catch that real-time processing missed?
You can now
- Wire hosted payments without ever touching card data
- Treat webhooks as untrusted input until signatures verify
- Keep money-state changes idempotent, audited and reconciled
Up next
Observability Foundation