How to Integrate LangChain for lending with Stripe for multi-agent systems
Combining LangChain for lending with Stripe gives you a clean way to turn an agentic lending workflow into something that can actually move money. The useful pattern here is: one agent evaluates the borrower, another agent handles payment collection or disbursement, and Stripe acts as the transaction layer that makes the workflow real.
Prerequisites
- •Python 3.10+
- •A LangChain for lending project set up with your lender-specific tools and prompts
- •A Stripe account with:
- •Secret key
- •Test mode enabled
- •Webhook endpoint configured if you want async payment events
- •Installed packages:
- •
langchain - •
stripe - •
python-dotenv
- •
- •Access to your lending data source:
- •CRM, underwriting API, loan origination system, or a mock dataset for testing
Install the dependencies:
pip install langchain stripe python-dotenv
Integration Steps
- •Set up environment variables and initialize both SDKs.
Keep credentials out of code. Load Stripe first, then wire your lending agent config into LangChain.
import os
from dotenv import load_dotenv
import stripe
load_dotenv()
STRIPE_API_KEY = os.getenv("STRIPE_SECRET_KEY")
stripe.api_key = STRIPE_API_KEY
LENDING_API_KEY = os.getenv("LENDING_API_KEY")
LENDING_BASE_URL = os.getenv("LENDING_BASE_URL")
- •Build the lending agent in LangChain.
For lending systems, the agent usually needs access to underwriting context, repayment rules, and customer profile data. In a production setup, this is where you connect your retriever, tools, or chain.
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a lending operations agent. Decide whether a borrower should be sent to payment collection."),
("human", "Borrower profile: {borrower_profile}\nLoan status: {loan_status}")
])
lending_chain = prompt | llm
If you’re using LangChain tools around your lending stack, this is where you would add retrieval or API calls. The point is that the output should be structured enough for downstream payment actions.
- •Add a Stripe payment action for collections.
For multi-agent systems, don’t let the lending agent call Stripe directly unless that’s the only action it can take. Wrap Stripe in a tool so another orchestrator or policy layer can control execution.
from typing import Dict
def create_stripe_payment_intent(amount_cents: int, currency: str, customer_id: str) -> Dict:
intent = stripe.PaymentIntent.create(
amount=amount_cents,
currency=currency,
customer=customer_id,
automatic_payment_methods={"enabled": True},
metadata={
"source": "lending_agent",
"workflow": "loan_repayment"
}
)
return {
"id": intent["id"],
"status": intent["status"],
"client_secret": intent["client_secret"]
}
This uses Stripe’s real PaymentIntent.create() API. In lending flows, PaymentIntents are better than one-off charges because they support retries and asynchronous confirmation.
- •Orchestrate the two agents in a simple multi-agent flow.
A common pattern is: lending agent decides whether collection is needed; payment agent executes via Stripe if approved by policy.
def run_lending_workflow(borrower_profile: str, loan_status: str, customer_id: str):
decision = lending_chain.invoke({
"borrower_profile": borrower_profile,
"loan_status": loan_status
})
decision_text = decision.content.lower()
if "collect" in decision_text or "payment" in decision_text:
payment_result = create_stripe_payment_intent(
amount_cents=2500,
currency="usd",
customer_id=customer_id
)
return {
"lending_decision": decision.content,
"stripe_result": payment_result
}
return {
"lending_decision": decision.content,
"stripe_result": None
}
In production, replace string matching with structured outputs like JSON schema or Pydantic models. That keeps your orchestration deterministic.
- •Add webhook handling for payment confirmation.
Stripe payments are often asynchronous. If you want your loan servicing state to update correctly, listen for events like payment_intent.succeeded.
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/webhook/stripe", methods=["POST"])
def stripe_webhook():
payload = request.data
sig_header = request.headers.get("Stripe-Signature")
endpoint_secret = os.getenv("STRIPE_WEBHOOK_SECRET")
event = stripe.Webhook.construct_event(
payload=payload,
sig_header=sig_header,
secret=endpoint_secret
)
if event["type"] == "payment_intent.succeeded":
payment_intent = event["data"]["object"]
# Update loan ledger / notify lending system here
print(f"Payment confirmed: {payment_intent['id']}")
return jsonify({"received": True})
That webhook becomes the bridge back into your lending system so repayment state stays consistent.
Testing the Integration
Run a local test with Stripe test mode and a known customer ID from your test environment.
if __name__ == "__main__":
result = run_lending_workflow(
borrower_profile="Borrower has missed 2 payments but has stable income.",
loan_status="delinquent",
customer_id="cus_test123"
)
print(result)
Expected output:
{
'lending_decision': 'Send to collections workflow and request repayment.',
'stripe_result': {
'id': 'pi_123456789',
'status': 'requires_payment_method',
'client_secret': 'pi_123456789_secret_abc'
}
}
If you’re testing webhooks locally, use the Stripe CLI:
stripe listen --forward-to localhost:5000/webhook/stripe
Real-World Use Cases
- •
Automated delinquency handling:
- •One agent reviews repayment risk.
- •Another creates Stripe PaymentIntents for overdue balances.
- •Webhooks update loan servicing state after confirmation.
- •
Loan application fee collection:
- •A LangChain underwriting agent approves an application.
- •A payments agent collects processing fees through Stripe before booking the loan.
- •
Multi-agent servicing workflows:
- •One agent handles borrower communication.
- •One validates repayment eligibility.
- •One executes collections or refunds through Stripe based on policy rules.
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