How to Integrate Anthropic for payments with Cloudflare Workers for startups
Combining Anthropic for payments with Cloudflare Workers gives you a clean edge for startup-grade AI systems: low-latency edge execution plus a model-driven layer that can decide when and how to trigger payment flows. The practical win is simple — you can build agents that quote, approve, and initiate payment-related actions close to the user without routing every request through a central app server.
Prerequisites
- •Python 3.11+
- •An Anthropic API key
- •A Cloudflare account with:
- •Workers enabled
- •Wrangler CLI installed and authenticated
- •A Stripe account if your “payments” flow needs real charging logic behind the worker
- •
httpxorrequestsfor calling the Worker from Python - •
anthropicPython SDK installed:pip install anthropic httpx - •Environment variables set:
- •
ANTHROPIC_API_KEY - •
CLOUDFLARE_ACCOUNT_ID - •
CLOUDFLARE_API_TOKEN - •
WORKER_URL
- •
Integration Steps
- •
Set up Anthropic to decide when a payment action is needed
Use Anthropic as the reasoning layer. In a startup workflow, this is where the agent decides whether a user request should trigger a quote, invoice creation, or payment intent.
import os from anthropic import Anthropic client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) prompt = """ You are a billing assistant. If the user wants to pay an invoice, return JSON with: { "action": "create_payment_request", "amount": number, "currency": "usd", "customer_email": string, "reason": string } Otherwise return {"action":"noop"}. """ message = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=300, temperature=0, messages=[ {"role": "user", "content": f"Please pay invoice INV-1042 for $49.99 for acme@example.com"} ], system=prompt, ) print(message.content[0].text) - •
Expose a Cloudflare Worker endpoint for payment execution
Cloudflare Workers will be your edge endpoint. The Worker receives the structured intent from your app or agent runtime and forwards it to your payment provider.
In production, this is where you validate signatures, enforce idempotency, and keep secrets out of the client.
import os import httpx worker_url = os.environ["WORKER_URL"] payload = { "action": "create_payment_request", "amount": 49.99, "currency": "usd", "customer_email": "acme@example.com", "reason": "Invoice INV-1042" } response = httpx.post(worker_url, json=payload, timeout=10) response.raise_for_status() print(response.json()) - •
Implement the Worker-side payment bridge
Your Worker should accept JSON from the agent backend and call your payments API. If you use Stripe behind the worker, keep all secret handling inside Cloudflare.
The example below shows a Python script that deploys or configures the Worker interaction pattern from your backend side using Cloudflare’s API shape indirectly through HTTP calls. The actual Worker code lives in JavaScript/TypeScript, but this is how your Python service talks to it.
import os import json import httpx cf_token = os.environ["CLOUDFLARE_API_TOKEN"] account_id = os.environ["CLOUDFLARE_ACCOUNT_ID"] headers = { "Authorization": f"Bearer {cf_token}", "Content-Type": "application/json", } # Example: store worker metadata or hit an internal admin endpoint you expose on Workers. url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts/payment-agent" # This call is illustrative for managing the script lifecycle from Python. # In practice you'd deploy via wrangler; runtime calls still go to WORKER_URL. resp = httpx.get(url, headers=headers, timeout=15) print(resp.status_code) print(resp.text[:200]) - •
Wire Anthropic output into the Worker request
This is the core loop: Anthropic produces structured intent, your Python backend validates it, then forwards it to Cloudflare Workers for execution.
Keep this layer strict. Don’t let free-form text reach the payment boundary.
import os import json import httpx from anthropic import Anthropic anthropic_client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) worker_url = os.environ["WORKER_URL"] def get_payment_intent(user_text: str) -> dict: system_prompt = """ Return only valid JSON. Schema: { "action": "create_payment_request" | "noop", "amount": number | null, "currency": string | null, "customer_email": string | null, "reason": string | null } """ msg = anthropic_client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=200, temperature=0, system=system_prompt, messages=[{"role": "user", "content": user_text}], ) return json.loads(msg.content[0].text) intent = get_payment_intent("Charge acme@example.com $49.99 for invoice INV-1042") if intent["action"] != "noop": r = httpx.post(worker_url, json=intent, timeout=10) r.raise_for_status() print(r.json()) else: print({"status": "ignored"}) - •
Add idempotency and audit logging
Payments need replay protection and traceability. Use an idempotency key derived from the invoice or request ID and log every agent decision before it hits the Worker.
import hashlib import json import httpx def idempotency_key(source: str) -> str: return hashlib.sha256(source.encode("utf-8")).hexdigest() payload = { "action": "create_payment_request", "amount": 49.99, "currency": "usd", "customer_email": "acme@example.com", "reason": "Invoice INV-1042", "idempotency_key": idempotency_key("INV-1042"), } # audit log before sending to edge worker print(json.dumps({"event": "payment_intent_created", **payload}, indent=2)) resp = httpx.post( os.environ["WORKER_URL"], json=payload, headers={"X-Idempotency-Key": payload["idempotency_key"]}, timeout=10, ) resp.raise_for_status() print(resp.json())
Testing the Integration
Run a local smoke test that simulates a user asking to pay an invoice, then verify that Anthropic returns structured JSON and that the Worker responds with a payment confirmation object.
import os
import json
import httpx
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
worker_url = os.environ["WORKER_URL"]
msg = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=150,
temperature=0,
system="Return only JSON with action/amount/currency/customer_email/reason.",
messages=[{"role": "user", "content": "Pay $19.00 to billing@startup.io for invoice STP-778"}],
)
intent = json.loads(msg.content[0].text)
response = httpx.post(worker_url, json=intent, timeout=10)
response.raise_for_status()
print("Anthropic intent:", intent)
print("Worker response:", response.json())
Expected output:
Anthropic intent: {'action': 'create_payment_request', 'amount': 19.0, 'currency': 'usd', 'customer_email': 'billing@startup.io', 'reason': 'invoice STP-778'}
Worker response: {'status': 'ok', 'payment_request_id': 'pr_12345', 'provider': 'stripe'}
Real-World Use Cases
- •
AI billing assistant
- •Let users ask natural-language questions like “pay my latest invoice” or “show failed payments,” then route approved actions through Workers.
- •
Subscription ops agent
- •Detect failed renewals, generate payment links, and send retry flows without putting your origin server on every request path.
- •
Support-to-payments workflow
- •A support agent can confirm refund eligibility with Anthropic, then trigger refund or charge adjustment logic at the edge through Cloudflare Workers.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit