How to Integrate LangChain for lending with Stripe for AI agents
Combining LangChain for lending with Stripe gives you a clean path from AI-driven loan workflows to actual payment rails. The practical use case is straightforward: an agent can qualify a borrower, generate repayment schedules, and then collect deposits, fees, or installment payments through Stripe without human handoff.
Prerequisites
- •Python 3.10+
- •A Stripe account with:
- •Secret key
- •Webhook signing secret
- •Test mode enabled
- •Access to your lending stack that exposes borrower, loan, or underwriting data
- •LangChain installed in your project
- •An LLM provider configured for LangChain
- •
stripePython SDK installed - •Environment variables set:
- •
STRIPE_API_KEY - •
STRIPE_WEBHOOK_SECRET - •
OPENAI_API_KEYor another model provider key
- •
- •A backend service that can receive Stripe webhooks
Integration Steps
- •Install the dependencies.
pip install langchain langchain-openai stripe python-dotenv fastapi uvicorn
- •Build the lending agent with LangChain.
For lending workflows, keep the agent focused on structured outputs: borrower status, approved amount, repayment cadence, and payment action. The agent should not “decide” payments in free text; it should return data your app can safely turn into Stripe calls.
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import JsonOutputParser
load_dotenv()
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a lending operations assistant. Return valid JSON only."),
("user", """
Borrower: {borrower_name}
Loan amount: {loan_amount}
Term months: {term_months}
Action needed: create a repayment plan and indicate whether a payment intent should be created.
Return keys:
- approved: boolean
- monthly_payment_cents: integer
- create_payment_intent: boolean
- reason: string
""")
])
parser = JsonOutputParser()
chain = prompt | llm | parser
result = chain.invoke({
"borrower_name": "Amina Patel",
"loan_amount": 120000,
"term_months": 12,
})
print(result)
- •Create the Stripe payment object from the agent output.
Use the agent’s structured response to decide whether to create a PaymentIntent. In lending systems, this is useful for collecting application fees, down payments, or first installment charges.
import os
import stripe
stripe.api_key = os.environ["STRIPE_API_KEY"]
def create_repayment_payment_intent(amount_cents: int, customer_id: str):
intent = stripe.PaymentIntent.create(
amount=amount_cents,
currency="usd",
customer=customer_id,
automatic_payment_methods={"enabled": True},
metadata={
"product": "loan_repayment",
"source": "langchain_lending_agent",
},
)
return intent
agent_output = {
"approved": True,
"monthly_payment_cents": 11250,
"create_payment_intent": True,
"reason": "Borrower qualifies for standard repayment plan."
}
if agent_output["create_payment_intent"]:
payment_intent = create_repayment_payment_intent(
amount_cents=agent_output["monthly_payment_cents"],
customer_id="cus_123456789"
)
print(payment_intent["id"])
- •Wire Stripe webhooks back into your lending workflow.
This is where the integration becomes production-grade. Your app should listen for successful payments and update the loan ledger, repayment status, and next due date.
from fastapi import FastAPI, Request, HTTPException
import stripe
import os
app = FastAPI()
stripe.api_key = os.environ["STRIPE_API_KEY"]
endpoint_secret = os.environ["STRIPE_WEBHOOK_SECRET"]
@app.post("/webhooks/stripe")
async def stripe_webhook(request: Request):
payload = await request.body()
sig_header = request.headers.get("stripe-signature")
try:
event = stripe.Webhook.construct_event(
payload=payload,
sig_header=sig_header,
secret=endpoint_secret,
)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid payload")
except stripe.error.SignatureVerificationError:
raise HTTPException(status_code=400, detail="Invalid signature")
if event["type"] == "payment_intent.succeeded":
payment_intent = event["data"]["object"]
loan_id = payment_intent["metadata"].get("loan_id")
# Update your lending database here.
print(f"Payment succeeded for loan {loan_id}: {payment_intent['id']}")
return {"received": True}
- •Connect the full flow end-to-end.
The pattern is:
- •LangChain evaluates borrower context
- •Your app maps the result to a Stripe action
- •Stripe confirms payment state through webhooks
- •Your lending system updates balances and schedules
def process_borrower(borrower):
decision = chain.invoke({
"borrower_name": borrower["name"],
"loan_amount": borrower["loan_amount"],
"term_months": borrower["term_months"],
})
if not decision["approved"]:
return {"status": "rejected", "reason": decision["reason"]}
if decision["create_payment_intent"]:
intent = stripe.PaymentIntent.create(
amount=decision["monthly_payment_cents"],
currency="usd",
customer=borrower["stripe_customer_id"],
metadata={
"loan_id": borrower["loan_id"],
"borrower_name": borrower["name"],
},
)
return {
"status": "payment_created",
"payment_intent_id": intent.id,
"amount_cents": decision["monthly_payment_cents"],
}
return {"status": "approved_no_charge"}
print(process_borrower({
"name": "Amina Patel",
"loan_amount": 120000,
"term_months": 12,
"stripe_customer_id": "cus_123456789",
"loan_id": "loan_001"
}))
Testing the Integration
Run a local test by invoking the chain and creating a test-mode PaymentIntent. You should see a valid Stripe object ID and a JSON decision from the agent.
test_borrower = {
"name": "Jordan Lee",
"loan_amount": 50000,
"term_months": 6,
}
decision = chain.invoke(test_borrower)
print("Agent decision:", decision)
if decision.get("approved"):
intent = stripe.PaymentIntent.create(
amount=decision["monthly_payment_cents"],
currency="usd",
customer="cus_test_123",
metadata={"loan_id": "loan_test_001"},
)
print("Stripe PaymentIntent:", intent.id)
Expected output:
Agent decision: {'approved': True, 'monthly_payment_cents': 8500, 'create_payment_intent': True, 'reason': 'Borrower qualifies for a short-term repayment plan.'}
Stripe PaymentIntent: pi_3NfExample123456789
Real-World Use Cases
- •Loan origination fees: Have the agent assess eligibility and collect application or processing fees through Stripe before underwriting continues.
- •Automated installment collection: Use LangChain to generate repayment plans and Stripe to charge recurring installments tied to loan metadata.
- •Collections workflows: Let the agent detect missed payments from webhook events and trigger follow-up actions like reminders, retries, or hardship review.
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