How to Integrate LangChain for fintech with Stripe for startups
Combining LangChain for fintech with Stripe gives you a clean way to build AI agents that can answer payment questions, inspect transaction state, and trigger billing actions without hardcoding every workflow. For startups, this is useful when you need a support agent that can explain invoices, a finance assistant that checks subscription status, or an ops bot that flags failed payments and takes action.
Prerequisites
- •Python 3.10+
- •A Stripe account with:
- •Secret key
- •Test mode enabled
- •Access to your LangChain for fintech package and API credentials
- •
pipinstalled - •Environment variables set:
- •
STRIPE_API_KEY - •
OPENAI_API_KEYor your model provider key - •Any LangChain for fintech auth token if your setup requires it
- •
Install the core packages:
pip install stripe langchain langchain-openai python-dotenv
If your LangChain for fintech setup uses a dedicated package or internal wrapper, install that too. In most production setups, I keep the Stripe integration thin and let LangChain handle orchestration through tools.
Integration Steps
1) Load configuration and initialize Stripe
Keep keys out of code. Use environment variables and initialize the Stripe client once at startup.
import os
from dotenv import load_dotenv
import stripe
load_dotenv()
stripe.api_key = os.getenv("STRIPE_API_KEY")
if not stripe.api_key:
raise ValueError("Missing STRIPE_API_KEY")
print("Stripe client initialized")
This is the baseline. Everything else in the workflow depends on having a valid Stripe client that can call the API in test mode first.
2) Wrap Stripe operations as LangChain tools
The useful pattern here is to expose Stripe actions as tools that your agent can call. For fintech use cases, start with read-only operations before enabling write actions like refunds or subscription updates.
from langchain_core.tools import tool
import stripe
@tool
def get_customer_by_email(email: str) -> dict:
"""Fetch a Stripe customer by email."""
customers = stripe.Customer.list(email=email, limit=1)
if not customers.data:
return {"found": False}
customer = customers.data[0]
return {
"found": True,
"id": customer.id,
"email": customer.email,
"name": customer.name,
"created": customer.created,
}
@tool
def list_recent_payments(customer_id: str) -> dict:
"""List recent payment intents for a customer."""
payments = stripe.PaymentIntent.list(customer=customer_id, limit=5)
return {
"customer_id": customer_id,
"payments": [
{
"id": p.id,
"amount": p.amount,
"currency": p.currency,
"status": p.status,
}
for p in payments.data
],
}
These are real Stripe SDK calls: stripe.Customer.list(...) and stripe.PaymentIntent.list(...). In production, keep these wrappers narrow and deterministic.
3) Build the LangChain agent around those tools
Now attach the tools to an LLM-backed agent. The agent can decide when to query Stripe based on user input.
from langchain_openai import ChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
tools = [get_customer_by_email, list_recent_payments]
prompt = ChatPromptTemplate.from_messages([
("system", "You are a fintech support assistant. Use Stripe tools when needed."),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
agent = create_tool_calling_agent(llm=llm, tools=tools, prompt=prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
This is the point where LangChain becomes useful for fintech workflows. You are no longer hardcoding every path; you are giving the model controlled access to specific payment operations.
4) Add a write action carefully: create a refund tool
Once read paths work, add one write path with guardrails. Refunds are common in startup support flows, but they should be explicit and audited.
from langchain_core.tools import tool
import stripe
@tool
def refund_payment_intent(payment_intent_id: str, amount: int | None = None) -> dict:
"""Refund a payment intent fully or partially."""
refund_kwargs = {"payment_intent": payment_intent_id}
if amount is not None:
refund_kwargs["amount"] = amount
refund = stripe.Refund.create(**refund_kwargs)
return {
"refund_id": refund.id,
"status": refund.status,
"amount": refund.amount,
"currency": refund.currency,
}
The key method here is stripe.Refund.create(...). In production, gate this behind policy checks:
- •only allow refunds for authenticated support staff
- •only allow amounts under a threshold unless approved
- •log every request and response payload
Then add it to your tool list:
tools.append(refund_payment_intent)
5) Run an end-to-end agent query
At this point the agent can answer billing questions and trigger actions through Stripe.
result = executor.invoke({
"input": "Find the customer john@startup.com and show recent payments."
})
print(result["output"])
If you want to make it more operational, route queries like “refund the last failed charge” into the refund tool after confirming policy rules in your application layer.
Testing the Integration
Use test mode data in Stripe and verify both retrieval and action paths. Here is a simple smoke test:
test_email = "john@startup.com"
customer_result = get_customer_by_email.invoke({"email": test_email})
print(customer_result)
if customer_result["found"]:
payments_result = list_recent_payments.invoke({"customer_id": customer_result["id"]})
print(payments_result)
Expected output:
{'found': True, 'id': 'cus_12345', 'email': 'john@startup.com', 'name': 'John Doe', 'created': 1710000000}
{'customer_id': 'cus_12345', 'payments': [{'id': 'pi_abc123', 'amount': 4900, 'currency': 'usd', 'status': 'succeeded'}]}
If you test refunds in sandbox mode:
refund_result = refund_payment_intent.invoke({"payment_intent_id": "pi_abc123"})
print(refund_result)
Expected output:
{'refund_id': 're_12345', 'status': 'succeeded', 'amount': 4900, 'currency': 'usd'}
Real-World Use Cases
- •
Billing support agent
- •Looks up customers by email
- •Checks recent charges or payment intents
- •Explains invoice status in plain language
- •
Finance ops copilot
- •Detects failed payments from Stripe data
- •Summarizes churn risk for subscriptions
- •Creates refunds after approval checks
- •
Founder dashboard assistant
- •Answers questions like “Who paid us today?”
- •Pulls revenue snapshots from Stripe objects
- •Turns raw payment data into readable summaries for non-finance users
For startups building AI agents around money movement, this pattern keeps the model useful without giving it broad system access. Keep Stripe wrapped in small tools, let LangChain orchestrate them, and put policy enforcement outside the model where it belongs.
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