How to Integrate LangChain for payments with Twilio for production AI
Combining LangChain for payments with Twilio gives you a clean path from AI-driven intent to real-world transaction handling and customer messaging. The useful pattern here is simple: let the agent decide what payment action to take, then use Twilio to notify users, confirm OTPs, or send receipt updates in a production-safe flow.
Prerequisites
- •Python 3.10+
- •A LangChain payments integration package or provider configured in your stack
- •A Twilio account with:
- •
TWILIO_ACCOUNT_SID - •
TWILIO_AUTH_TOKEN - •a verified
TWILIO_PHONE_NUMBER
- •
- •A payment provider connected through your LangChain toolchain
- •Environment variables stored securely
- •Basic Flask/FastAPI knowledge if you plan to expose webhooks
Integration Steps
- •
Install the SDKs and wire environment variables
Start by installing the Python packages you need. For Twilio, use the official SDK. For LangChain, install the core package and whichever payments tool or provider adapter your implementation uses.
pip install langchain twilio python-dotenvLoad secrets from environment variables before you instantiate clients:
import os from dotenv import load_dotenv load_dotenv() TWILIO_ACCOUNT_SID = os.getenv("TWILIO_ACCOUNT_SID") TWILIO_AUTH_TOKEN = os.getenv("TWILIO_AUTH_TOKEN") TWILIO_PHONE_NUMBER = os.getenv("TWILIO_PHONE_NUMBER") CUSTOMER_PHONE_NUMBER = os.getenv("CUSTOMER_PHONE_NUMBER") - •
Create the Twilio client for customer notifications
Use Twilio’s official
Clientclass to send SMS confirmations, payment receipts, or OTP messages after the agent completes a payment action.from twilio.rest import Client twilio_client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) message = twilio_client.messages.create( body="Your payment request was received and is being processed.", from_=TWILIO_PHONE_NUMBER, to=CUSTOMER_PHONE_NUMBER, ) print(f"Twilio message SID: {message.sid}")In production, do not send SMS directly inside your model callback. Wrap this in a service layer so retries, idempotency, and audit logging are handled outside the agent.
- •
Define a LangChain tool that represents the payment action
The exact payment integration depends on your provider, but the pattern is stable: expose a tool that your agent can call when it needs to charge, authorize, or verify a payment.
If you’re using LangChain tools directly, define a structured tool around your payment service:
from langchain_core.tools import tool @tool def create_payment_intent(amount_cents: int, currency: str, customer_id: str) -> str: """ Create a payment intent in the downstream payments system. """ # Replace this with your actual payments provider call. # Example: stripe.PaymentIntent.create(...) return f"payment_intent_created:{customer_id}:{amount_cents}:{currency}" - •
Build an agent that can call both payment and messaging tools
Once both tools exist, bind them into an agent workflow. The agent can decide when to create a payment intent and when to notify the customer through Twilio.
from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI from langchain.agents import create_tool_calling_agent, AgentExecutor llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) tools = [create_payment_intent] prompt = ChatPromptTemplate.from_messages([ ("system", "You are a payments assistant. Create payment intents when asked."), ("human", "{input}"), ("placeholder", "{agent_scratchpad}"), ]) agent = create_tool_calling_agent(llm=llm, tools=tools, prompt=prompt) executor = AgentExecutor(agent=agent, tools=tools, verbose=True) result = executor.invoke({ "input": "Create a $25 USD payment intent for customer cus_12345." }) print(result["output"]) - •
Trigger Twilio after the payment step completes
In production, treat Twilio as a downstream side effect after your payment operation succeeds. That keeps failures isolated and makes retries predictable.
def notify_payment_status(phone_number: str, amount_cents: int, currency: str) -> str: msg = twilio_client.messages.create( body=f"Payment of {amount_cents / 100:.2f} {currency.upper()} has been created successfully.", from_=TWILIO_PHONE_NUMBER, to=phone_number, ) return msg.sid
result_text = result["output"] sms_sid = notify_payment_status( phone_number=CUSTOMER_PHONE_NUMBER, amount_cents=2500, currency="usd", )
print(result_text) print(f"SMS sent: {sms_sid}")
## Testing the Integration
Use a small script that exercises both paths: create the LangChain payment action and send a Twilio SMS confirmation.
```python
def test_flow():
payment_result = create_payment_intent(
amount_cents=2500,
currency="usd",
customer_id="cus_12345",
)
sms_sid = twilio_client.messages.create(
body=f"Payment flow complete: {payment_result}",
from_=TWILIO_PHONE_NUMBER,
to=CUSTOMER_PHONE_NUMBER,
).sid
return {"payment_result": payment_result, "sms_sid": sms_sid}
if __name__ == "__main__":
output = test_flow()
print(output)
Expected output:
{
'payment_result': 'payment_intent_created:cus_12345:2500:usd',
'sms_sid': 'SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
}
If this fails in staging first:
- •Check Twilio sender/recipient verification
- •Confirm your environment variables are loaded
- •Verify your payments backend returns an idempotent reference
- •Log both request IDs so you can trace failures end-to-end
Real-World Use Cases
- •
Payment confirmation agents
An AI assistant creates a payment intent or authorization and sends an SMS confirmation through Twilio with next steps or receipt status. - •
Collections and reminder workflows
The agent identifies overdue accounts, triggers a payment action in your backend, then uses Twilio to send reminders or settlement links. - •
Fraud review escalation
When risk rules flag a transaction, the agent pauses automation and sends an OTP or manual review notice via Twilio before releasing funds.
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