# How to Add Credits-Based Billing to Your AI App

> Step-by-step guide to implementing credit-based billing for AI applications. Let users buy credit packs and consume them per API call or generation with Dodo Payments.
- **Author**: Ayush Agarwal
- **Published**: 2026-03-25
- **Category**: Payments, AI, How-To
- **URL**: https://dodopayments.com/blogs/add-credits-billing-ai-app

---

Your AI app burns tokens on every request. Whether you are calling OpenAI, Anthropic, or running your own Llama 3 instance on H100s, every generation has a direct marginal cost. Flat subscriptions often fail in this environment. They either overprice light users who barely touch the app or lose money on heavy users who generate thousands of images or millions of tokens.

Credits-based billing aligns your costs with your usage while giving users total control over their spending. It is the most popular billing model for AI applications in 2026 because it solves the "heavy user" problem without scaring away casual experimenters. By selling credit packs, you turn your variable costs into predictable revenue and create a clear value exchange for your customers.

In this guide, we will walk through exactly how to implement a robust credit-based billing system for your AI application using Dodo Payments. We will cover everything from defining your credit economy to handling webhooks and building a low-balance UI.

## Why Credits for AI Apps?

AI applications are unique because their cost structure is highly variable. Unlike a traditional SaaS where a user's impact on your server bill is negligible, an AI user can cost you dollars in a single session. This makes traditional flat-rate pricing risky.

Credits provide a buffer between your infrastructure costs and your user pricing. When a user buys a 500-credit pack, they are essentially pre-paying for a specific amount of compute. This ensures you are never "in the red" for a specific user's activity. It also prevents abuse, as a malicious user or a runaway script can only consume what has already been paid for.

Users also understand credits intuitively. The "arcade token" model is familiar and reduces the friction of variable pricing. Instead of worrying about "tokens per thousand words," users just see that a GPT-4 query costs 5 credits and an image generation costs 10 credits. This transparency builds trust and encourages users to explore your features without fear of a surprise bill at the end of the month.

Finally, credits allow for better margin control. You can set different credit costs for different models or features. If a new, more expensive model comes out, you don't have to change your subscription tiers. You simply set a higher credit cost for that specific action. This flexibility is crucial in the fast-moving AI landscape.

## How the Credit Economy Works

A successful credit system consists of three main parts: the purchase, the storage, and the deduction. The user buys a credit pack through your checkout. Your system receives a notification and updates the user's balance in your database. Then, every time the user performs an AI action, your app checks the balance and deducts the appropriate amount.

This model creates a virtuous cycle. Users buy credits when they need them, and you get paid upfront. If they run low, you can trigger a re-purchase prompt right in the UI. This "top-up" behavior is much more natural for AI tools than a recurring monthly bill that might not match the user's actual needs for that month.

You can also combine credits with subscriptions. For example, a "Pro" plan might include 1,000 credits per month, with the option to buy extra "top-up" packs if the user runs out early. This hybrid model provides the stability of recurring revenue with the flexibility of usage-based billing.

## Step 1: Define Your Credit Economy

Before you write a single line of code, you need to decide what a "credit" is worth. This is your credit economy. You should aim for a system that is easy for users to calculate but granular enough to cover your different costs.

For example, you might decide that 1 credit equals $0.10 of value. You then map your AI actions to this unit:

- 1 credit = 1 standard image generation (Stable Diffusion)
- 5 credits = 1 high-res image generation (Flux)
- 2 credits = 1 GPT-4o mini query
- 10 credits = 1 GPT-4o query

By decoupling the dollar amount from the action, you can adjust your pricing or your costs behind the scenes without confusing the user. If your API provider drops their prices, you can simply grant more credits per dollar or reduce the credit cost per action.

## Step 2: Create Credit Pack Products in Dodo Payments

Once your economy is defined, you need to create the products that users will actually buy. In the Dodo Payments dashboard, you will create "One-Time" products for your credit packs.

Common tiers might look like this:

- Starter Pack: 100 credits for $10
- Power Pack: 500 credits for $40 (20% discount)
- Pro Pack: 1,500 credits for $100 (33% discount)

When creating these products, you can use the [credit-based billing](https://docs.dodopayments.com/features/credit-based-billing) features in Dodo to attach entitlements directly to the product. This allows Dodo to track the balance for you, or you can simply use the purchase event to update your own internal ledger.

## Step 3: Implement the Checkout Flow

To let users buy credits, you will use the [overlay checkout](https://docs.dodopayments.com/developer-resources/overlay-checkout). This provides a seamless experience where the user never leaves your app to pay.

You can trigger the checkout using the Dodo Payments SDK. When the user clicks "Buy 500 Credits," your backend creates a checkout session and returns the URL or ID to the frontend.

```javascript
import DodoPayments from "dodopayments";

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

const session = await client.checkoutSessions.create({
  product_cart: [
    {
      product_id: "pdt_credit_pack_500",
      quantity: 1,
    },
  ],
  customer: {
    email: user.email,
    name: user.name,
  },
  return_url: "https://dodopayments.com",
});
```

This integration ensures that you are using a [merchant of record for AI](https://dodopayments.com/blogs/merchant-of-record-ai) which handles all the global tax compliance and payment routing for you. You don't have to worry about VAT in Europe or sales tax in the US; Dodo handles it all.

## Step 4: Handle the Purchase Webhook

After a successful payment, Dodo Payments will send a webhook to your server. This is the most critical part of the integration. You must listen for the `payment.succeeded` or `credit.added` event to update your user's balance.

Using [webhooks](https://docs.dodopayments.com/developer-resources/webhooks) ensures that even if the user closes their browser during the redirect, their credits will still be added to their account.

```javascript
// Example webhook handler (Node.js/Express)
app.post("/webhooks/dodo", async (req, res) => {
  const event = req.body;

  if (event.type === "payment.succeeded") {
    const { customer_id, product_cart } = event.data;
    const creditProduct = product_cart[0];

    // Map product_id to credit amount
    const creditAmount = getCreditsForProduct(creditProduct.product_id);

    // Update your database
    await db.users.update(
      { dodo_customer_id: customer_id },
      { $inc: { credit_balance: creditAmount } },
    );
  }

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

This logic ensures your [api monetization](https://dodopayments.com/blogs/api-monetization) is accurate and real-time. You can also use Dodo's built-in credit ledger if you prefer not to manage the balance in your own database.

## Step 5: Deduct Credits on AI Requests

Now that users can buy credits, you need to enforce the balance. Every time a user hits your AI endpoint, you should check their balance and deduct the cost of the action.

A common pattern is to use a middleware or a wrapper function for your AI calls. This prevents code duplication and ensures that every request is accounted for.

```javascript
async function processAIRequest(userId, actionType, params) {
  const user = await db.users.findById(userId);
  const cost = getCreditCost(actionType);

  if (user.credit_balance < cost) {
    throw new Error("Insufficient credits");
  }

  // Deduct credits first (pessimistic locking)
  await db.users.update({ _id: userId }, { $inc: { credit_balance: -cost } });

  try {
    const result = await callAIModel(actionType, params);
    return result;
  } catch (error) {
    // Refund credits if the AI call fails
    await db.users.update({ _id: userId }, { $inc: { credit_balance: cost } });
    throw error;
  }
}
```

This approach is essential for [monetizing AI](https://dodopayments.com/blogs/monetize-ai) effectively. It protects your margins by ensuring that every successful generation is paid for, while being fair to the user if a technical error occurs.

## Step 6: Visualize the Credit Flow

To help your team and stakeholders understand the system, a flow diagram is incredibly useful. It shows the interaction between the user, your app, and Dodo Payments.

```mermaid
flowchart TD
    A[User clicks Buy Credits] --> B[App creates Dodo Checkout Session]
    B --> C[User completes payment in Overlay]
    C --> D[Dodo sends payment.succeeded Webhook]
    D --> E[App updates User Balance in DB]
    E --> F[User makes AI Request]
    F --> G{App checks Balance}
    G -- Insufficient --> H[Show Top-up Prompt]
    G -- Sufficient --> I[Deduct Credits & Call AI]
    I --> J[Show Result & New Balance]
```

This diagram illustrates the full lifecycle of a credit. It highlights the importance of the [billing UX](https://dodopayments.com/blogs/billing-ux-usage-caps-alerts) where the user is prompted to top up before they hit a hard wall.

## Step 7: Build the Low-Balance UI

A credit system is only as good as its user experience. If a user's request suddenly fails because they ran out of credits, they will be frustrated. You should proactively show their balance and warn them when it gets low.

You can implement a simple "Credit Bar" in your navigation or a toast notification when the balance drops below a certain threshold.

```javascript
// React component for low balance alert
function CreditBalance({ balance }) {
  const isLow = balance < 20;

  return (
    <div className="flex items-center gap-2">
      <span className={isLow ? "font-bold text-red-500" : "text-gray-700"}>
        {balance} Credits Remaining
      </span>
      {isLow && (
        <button
          onClick={openTopUpModal}
          className="rounded bg-lime-400 px-3 py-1 text-sm"
        >
          Top Up
        </button>
      )}
    </div>
  );
}
```

Providing these [usage caps and alerts](https://dodopayments.com/blogs/billing-ux-usage-caps-alerts) is a best practice for any [usage-based billing SaaS](https://dodopayments.com/blogs/usage-based-billing-saas). It keeps the user informed and reduces support tickets related to "missing" credits or failed requests.

## Advanced Credit Strategies

Once you have the basics down, you can implement more advanced strategies to increase retention and revenue.

### Auto-Recharge

Some users don't want to manually buy credits every time they run out. You can offer an "Auto-Recharge" feature where your app automatically purchases a specific pack when the balance hits a threshold. This requires saving the user's payment method, which Dodo handles securely.

### Credit Expiry

To encourage usage and manage your long-term liabilities, you might set an expiry date on credits. For example, credits could expire 12 months after purchase. This is a common practice in many industries, but be sure to communicate this clearly to your users to avoid frustration.

### Gifting and Referrals

Credits are a great tool for growth. You can grant 50 free credits to new users to let them try the app. You can also give 100 credits to a user who refers a friend. Since credits have a fixed cost for you, it is much easier to calculate the ROI of these marketing efforts compared to offering "one month free" of a subscription.

### Hybrid Subscription Models

As mentioned earlier, combining credits with a subscription is a powerful way to [implement usage-based billing](https://dodopayments.com/blogs/implement-usage-based-billing). You can offer a "Basic" plan for $10/month that includes 100 credits, and a "Pro" plan for $50/month that includes 1,000 credits. Any usage beyond that is handled via one-time credit pack purchases. This gives you the best of both worlds: recurring revenue and unlimited upside.

## Managing Cash Flow with Credits

One of the biggest advantages of credit-based billing is the impact on your cash flow. Because users pay for credits upfront, you receive the cash before you have to pay your AI providers for the tokens. This "negative cash conversion cycle" is a massive advantage for scaling startups.

You can read more about how this affects your business in our post on [billing credits and cash flow](https://dodopayments.com/blogs/billing-credits-pricing-cashflow). By collecting revenue early, you can reinvest that capital into growth or product development much faster than a company waiting for end-of-month invoices.

## Choosing the Right AI Pricing Model

While credits are excellent for many AI apps, they aren't the only option. Depending on your target audience, you might consider pure usage-based billing (pay-as-you-go) or tiered subscriptions.

We have a detailed breakdown of different [AI pricing models](https://dodopayments.com/blogs/ai-pricing-models) to help you decide which one fits your product best. Generally, credits are the best middle ground for B2C and Prosumer tools, while pure usage-based billing is often preferred by developers and enterprise API users.

## Integrating with Dodo Payments SDKs

To make the implementation even easier, you should use the official [Dodo Payments SDKs](https://docs.dodopayments.com/developer-resources/dodo-payments-sdks). They provide type-safe methods for creating checkout sessions, managing customers, and handling webhooks.

Whether you are building with Node.js, Python, or Go, the SDKs handle the heavy lifting of API authentication and request formatting. This lets you focus on your AI logic instead of the plumbing of your billing system.

## Conclusion

Adding credit-based billing to your AI app is a strategic move that protects your margins and improves your user experience. By following the steps in this guide, you can implement a system that is scalable, transparent, and highly profitable.

Dodo Payments makes this process simple by providing the infrastructure for [how to accept online payments](https://dodopayments.com/blogs/how-to-accept-online-payments) globally without the headache of tax compliance. With our [usage-based billing](https://docs.dodopayments.com/features/usage-based-billing/introduction) and [credit-based billing](https://docs.dodopayments.com/features/credit-based-billing) features, you can launch your AI product with confidence.

Ready to start monetizing your AI app? [Sign up for Dodo Payments](https://dodopayments.com) today and get your first credit pack live in minutes.

## FAQ

### How do I handle refunds for unused credits?

Refunds for credits can be handled directly through the Dodo Payments dashboard. You can choose to refund the entire purchase or a partial amount. When a refund is processed, you should listen for the `payment.refunded` webhook and deduct the corresponding credits from the user's balance in your database to keep everything in sync.

### Can I set credits to never expire?

Yes, you can configure your credit entitlements in Dodo Payments to have no expiration date. This is often the most user-friendly approach, as it removes the "use it or lose it" pressure. However, some businesses prefer expiration to manage their financial liabilities over time. The choice depends on your specific business model and customer expectations.

### What happens if a user's AI request fails after credits are deducted?

You should always implement a "refund on failure" logic in your application code. As shown in our code examples, you can wrap your AI call in a try-catch block. If the AI model returns an error or times out, you should immediately increment the user's credit balance back to its previous state. This ensures that users are only charged for successful generations.

### How do I prevent users from "gaming" the credit system?

The best way to prevent abuse is to use pessimistic locking in your database when deducting credits. This means you deduct the credits _before_ you start the expensive AI generation. If you deduct them after, a user could potentially fire off hundreds of concurrent requests before their balance hits zero. By deducting upfront, you ensure that they can never exceed their paid limit.

### Can I offer different credit types for different features?

Absolutely. Dodo Payments allows you to create multiple credit entitlements for the same customer. You could have "Image Credits" for your generator and "Text Credits" for your chatbot. This allows you to price different types of compute differently and gives you more granular data on how your users are interacting with your product.

---

Check out our [pricing](https://dodopayments.com/pricing) to see how Dodo Payments can help you scale your AI business globally.
---
- [More Payments articles](https://dodopayments.com/blogs/category/payments)
- [All articles](https://dodopayments.com/blogs)