How to Integrate LangChain for payments with Stripe for AI agents

By Cyprian AaronsUpdated 2026-04-21
langchain-for-paymentsstripeai-agents

LangChain for payments gives your agent the ability to reason about pricing, plans, and purchase flows. Stripe handles the actual money movement, customer records, and payment confirmation, which is what you want when an AI agent needs to sell a subscription, charge for usage, or collect a one-time fee.

Prerequisites

  • Python 3.10+
  • A Stripe account with:
    • STRIPE_SECRET_KEY
    • a Price ID or Product setup in Stripe
  • A LangChain environment configured for tool use
  • Installed packages:
    • langchain
    • langchain-openai
    • stripe
  • An OpenAI API key if you’re using an LLM-backed agent
  • A webhook endpoint if you want asynchronous payment confirmation

Integration Steps

  1. Install the dependencies.
pip install langchain langchain-openai stripe python-dotenv
  1. Configure your environment variables.
import os
from dotenv import load_dotenv

load_dotenv()

os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "")
os.environ["STRIPE_SECRET_KEY"] = os.getenv("STRIPE_SECRET_KEY", "")
  1. Create a Stripe payment helper that your LangChain agent can call.

Use Stripe’s Python SDK directly for payment intent creation. In production, this is the cleanest path because you keep payment logic deterministic and auditable.

import stripe

stripe.api_key = os.environ["STRIPE_SECRET_KEY"]

def create_payment_intent(amount_cents: int, currency: str = "usd", customer_email: str | None = None):
    params = {
        "amount": amount_cents,
        "currency": currency,
        "automatic_payment_methods": {"enabled": True},
        "metadata": {
            "source": "langchain_agent",
        },
    }

    if customer_email:
        params["receipt_email"] = customer_email

    intent = stripe.PaymentIntent.create(**params)
    return {
        "id": intent.id,
        "client_secret": intent.client_secret,
        "status": intent.status,
    }
  1. Wrap the Stripe function as a LangChain tool.

This lets the agent decide when to charge, but keeps the actual charge operation inside a controlled function.

from langchain_core.tools import tool

@tool
def charge_customer(amount_cents: int, currency: str = "usd", customer_email: str | None = None) -> dict:
    """Create a Stripe PaymentIntent for an AI agent payment flow."""
    return create_payment_intent(
        amount_cents=amount_cents,
        currency=currency,
        customer_email=customer_email,
    )
  1. Wire the tool into a LangChain agent.

Here I’m using ChatOpenAI plus create_tool_calling_agent and AgentExecutor. This is the standard pattern when you want an LLM to choose when to invoke Stripe-backed tools.

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)

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a billing assistant. Use tools to create payment intents only when the user confirms purchase."),
    ("human", "{input}"),
])

tools = [charge_customer]
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

result = executor.invoke({
    "input": "The user confirmed they want to buy the $19 onboarding package. Charge them."
})

print(result)

If you need subscriptions instead of one-time charges, swap PaymentIntent.create for stripe.Subscription.create and map it into another LangChain tool.

@tool
def start_subscription(customer_id: str, price_id: str) -> dict:
    """Create a Stripe subscription for recurring billing."""
    subscription = stripe.Subscription.create(
        customer=customer_id,
        items=[{"price": price_id}],
        collection_method="charge_automatically",
        expand=["latest_invoice.payment_intent"],
    )
    return {
        "id": subscription.id,
        "status": subscription.status,
        "latest_invoice_id": subscription.latest_invoice.id if subscription.latest_invoice else None,
    }

Testing the Integration

Run a direct tool call first before putting the LLM in front of it. That isolates Stripe setup issues from agent behavior.

if __name__ == "__main__":
    test_result = charge_customer.invoke({
        "amount_cents": 1900,
        "currency": "usd",
        "customer_email": "test@example.com",
    })
    print(test_result)

Expected output:

{
  'id': 'pi_3Qxxxxxxx',
  'client_secret': 'pi_3Qxxxxxxx_secret_xxxxx',
  'status': 'requires_payment_method'
}

That status is normal. It means Stripe created the PaymentIntent successfully and is waiting for a payment method to complete it.

Real-World Use Cases

  • Paid AI workflows
    • Charge users before running expensive document processing, legal review, or insurance quote generation.
  • Subscription-based agents
    • Let an AI assistant upgrade customers from free support to premium plans using recurring Stripe subscriptions.
  • Usage-based billing
    • Meter agent actions like token-heavy research runs or underwriting checks and bill per completed job.

If you’re building this for production, keep these rules tight:

  • Never let the model decide amount math without validation.
  • Keep all Stripe keys server-side.
  • Use webhooks to confirm successful payments before unlocking premium actions.
  • Log every tool invocation with request IDs and user identity.

Keep learning

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

Related Guides