# Agentic AI Billing Workflows

This guide explains how to build agentic AI SaaS billing workflows using the Stripe API and AI-driven agents. You'll learn how to provision new customers and subscriptions, respond to subscription lifecycle events using webhooks, and invoke billing actions from an AI agent using the agent toolkit.

## Key Concepts

*   **Agent Toolkit:** A set of tools and libraries that enable AI agents to interact with Stripe. This includes the Model Context Protocol (MCP) server for communication with the Stripe API.
*   **Model Context Protocol (MCP):** A protocol that allows AI agents to interact with the Stripe API and search Stripe's knowledge base.
*   **Agentic AI SaaS Billing:** Automating recurring billing workflows for SaaS products using AI agents.

## Building Agentic Billing Workflows

### 1. Provisioning Customers and Subscriptions

Your AI agent can create new customers and subscriptions within Stripe. This involves using the Stripe API to:

*   **Create a Customer:** Associate customer information (like email and name) with a new Stripe customer object.
*   **Create a Subscription:** Attach a subscription to the customer, specifying the desired price ID.

**Example using Stripe Node.js SDK:**

```javascript
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

async function createSubscription(customerInfo, priceId) {
  // 1. Create or fetch the customer
  const customer = await stripe.customers.create({
    email: customerInfo.email,
    name: customerInfo.name,
  });

  // 2. Create the subscription
  const subscription = await stripe.subscriptions.create({
    customer: customer.id,
    items: [{ price: priceId }],
    expand: ['latest_invoice.payment_intent'],
  });
}
```

For more details on pricing and trial options, refer to the [Build subscriptions documentation](https://stripe.com/docs/billing/subscriptions/build).

### 2. Handling Subscription Lifecycle Events with Webhooks

Webhooks are essential for your AI agent to be notified of events related to subscriptions, such as renewals, cancellations, or payment failures. By setting up webhook endpoints, your agent can react to these events and take appropriate actions.

### 3. Invoking Billing Actions from an AI Agent

The Stripe agent toolkit allows your AI agent to perform various billing actions through function calling. This enables dynamic interactions with Stripe, such as:

*   Creating payment links for new products.
*   Integrating with support workflows to assist customers.
*   Scaffolding test data for development and testing.

The Stripe agent toolkit supports popular AI SDKs like OpenAI's Agents SDK, Vercel's AI SDK, LangChain, and CrewAI. It's compatible with any LLM provider that supports function calling and works with both Python and TypeScript.

**Example using Python and the Stripe Agent Toolkit:**

```python
import asyncio
import os
from agents import Agent, Runner
from stripe_agent_toolkit.openai.toolkit import create_stripe_agent_toolkit

async def main():
    # Initialize toolkit - use restricted key (rk_*) for better security
    toolkit = await create_stripe_agent_toolkit(
        secret_key=os.getenv("STRIPE_SECRET_KEY")
    )
    try:
        agent = Agent(
            name="Stripe Agent",
            instructions="Integrate with Stripe effectively to support business needs.",
            tools=toolkit.get_tools()
        )
        assignment = "Create a payment link for a new product called \"Test\" with a price of $100."
        result = await Runner.run(agent, assignment)
        print(result.final_output)
    finally:
        await toolkit.close()

if __name__ == "__main__":
    asyncio.run(main())
```

## Related Resources

*   [Add Stripe to your agentic workflows](https://stripe.com/docs/agents)
*   [Stripe Agent Toolkit](https://stripe.com/docs/agent-toolkit)
*   [Model Context Protocol (MCP)](https://stripe.com/docs/mcp)
*   [Build subscriptions](https://stripe.com/docs/billing/subscriptions/build)
*   [Webhooks](https://stripe.com/docs/webhooks)