Letting an AI Agent Take Payments Safely: What to Hand Off and What to Keep
AI agents no longer only answer questions about payments. With an MCP server or an API key, an agent can create a checkout, read a customer's invoices, change a subscription plan or ask for a refund. The engineering question has moved from "can the agent do this?" to "which of these actions should the agent be allowed to do on its own?"
The rule I use is simple. The agent proposes and prepares. Deterministic code enforces. A human approves anything that sends money out. Everything below is an application of that rule.
| Hand off to the agent | Keep in code or with a human |
|---|---|
| Create a checkout link for a known product | Handling card numbers in any form |
| Look up a payment's status | Choosing live vs test mode |
| List invoices, send a receipt again | Amount and currency limits |
| Draft a refund request with a reason | Approving the refund |
| Summarize disputes and failed renewals | Signing secrets and webhook verification |
| Suggest a plan change | Writing to the audit log |
1. Keep card data out of the agent entirely
The agent should never see, store or forward a card number. Not in a tool argument, not in a chat message, not in a log line.
This is easier than it sounds: the agent never needs card data to take a payment. It creates a hosted checkout and returns the link. The buyer types their card into the payment provider's form, and neither your server nor the agent receives it. If you fully outsource card entry to a validated provider's hosted page, your PCI DSS scope stays at its smallest; the PCI SSC document library has the self-assessment questionnaires that define it.
Agent transcripts are logs. They get stored, replayed, sent to model providers and pasted into bug reports. If a customer pastes a card number into a support chat that an agent reads, treat it as an incident: redact it before it reaches the model, and tell the customer to use the checkout link.
2. Test keys by default, live keys by exception
Give the agent a test key while you build, and make the agent process refuse a live key unless someone turned that on deliberately. Most providers encode the mode in the key prefix, so the check is one line at startup:
function assertAgentKey(key: string, allowLive: boolean): void { const isTest = key.startsWith('sk_test_') || key.startsWith('rk_test_'); if (!isTest && !allowLive) { throw new Error('Agent process refuses to start with a live key'); } } assertAgentKey(process.env.PAYMENTS_KEY ?? '', process.env.AGENT_ALLOW_LIVE === 'true'); When you do go live, scope the key. Stripe's documentation recommends restricted API keys for keys you give to AI agents, so the key can only touch the resources you grant (Read, Write or None per resource). One key per service: the agent's key should not be the key your refund worker uses.
3. Limits live in code, not in the prompt
"Never create a checkout over 500 euros" in a system prompt is a suggestion. Prompt injection is number one on the OWASP Top 10 for LLM Applications, and an agent that reads customer emails or web pages will eventually read text written to change its behavior. OWASP calls the resulting damage Excessive Agency: the agent had more power than its task needed.
Put the limits in the tool handler, between the model and the API:
type Policy = { maxPerCheckoutMinor: Record<string, number>; dailyCapMinor: Record<string, number>; }; type CheckoutRequest = { amountMinor: number; currency: string }; function checkPolicy(req: CheckoutRequest, policy: Policy, spentTodayMinor: number): string | null { const max = policy.maxPerCheckoutMinor[req.currency]; const cap = policy.dailyCapMinor[req.currency]; if (max === undefined || cap === undefined) return `currency ${req.currency} is not allowed`; if (!Number.isInteger(req.amountMinor) || req.amountMinor <= 0) { return 'amount must be a positive integer in minor units'; } if (req.amountMinor > max) return `amount ${req.amountMinor} is over the per-checkout limit ${max}`; if (spentTodayMinor + req.amountMinor > cap) return 'daily cap reached, ask a human'; return null; // allowed } Return the refusal reason to the model as the tool result. A clear "over the per-checkout limit" lets the agent explain the problem to the user instead of retrying with a different phrasing. Use integer minor units (cents) in the policy, because models are loose with decimals: 49.99 and 4999 look similar in a transcript.
4. Idempotency keys tied to the agent's intent
Payment APIs use idempotency keys so a retried request does not charge twice. Stripe's idempotency docs suggest V4 UUIDs or similar random strings, allow keys up to 255 characters, warn against putting personal data such as email addresses in them, and may prune keys after 24 hours.
Agents add a failure mode that SDK retries do not cover. Many SDKs generate a fresh random key per call and reuse it only for their own network retries. That protects you from a dropped TCP connection. It does not protect you from the agent itself: the tool call times out, the model decides to "try again", and your handler sends a brand-new request with a brand-new key. Two checkouts, or two charges.
The fix is to derive the key from the agent's intent: the task, the action and the canonical parameters. The same intent produces the same key, however many times the model calls the tool.
import { createHash } from 'node:crypto'; function canonical(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`; if (value && typeof value === 'object') { const entries = Object.entries(value as Record<string, unknown>) .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`); return `{${entries.join(',')}}`; } return JSON.stringify(value); } function intentKey(taskId: string, action: string, params: unknown): string { return createHash('sha256').update(`${taskId}|${action}|${canonical(params)}`).digest('hex'); } The hash keeps personal data out of the key and fits well under 255 characters. Sorting object keys matters: {a, b} and {b, a} must produce the same key.
Two caveats. Not every endpoint honors the header, so read your provider's docs per endpoint; where it is ignored, list the resource and check whether the first request succeeded before retrying. And if the user genuinely wants a second checkout for the same thing, that must be a new task ID, decided by your code, not by the model.
5. Webhooks are the source of truth: verify, then deduplicate
The agent should never decide that a payment succeeded because a redirect happened or because the model "saw" a success page. Your backend learns about payments from signed webhooks.
Most providers sign {timestamp}.{raw_body} with HMAC-SHA256 and send t=...,v1=... in a header. Verify against the raw bytes, reject old timestamps, and compare in constant time:
import { createHmac, timingSafeEqual } from 'node:crypto'; function verifySignature(rawBody: Buffer, header: string, secret: string, toleranceSec = 300): boolean { const parts = Object.fromEntries( header.split(',').map((p) => { const i = p.indexOf('='); return [p.slice(0, i), p.slice(i + 1)]; }), ); const t = Number(parts.t); if (!Number.isInteger(t) || !parts.v1) return false; const age = Math.floor(Date.now() / 1000) - t; if (age < 0 || age > toleranceSec) return false; // replayed or clock skew const expected = createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest(); const given = Buffer.from(parts.v1, 'hex'); return given.length === expected.length && timingSafeEqual(given, expected); } Use your provider's SDK verifier if it has one; this is what it does underneath. Two common bugs: a JSON body parser that runs before verification (the re-serialized body no longer matches the signature), and a === comparison instead of a constant-time one.
Retries mean the same event arrives more than once. Store a dedup key per event with a unique constraint, return 2xx quickly, and do slow work (emails, provisioning) after you respond. Check which field your provider documents as the dedup key; the event ID is not always enough for every event type.
6. Refunds: the agent proposes, a human approves
Refunds are the clearest case of money leaving. OWASP's Excessive Agency entry uses an email assistant that could send messages when it only needed to read them; a support agent with a refund tool is the same mistake with money attached.
Give the agent a propose_refund tool that writes a row and nothing else. A person approves it in your admin. A separate worker, with its own key that the agent never sees, executes approved rows.
type RefundProposal = { id: string; paymentId: string; reason: string; // written by the agent, shown to the approver proposedBy: string; // agent run ID status: 'pending' | 'approved' | 'rejected' | 'executed'; approvedBy?: string; // a human user ID, never an agent }; The approver sees the agent's reason next to the original conversation, so a refund argued for by an injected instruction is easy to spot.
7. Audit every tool call
For each tool call, record: agent run ID, tool name, a hash of the arguments, the idempotency key, the policy decision, the provider's request ID, the result, and the human approver if there was one. Write it append-only, outside the agent's reach. When a customer asks "why was I charged twice?", this is the table that answers in minutes instead of days.
8. How a merchant of record changes the surface
So far the risk has been operational: double charges, bad refunds, leaked keys. There is a second, legal surface. When you sell digital products across borders as the seller, you owe VAT or sales tax in your buyers' countries; in the EU, VAT on digital services follows the buyer's location (see the EU One Stop Shop). An agent that happily creates checkouts for buyers in 30 countries is creating tax obligations in 30 countries.
A merchant of record (MoR) is the legal seller on each sale instead of you. It handles the VAT or sales tax that applies to each sale, issues the invoices, and answers disputes. For agent design, that changes three things: the tax logic leaves your codebase, invoices are not something your agent can get wrong, and refunds and chargebacks go through the MoR's own process. The trade-offs are real too: you give up some control over refund timing and checkout, and the MoR takes a fee.
Disclosure: I founded AgentaOS, a merchant of record, so here is the example I know best. Its MCP server lists 31 tools for products, checkouts, subscriptions, discount codes, customers and invoices, and none of them sends a refund. A person picks test or live mode on the approval page, and the mode is fixed from then on: to go live you disconnect and approve again, so the agent cannot promote itself. A test connection sees only test data. A refund request through the API moves no money until the MoR reviews it. That is the "agent proposes, someone else approves" pattern from section 6, enforced by the seller rather than by your code.
Two of those tools do change what a customer pays: moving a subscriber to a bigger plan charges the difference right away, and a credit comes off their next invoice. Neither sends money out of the account, but both belong behind the limits from section 3. Whichever provider you use, read its tool list the same way: which tools can move money, in which direction, and who approves them.
Checklist
- [ ] The agent never receives card numbers; it returns hosted checkout links.
- [ ] Transcripts are redacted before they reach the model or the logs.
- [ ] The agent process refuses live keys unless a flag says otherwise.
- [ ] Live keys are scoped to the agent's resources, one key per service.
- [ ] Amount, currency and daily limits are enforced in the tool handler.
- [ ] Idempotency keys come from task, action and canonical parameters.
- [ ] Webhooks are verified on the raw body, deduplicated, and answered fast.
- [ ] Refunds are proposals; a human approves; a separate worker executes.
- [ ] Every tool call lands in an append-only audit log.
- [ ] You know who the legal seller is, and who owes the tax.
What would you add to the checklist? I'm especially curious how others handle refund approval when the agent runs unattended.