# How to Build a Billing System for AI SaaS Products

> A step-by-step guide to building billing infrastructure for AI SaaS products - from choosing pricing models and metering usage to credit entitlements, subscription lifecycle, and customer-facing billing UI.
- **Author**: Ayush Agarwal
- **Published**: 2026-04-11
- **Category**: AI, Billing, Engineering
- **URL**: https://dodopayments.com/blogs/build-billing-system-ai-saas

---

Most AI SaaS founders underestimate billing complexity until it blocks their launch. You build an LLM wrapper, an image generation API, or an AI coding assistant, and then realize you need to charge per token, handle credit balances, manage subscriptions across 50 countries, and reconcile usage data at the end of every billing cycle. The billing system becomes harder than the product itself.

This guide walks you through building a production-grade billing system for AI SaaS products in seven steps. Each step includes architecture decisions, code examples using Dodo Payments, and references to documentation you can follow along with.

```mermaid
flowchart LR
    A["Pricing
Model"] -->|"Products & plans"| B["Billing
Infrastructure"]
    B -->|"Events API"| C["Usage
Metering"]
    C -->|"Deductions"| D["Credit
Entitlements"]
    B -->|"Recurring charges"| E["Subscription
Lifecycle"]
    D --> F["Customer
Billing UI"]
    E --> F
    F -->|"Analytics"| G["Monitor &
Optimize"]
```

## Step 1: Choose Your Pricing Model

The pricing model you pick in month one constrains your flexibility in year two. AI products have unique cost structures - variable inference costs, model-specific pricing tiers, and consumption patterns that don't fit neatly into flat-rate subscriptions. Before writing any billing code, map your cost structure to a pricing model.

Here is a decision matrix for the five common AI SaaS pricing models:

| Model            | How it works                                | Best for                             | Example                                          |
| ---------------- | ------------------------------------------- | ------------------------------------ | ------------------------------------------------ |
| **Per-token**    | Charge per input/output token consumed      | LLM APIs, text generation            | $0.01 per 1K tokens                              |
| **Per-request**  | Flat fee per API call regardless of size    | Image generation, translation APIs   | $0.05 per request                                |
| **Credit-based** | Sell credit packs; usage deducts credits    | Multi-model platforms, AI assistants | 100 credits/month, 1 image = 10 credits          |
| **Subscription** | Fixed monthly/annual fee with feature gates | Productivity tools, AI writing apps  | $29/month Pro plan                               |
| **Hybrid**       | Base subscription + usage overage           | Most AI SaaS at scale                | $49/month includes 10K tokens, then $0.002/token |

Most successful AI products land on hybrid pricing. A base subscription provides predictable revenue, while [usage-based components](https://dodopayments.com/blogs/subscriptions-usage-based-billing-saas) align cost with value delivered. Credit-based models work well when you want to abstract away the underlying cost differences between models or operations.

> The billing model you choose in month one will constrain your pricing flexibility in year two. Build on infrastructure that supports subscriptions, usage, credits, and hybrid models from the start.
>
> \- Ayush Agarwal, Co-founder & CPTO at Dodo Payments

**Key decision**: If your AI product uses multiple models with different costs (GPT-4 vs GPT-4o-mini, Claude Opus vs Sonnet), credit-based billing lets you assign different credit weights per operation without exposing raw token costs to customers. This is how [Cursor and similar AI tools](https://dodopayments.com/blogs/charge-users-claude-code-project) handle multi-model pricing.

## Step 2: Set Up Your Billing Infrastructure

Once you have a pricing model, you need infrastructure to create products, set prices, and process payments. Building this from scratch means handling payment processing, tax compliance in 50+ jurisdictions, currency conversion, fraud detection, and PCI compliance. A [Merchant of Record](https://dodopayments.com/blogs/what-is-a-merchant-of-record) handles all of this so you can focus on your AI product.

With [Dodo Payments](https://dodopayments.com), you create products in the dashboard or via API. Each product has a pricing type: one-time, subscription, or [usage-based](https://docs.dodopayments.com/features/usage-based-billing/introduction).

**Create your first product via the SDK:**

```typescript
import DodoPayments from "dodopayments";

const client = new DodoPayments({
  bearerToken: process.env["DODO_PAYMENTS_API_KEY"],
});

// Create a subscription product for your AI Pro plan
const product = await client.products.create({
  name: "AI Pro Plan",
  description: "Pro tier with 50K tokens/month and priority model access",
  price: {
    currency: "USD",
    type: "recurring",
    billing_period: "monthly",
    unit_amount: 4900, // $49.00
  },
  tax_category: "saas",
});
```

**Set up checkout for your product:**

Use the [overlay checkout](https://docs.dodopayments.com/developer-resources/overlay-checkout) or [inline checkout](https://docs.dodopayments.com/developer-resources/inline-checkout) to handle the payment flow. The overlay is faster to integrate; the inline version gives you full control over the checkout experience.

```typescript
import { DodoPayments } from "dodopayments-checkout";

DodoPayments.Initialize({
  mode: "live",
  displayType: "overlay",
  onEvent: (event) => {
    if (event.type === "checkout.payment_succeeded") {
      // Provision access to AI features
      activateSubscription(event.data.customer_id);
    }
  },
});

// Open checkout when user clicks "Upgrade to Pro"
DodoPayments.Checkout.open({
  checkoutUrl: checkoutSession.url,
});
```

Dodo Payments acts as the [Merchant of Record](https://dodopayments.com/blogs/indie-hackers-lose-revenue-without-merchant-of-record), which means it is the legal seller on every transaction. Sales tax, VAT, and GST across [220+ countries](https://dodopayments.com/blogs/global-billing) are calculated and remitted automatically. You don't need to register for tax in each jurisdiction or worry about [sales tax compliance](https://dodopayments.com/blogs/us-sales-tax-saas).

## Step 3: Implement Usage Metering

This is where AI billing gets interesting. Every LLM call, image generation, or API request needs to be tracked, aggregated, and billed. Dodo Payments provides [meters](https://docs.dodopayments.com/features/usage-based-billing/meters) that aggregate raw events into billable quantities.

**Create a meter for token tracking:**

In the Dodo Payments dashboard, navigate to Products, then Meters, then Create Meter. Configure:

- **Event name**: `llm.completion`
- **Aggregation**: `sum`
- **Over property**: `totalTokens`

This meter sums the `totalTokens` property across all events named `llm.completion` for each customer per billing cycle.

**Send usage events from your application:**

```typescript
// Manual event ingestion for custom metering
await client.usageEvents.ingest({
  events: [
    {
      event_id: `llm_${Date.now()}_${crypto.randomUUID()}`,
      customer_id: "cus_abc123",
      event_name: "llm.completion",
      timestamp: new Date().toISOString(),
      metadata: {
        model: "gpt-4o",
        inputTokens: "850",
        outputTokens: "1200",
        totalTokens: "2050",
      },
    },
  ],
});
```

**Use the LLM Ingestion Blueprint for automatic tracking:**

Instead of manually constructing events, the [LLM Ingestion Blueprint](https://docs.dodopayments.com/developer-resources/ingestion-blueprints/llm) wraps your LLM client and tracks token usage automatically. It supports OpenAI, Anthropic, Groq, Google Gemini, and the Vercel AI SDK.

```typescript
import { createLLMTracker } from "@dodopayments/ingestion-blueprints";
import OpenAI from "openai";

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const tracker = createLLMTracker({
  apiKey: process.env.DODO_PAYMENTS_API_KEY,
  environment: "live_mode",
  eventName: "llm.completion", // matches your meter
});

const client = tracker.wrap({
  client: openai,
  customerId: "cus_abc123",
});

// Every call is now automatically metered
const response = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Explain quantum computing" }],
});
// Token usage sent to Dodo Payments automatically
```

For [API monetization](https://dodopayments.com/blogs/api-monetization) scenarios, the API Gateway Blueprint tracks per-request billing. For storage or streaming products, there are [additional blueprints](https://docs.dodopayments.com/features/usage-based-billing/ingestion-blueprints) covering object storage, streaming bandwidth, and compute time.

Read the full [usage-based billing integration guide](https://docs.dodopayments.com/developer-resources/usage-based-billing-guide) for detailed setup instructions.

## Step 4: Add Credit Entitlements

Credit-based billing is the preferred model for AI products with multiple operation types. Instead of exposing raw token costs, you sell credit packs and assign different credit weights to different operations. An image generation might cost 10 credits while a text completion costs 1 credit. Customers see a single balance rather than per-model pricing.

**How credit deduction works with meters:**

1. Your application sends usage events (same as Step 3)
2. Meters aggregate events into quantities
3. A background worker converts meter units to credits using your configured rate
4. Credits are deducted from the customer's balance using FIFO ordering (oldest grants first)
5. If credits run out and overage is enabled, usage continues and overage is billed at cycle end

**Configure credits on a product:**

In the Dodo Payments dashboard, create a credit entitlement under Products, then Credits. Define:

- **Credit name**: "AI Credits"
- **Unit**: credits
- **Amount per cycle**: 1000
- **Expiry**: end of billing cycle
- **Rollover**: allow up to 500 unused credits to carry forward
- **Overage**: enabled at $0.01 per credit

Then attach the credit entitlement to your subscription product and link your meters to deduct from it. Toggle "Bill usage in Credits" on the meter configuration and set the conversion rate (e.g., 1000 tokens = 1 credit).

**Multiple meters sharing one credit pool:**

You can link multiple meters to the same credit entitlement. This is how AI platforms with different operation types work:

| Meter              | Operation       | Credits per unit        |
| ------------------ | --------------- | ----------------------- |
| `text.completion`  | Text generation | 1 credit per 1K tokens  |
| `image.generation` | Image creation  | 10 credits per image    |
| `code.completion`  | Code assistance | 2 credits per 1K tokens |

All three meters deduct from the same "AI Credits" pool. The customer sees one unified balance in their portal.

**Listen for credit lifecycle events via [webhooks](https://docs.dodopayments.com/developer-resources/webhooks):**

```typescript
// Webhook handler for credit events
app.post("/webhooks/dodo", async (req, res) => {
  const event = req.body;

  switch (event.type) {
    case "credit.balance_low":
      // Alert customer their credits are running low
      await sendCreditLowEmail(
        event.data.customer_id,
        event.data.available_balance,
        event.data.threshold_amount,
      );
      break;

    case "credit.deducted":
      // Update local cache of credit balance
      await updateLocalBalance(
        event.data.customer_id,
        event.data.balance_after,
      );
      break;

    case "credit.overage_charged":
      // Log overage for analytics
      await logOverageEvent(event.data.customer_id, event.data.amount);
      break;
  }

  res.status(200).send("OK");
});
```

See the full [credit-based billing documentation](https://docs.dodopayments.com/features/credit-based-billing) for configuration details and the [credit webhook reference](https://docs.dodopayments.com/developer-resources/webhooks/intents/credit) for all available events.

## Step 5: Handle Subscription Lifecycle

Subscriptions are the revenue backbone of most AI SaaS products. Beyond initial signup, you need to handle plan changes, trial periods, payment failures, and cancellations gracefully. Getting this wrong causes [revenue leakage](https://dodopayments.com/blogs/revenue-leakage-saas) and involuntary churn.

**Plan changes (upgrades and downgrades):**

When a customer outgrows their current tier, you need to move them to a higher plan with fair billing. Dodo Payments supports four [proration modes](https://docs.dodopayments.com/developer-resources/subscription-upgrade-downgrade):

```typescript
// Upgrade customer from Basic to Pro with prorated billing
await client.subscriptions.changePlan("sub_xyz789", {
  product_id: "prod_pro_plan",
  quantity: 1,
  proration_billing_mode: "prorated_immediately",
});
// Customer is charged the prorated difference for remaining cycle days
```

| Proration mode           | Upgrade behavior           | Downgrade behavior      | Best for                |
| ------------------------ | -------------------------- | ----------------------- | ----------------------- |
| `prorated_immediately`   | Charge prorated difference | Credit remaining value  | Fair time-based billing |
| `difference_immediately` | Charge price difference    | Credit price difference | Simple math             |
| `full_immediately`       | Charge full new price      | No credit               | Billing cycle resets    |
| `do_not_bill`            | No charge                  | No credit               | Free migrations         |

**Dunning and failed payment recovery:**

Failed payments are the biggest source of involuntary churn for [subscription businesses](https://dodopayments.com/blogs/best-subscription-billing-software). Dodo Payments automatically retries failed charges with smart scheduling and sends recovery emails to customers. Monitor the `payment.failed` and `subscription.on_hold` webhook events to take additional action:

```typescript
app.post("/webhooks/dodo", async (req, res) => {
  const event = req.body;

  if (event.type === "payment.failed") {
    // Downgrade to free tier after grace period
    await scheduleGracePeriod(event.data.customer_id, {
      days: 7,
      action: "downgrade_to_free",
    });
  }

  if (event.type === "subscription.active") {
    // Payment recovered - restore full access
    await restoreFullAccess(event.data.customer_id);
  }

  res.status(200).send("OK");
});
```

For more on [subscription pricing strategy](https://dodopayments.com/blogs/subscription-pricing-models), read our guide on choosing between one-time and recurring models.

## Step 6: Build Customer-Facing Billing UI

Your customers need a way to view their usage, manage subscriptions, update payment methods, and download invoices. Building these interfaces from scratch takes weeks. The [BillingSDK](https://docs.dodopayments.com/developer-resources/billingsdk) provides pre-built React components that handle all of this.

**Install and add components:**

```bash
# Install BillingSDK CLI
npm install @billingsdk/cli

# Add components to your project
npx @billingsdk/cli add billing-screen
npx @billingsdk/cli add billing-settings
```

**Available components:**

| Component                  | What it does                                                           |
| -------------------------- | ---------------------------------------------------------------------- |
| **Pricing Tables**         | Display your plans with feature comparison (1, 2, or 3-column layouts) |
| **Subscription Dashboard** | Show active subscriptions with plan details and renewal dates          |
| **Usage Meters**           | Linear and circular progress indicators for credit/quota tracking      |
| **Plan Updates**           | Upgrade/downgrade flows with confirmation dialogs                      |
| **Invoice History**        | Customer invoice display and download                                  |
| **Cancellation Flow**      | Retention-optimized cancellation with feedback collection              |
| **Payment Methods**        | Secure payment method management                                       |

These components are built on shadcn/ui primitives, so they integrate with your existing design system. They connect to Dodo Payments APIs under the hood, so usage data, subscription status, and invoice history are always current.

For AI products, the usage meter components are especially useful. Customers can see their credit balance, consumption rate, and projected usage before hitting their limit. This transparency reduces support tickets and increases upgrade conversions.

## Step 7: Monitor and Optimize

Shipping your billing system is the beginning, not the end. You need visibility into revenue health, usage patterns, and churn signals to optimize pricing and reduce leakage.

**Key metrics to track:**

- **MRR and ARR**: Track growth trends month over month. Sudden drops signal churn or failed payment issues
- **Usage distribution**: Identify customers approaching plan limits (upgrade opportunities) and those barely using their allocation (churn risk)
- **Credit consumption rate**: If customers consistently exhaust credits before cycle end, your pricing may be too aggressive
- **Failed payment rate**: Monitor recovery rates across payment methods and regions
- **Overage revenue**: Track how much revenue comes from overage charges vs base subscriptions

The Dodo Payments dashboard provides [usage-based billing analytics](https://docs.dodopayments.com/developer-resources/usage-based-billing-guide) with meter quantity charts, event tables, and activity metrics. Use these to spot patterns:

- **Customers with zero usage** in the last 30 days are likely to churn. Trigger re-engagement campaigns
- **Customers hitting credit limits early** every cycle are upgrade candidates. Send targeted upgrade offers
- **High overage customers** may prefer a higher tier with more included credits at a better per-unit rate

> Subscription fatigue is real, but recurring revenue is still the best model for SaaS. The solution is not to abandon subscriptions. It is to add usage-based components that align cost with value delivered.
>
> \- Rishabh Goel, Co-founder & CEO at Dodo Payments

**Webhook-driven alerting:**

Build automated alerts using webhook events. Combine `credit.balance_low`, `payment.failed`, and `subscription.on_hold` events to create a real-time churn risk dashboard. When a customer's credit balance drops below 20% and they have a failed payment on file, that is a high-priority retention case.

For a deeper look at preventing revenue loss, see our guide on [revenue leakage in SaaS](https://dodopayments.com/blogs/revenue-leakage-saas) and [common pricing mistakes founders make](https://dodopayments.com/blogs/top-pricing-mistakes-founders-make).

## Putting It All Together

Here is the complete billing architecture for a typical AI SaaS product:

```mermaid
flowchart TD
    subgraph App ["Your AI Application"]
        A["User sends prompt"] --> B["LLM processes request"]
        B --> C["Return response to user"]
    end

    subgraph Metering ["Usage Metering"]
        B -->|"LLM Blueprint wraps client"| D["Track tokens automatically"]
        D -->|"Events API"| E["Dodo Payments Meters"]
    end

    subgraph Billing ["Billing Engine"]
        E -->|"Aggregate usage"| F{"Credit-based?"}
        F -->|"Yes"| G["Deduct from credit balance"]
        F -->|"No"| H["Calculate per-unit charge"]
        G --> I["End-of-cycle invoice"]
        H --> I
    end

    subgraph Lifecycle ["Subscription Management"]
        J["Plan changes"] --> I
        K["Dunning & recovery"] --> I
    end

    I -->|"Webhooks"| L["Your backend"]
    L --> M["Update access & UI"]
```

The seven steps in this guide cover the full lifecycle: picking a [pricing model](https://dodopayments.com/blogs/metered-pricing-guide) that fits AI cost structures, setting up [billing infrastructure](https://dodopayments.com/blogs/billing-automation-saas) with a Merchant of Record, implementing usage metering with ingestion blueprints, adding credit entitlements for multi-model pricing, managing subscriptions with proper proration, building customer-facing UI with BillingSDK, and monitoring revenue health.

Each component is modular. You can start with simple per-request billing and layer on credits, subscriptions, and analytics as your product grows. The Dodo Payments API is designed so these components compose together without requiring a full rewrite when your pricing evolves.

Ready to build? Start with the [Dodo Payments integration guide](https://docs.dodopayments.com/developer-resources/integration-guide) and explore [pricing plans](https://dodopayments.com/pricing) with no monthly fees - just 4% + $0.40 per transaction.

## FAQ

### What pricing model works best for AI SaaS products?

Most AI SaaS products perform best with hybrid pricing: a base subscription for predictable revenue combined with usage-based components (tokens, requests, or credits) that scale with consumption. Credit-based models are especially effective when your product uses multiple AI models with different underlying costs.

### How do I track LLM token usage for billing?

Use the Dodo Payments LLM Ingestion Blueprint to wrap your LLM client (OpenAI, Anthropic, Groq, or Vercel AI SDK). It automatically captures input/output token counts and sends them as usage events to your configured meter. No manual event construction is needed.

### Can I bill for multiple AI operations from a single credit balance?

Yes. You can link multiple meters to the same credit entitlement with different conversion rates. For example, text generation at 1 credit per 1K tokens and image generation at 10 credits per image, both deducting from one shared "AI Credits" balance that customers see in their portal.

### How does the billing system handle failed payments on subscriptions?

Dodo Payments automatically retries failed charges with smart scheduling and sends recovery emails. You can monitor `payment.failed` and `subscription.on_hold` webhook events to implement additional logic like grace periods, access downgrades, or targeted retention outreach.

### Do I need to handle sales tax and VAT compliance myself?

No. When you use Dodo Payments as a Merchant of Record, it acts as the legal seller on every transaction and handles sales tax, VAT, and GST calculation and remittance across 220+ countries automatically. You don't need to register for tax in individual jurisdictions.

## Final Thoughts

Building billing for AI products is a solved problem if you use the right infrastructure. The combination of [usage-based metering](https://dodopayments.com/blogs/metered-pricing-guide), [credit entitlements](https://docs.dodopayments.com/features/credit-based-billing), and [flexible subscription management](https://dodopayments.com/blogs/flexible-billing-platforms) covers every pricing model an AI SaaS product needs. The hard part is not the billing code - it is choosing the right pricing model and iterating based on real customer data.

Start with the simplest model that captures value, instrument everything, and let the data tell you when to add complexity.
---
- [More AI articles](https://dodopayments.com/blogs/category/ai)
- [All articles](https://dodopayments.com/blogs)