How to Integrate LangChain for payments with Stripe for multi-agent systems
LangChain for payments gives your agents a structured way to decide when money should move. Stripe handles the actual charge, invoice, or payment intent, which is what you want in a multi-agent system: one agent reasons, another approves, and Stripe executes with auditability.
The useful pattern here is not “agent makes payment directly.” It’s “agent proposes payment action, policy layer validates it, Stripe performs the transaction.” That separation matters when you have multiple agents coordinating refunds, subscriptions, or marketplace payouts.
Prerequisites
- •Python 3.10+
- •A Stripe account with:
- •API secret key
- •Test mode enabled
- •A webhook endpoint if you want async confirmation
- •A LangChain setup with:
- •
langchain - •
langchain-openaior your preferred model provider
- •
- •An orchestration layer for multi-agent routing:
- •LangGraph, AutoGen, CrewAI, or your own dispatcher
- •Environment variables configured:
- •
STRIPE_SECRET_KEY - •
OPENAI_API_KEY
- •
Install the packages:
pip install stripe langchain langchain-openai pydantic
Integration Steps
1) Initialize Stripe and define the payment tool
Use a thin wrapper around Stripe so the agent never talks to Stripe raw. In production, keep this wrapper behind a policy check.
import os
import stripe
from typing import Optional
stripe.api_key = os.environ["STRIPE_SECRET_KEY"]
def create_payment_intent(amount_cents: int, currency: str = "usd", customer_id: Optional[str] = None):
payload = {
"amount": amount_cents,
"currency": currency,
"automatic_payment_methods": {"enabled": True},
}
if customer_id:
payload["customer"] = customer_id
return stripe.PaymentIntent.create(**payload)
This uses the real Stripe SDK method stripe.PaymentIntent.create(...). For agent systems, this should be the only function that can hit Stripe directly.
2) Wrap the payment action as a LangChain tool
If you are using LangChain tools, expose the payment function with @tool. The agent can then call it as part of its reasoning flow.
from langchain_core.tools import tool
@tool
def charge_customer(amount_cents: int, currency: str = "usd") -> str:
"""
Create a Stripe PaymentIntent for a customer charge.
"""
intent = create_payment_intent(amount_cents=amount_cents, currency=currency)
return f"created_payment_intent:{intent.id}:status:{intent.status}"
This is the bridge between LangChain and Stripe. In multi-agent systems, one agent can request charge_customer, while another agent handles approval or fraud checks before execution.
3) Build an agent that can call the payment tool
Use a chat model plus tool binding. The model decides when to call the Stripe-backed tool based on user intent.
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
tools = [charge_customer]
agent_llm = llm.bind_tools(tools)
messages = [
("system", "You are a billing assistant. Only charge after explicit approval."),
("user", "Charge $49.99 for premium onboarding.")
]
response = agent_llm.invoke(messages)
print(response.tool_calls)
The key method here is bind_tools(...). That gives the model access to your payment function without hardcoding business logic into prompts.
4) Add policy validation before executing payments
Do not let every tool call go straight to Stripe. Add a gate that checks amount limits, allowed currencies, and whether another agent approved the transaction.
from pydantic import BaseModel, Field
class PaymentRequest(BaseModel):
amount_cents: int = Field(gt=0, le=50000)
currency: str = Field(default="usd")
def approve_payment(request: PaymentRequest, approved_by_risk_agent: bool) -> bool:
allowed_currencies = {"usd", "eur"}
if request.currency not in allowed_currencies:
return False
if not approved_by_risk_agent:
return False
return True
req = PaymentRequest(amount_cents=4999, currency="usd")
if approve_payment(req, approved_by_risk_agent=True):
result = create_payment_intent(req.amount_cents, req.currency)
else:
result = None
In a real multi-agent flow:
- •Billing agent proposes the charge
- •Risk agent approves or rejects it
- •Execution agent calls Stripe only after approval
That keeps payment authority out of free-form LLM behavior.
5) Handle confirmation and status tracking from Stripe
Stripe returns objects with lifecycle states. Your system should persist those states so other agents can react to them later.
def get_payment_status(payment_intent_id: str):
intent = stripe.PaymentIntent.retrieve(payment_intent_id)
return {
"id": intent.id,
"status": intent.status,
"amount": intent.amount,
"currency": intent.currency,
}
# Example usage
status = get_payment_status("pi_123456789")
print(status)
For asynchronous flows like bank transfers or delayed capture cards, use webhooks and update your shared state store when Stripe sends events like payment_intent.succeeded.
Testing the Integration
Run this against Stripe test mode with a test card flow wired into your app. If you only want to verify object creation first, check that the PaymentIntent is created and has a valid ID.
test_intent = create_payment_intent(1500, "usd")
print(test_intent.id)
print(test_intent.status)
Expected output:
pi_XXXXXXXXXXXXXXXXXXXX
requires_payment_method
If you later confirm with a test payment method in your app flow, you should see:
succeeded
Real-World Use Cases
- •
Invoice collection assistant
- •One agent drafts an invoice reminder.
- •Another agent checks customer history.
- •A payment execution agent creates a Stripe PaymentIntent or Invoice payment link only after approval.
- •
Marketplace payout orchestration
- •Seller-support agents validate disputes.
- •Finance agents approve release conditions.
- •Execution agents trigger Stripe payouts or refunds through controlled workflows.
- •
Subscription recovery
- •A retention agent detects failed renewals.
- •A billing agent offers downgrade or retry options.
- •A payments agent updates the customer’s Stripe subscription state through approved actions.
The production pattern is simple: keep LangChain responsible for decisioning and routing, keep Stripe responsible for money movement. In multi-agent systems that separation is what gives you audit trails, policy control, and fewer bad charges.
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