How to Integrate LangChain for payments with Twilio for multi-agent systems
Combining LangChain for payments with Twilio gives you a clean way to build agent systems that can both reason about payment flows and communicate with users over SMS, WhatsApp, or voice. That matters when you need a payment agent to confirm charges, collect approvals, send receipts, or escalate to a human without leaving the workflow.
In practice, this lets one agent handle payment intent and policy checks while another agent handles customer messaging through Twilio. The result is a multi-agent system that can move from “customer asked to pay” to “payment initiated” to “confirmation sent” with less glue code.
Prerequisites
- •Python 3.10+
- •A Twilio account with:
- •
TWILIO_ACCOUNT_SID - •
TWILIO_AUTH_TOKEN - •A verified phone number or messaging-enabled sender
- •
- •Access to your LangChain payments provider setup
- •Installed packages:
- •
langchain - •
twilio - •any LangChain payment integration package your provider requires
- •
- •Environment variables configured in
.env - •A webhook endpoint if you want inbound Twilio messages routed back into your agent system
Install the core packages:
pip install langchain twilio python-dotenv
Integration Steps
- •
Initialize both SDKs
Start by loading secrets and creating clients for payment operations and messaging. Keep these in separate modules in production so your agents don’t share concerns.
import os
from dotenv import load_dotenv
from twilio.rest import Client as TwilioClient
load_dotenv()
TWILIO_ACCOUNT_SID = os.getenv("TWILIO_ACCOUNT_SID")
TWILIO_AUTH_TOKEN = os.getenv("TWILIO_AUTH_TOKEN")
TWILIO_FROM_NUMBER = os.getenv("TWILIO_FROM_NUMBER")
twilio_client = TwilioClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
For LangChain payments, the exact client depends on the provider you’ve connected through LangChain. The pattern is the same: initialize the payment tool or chain once, then expose it to your agents.
from langchain.tools import tool
@tool
def create_payment_intent(amount: int, currency: str = "usd") -> str:
# Replace this with your actual LangChain payments provider call.
# Example shape: payment_client.create_payment_intent(...)
return f"payment_intent_created:{amount}:{currency}"
- •
Create a payment agent tool
Your payment agent should only do one thing: translate intent into a payment action. Keep it deterministic and return structured output so another agent can consume it.
from langchain_core.tools import tool
@tool
def initiate_payment(customer_id: str, amount_cents: int) -> dict:
"""
Create a payment request and return data the messaging agent can use.
"""
# Replace with actual LangChain payments SDK call.
# Example:
# result = payments_client.payment_intents.create(
# customer_id=customer_id,
# amount=amount_cents,
# currency="usd",
# )
result = {
"payment_id": f"pay_{customer_id}_{amount_cents}",
"status": "requires_confirmation",
"amount_cents": amount_cents,
"currency": "usd",
}
return result
If you’re using a LangChain orchestration layer, register this tool with your agent so it can be called when the user asks to pay an invoice or approve a charge.
- •
Add a Twilio messaging tool for confirmations
Once the payment step returns an ID or status, send a message through Twilio. This is where multi-agent coordination pays off: one agent handles money movement, another handles communication.
def send_payment_confirmation(to_number: str, payment_id: str, amount_cents: int) -> str:
message_body = (
f"Payment request created.\n"
f"Payment ID: {payment_id}\n"
f"Amount: ${amount_cents / 100:.2f}\n"
f"Reply YES to approve."
)
message = twilio_client.messages.create(
body=message_body,
from_=TWILIO_FROM_NUMBER,
to=to_number,
)
return message.sid
This keeps outbound notifications simple. If you later add WhatsApp or voice callbacks, you only change the transport layer in this function.
- •
Wire the agents together
In a real multi-agent system, one orchestrator routes work between agents based on state. Here’s a minimal Python flow that calls the payment tool first and then uses Twilio to notify the user.
def process_payment_flow(customer_id: str, phone_number: str, amount_cents: int):
payment_result = initiate_payment.invoke({
"customer_id": customer_id,
"amount_cents": amount_cents,
})
if payment_result["status"] == "requires_confirmation":
sid = send_payment_confirmation(
to_number=phone_number,
payment_id=payment_result["payment_id"],
amount_cents=payment_result["amount_cents"],
)
return {
"payment_result": payment_result,
"twilio_message_sid": sid,
}
return {"payment_result": payment_result}
That invoke() call is the key LangChain pattern here. It keeps your tool invocation consistent whether you call it from an orchestrator, an API route, or another agent.
- •
Handle inbound replies from Twilio
For approval-based flows, wire a webhook that receives SMS replies like
YESorNO. The webhook can forward the response into your orchestration layer and trigger capture or cancellation.
from flask import Flask, request, Response
app = Flask(__name__)
@app.post("/twilio/inbound")
def inbound_sms():
body = request.form.get("Body", "").strip().upper()
from_number = request.form.get("From", "")
if body == "YES":
# Replace with actual capture call in your LangChain payments flow.
result = {"status": "captured", "user": from_number}
reply = "Payment approved and captured."
else:
result = {"status": "cancelled", "user": from_number}
reply = "Payment cancelled."
twiml = f"<Response><Message>{reply}</Message></Response>"
return Response(twiml, mimetype="application/xml")
This gives you closed-loop automation: outbound approval request, inbound confirmation, then final settlement action.
Testing the Integration
Use a dry-run script first so you can verify tool wiring before hitting live endpoints.
if __name__ == "__main__":
output = process_payment_flow(
customer_id="cust_123",
phone_number="+15551234567",
amount_cents=2599,
)
print(output)
Expected output:
{
'payment_result': {
'payment_id': 'pay_cust_123_2599',
'status': 'requires_confirmation',
'amount_cents': 2599,
'currency': 'usd'
},
'twilio_message_sid': 'SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}
If you’re not seeing a valid Twilio SID:
- •Check sender number formatting
- •Confirm sandbox vs production messaging rules
- •Verify webhook URLs are reachable over HTTPS
- •Confirm your payments provider credentials are loaded correctly
Real-World Use Cases
- •
Invoice approval agents
- •One agent creates or validates the charge.
- •Another sends SMS approval requests and captures replies before settlement.
- •
Collections workflows
- •A payments agent checks outstanding balances.
- •A Twilio agent sends reminder sequences and escalates delinquent accounts to human reps.
- •
Insurance billing assistants
- •A policy service agent calculates premium adjustments.
- •A messaging agent sends policyholder confirmations and receipt links over SMS or WhatsApp.
The pattern is straightforward: keep money logic inside the payments agent, keep user communication inside Twilio-facing agents, and connect them through explicit state transitions. That separation makes retries safer, auditing easier, and production incidents less painful.
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