← Blog

Claude API Subscription Billing: Stripe Integration

2026-11-10 · 5 min read · SubToAPI Team

If you're building a product on top of Claude and charging customers for it, you need a way to connect what people actually use — tokens, requests, model tiers — to what they pay. That's the core problem "Claude API subscription billing integration stripe" is really asking about: how do you wire Anthropic's token-based usage model into Stripe's subscription and metered billing system without building a fragile, custom invoicing pipeline from scratch.

The short answer is that Stripe doesn't know anything about Claude, and Claude doesn't know anything about Stripe — you have to build the bridge yourself. That bridge has three parts: tracking usage per customer, reporting that usage to Stripe on a schedule, and handling the subscription lifecycle (upgrades, downgrades, cancellations, failed payments) so access to the Claude-powered feature matches what's actually been paid for. Below is a practical breakdown of how to build it.

The three billing models you can choose from

Before writing any code, decide which pricing model fits your product:

Most teams start with flat tiers for simplicity and move to hybrid once they have enough usage data to set overage rates correctly.

Step 1: Track Claude usage per customer

Every Claude API response includes token counts in its usage metadata. You need to capture this on every call and attribute it to the customer who triggered it — not just log it for your own debugging.

async function callClaude(prompt, customerId) {
  const response = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "x-api-key": process.env.ANTHROPIC_API_KEY,
      "anthropic-version": "2023-06-01",
      "content-type": "application/json",
    },
    body: JSON.stringify({
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      messages: [{ role: "user", content: prompt }],
    }),
  });

  const data = await response.json();
  const { input_tokens, output_tokens } = data.usage;

  await recordUsage(customerId, input_tokens, output_tokens);
  return data;
}

recordUsage should write to your own database (not directly to Stripe) so you have an audit trail independent of Stripe's API availability. Batch and reconcile later.

If you're routing Claude access through an API gateway instead of calling Anthropic directly, this step gets simpler because the gateway already separates usage by application key. SubToAPI, for example, issues scoped sub_live_... keys per application and returns usage metadata on every response, which means you don't have to build the per-customer token-tracking layer yourself — you read it straight from the API response and forward it to Stripe. See /docs/messages for the response shape.

Step 2: Report usage to Stripe

For metered or hybrid billing, Stripe needs usage records tied to a subscription item. Run this on a schedule — hourly or daily depending on volume — rather than on every single API call, to avoid rate-limiting yourself against Stripe's API.

import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

async function reportUsageToStripe(subscriptionItemId, totalTokens, timestamp) {
  await stripe.subscriptionItems.createUsageRecord(subscriptionItemId, {
    quantity: totalTokens,
    timestamp,
    action: "increment",
  });
}

Aggregate your internal usage table by customer and billing period, then push the sum. Keep the raw per-call records for support disputes — "why was I charged X" questions are common with usage-based billing, and you want to be able to answer them precisely.

Step 3: Handle the subscription lifecycle with webhooks

Stripe webhooks are non-negotiable here. You need to react to at least these events:

app.post("/webhooks/stripe", async (req, res) => {
  const event = stripe.webhooks.constructEvent(
    req.rawBody,
    req.headers["stripe-signature"],
    process.env.STRIPE_WEBHOOK_SECRET
  );

  switch (event.type) {
    case "customer.subscription.deleted":
      await revokeClaudeAccess(event.data.object.customer);
      break;
    case "invoice.payment_failed":
      await startGracePeriod(event.data.object.customer);
      break;
  }

  res.sendStatus(200);
});

The critical design decision is where access control actually lives. Don't check Stripe's subscription status on every API call — that adds latency and a dependency on Stripe's uptime for your core feature. Instead, sync subscription state into your own database via webhooks, and check that local copy when deciding whether to let a request through to Claude.

Enforcing limits before the Claude call, not after

A common mistake is billing accurately but enforcing limits too late — letting a customer blow past their plan's cap and only catching it when the invoice generates. Check usage against the plan limit before making the Claude API call, and return a clear error (HTTP 402 or 429) if they're over.

async function checkLimitAndCall(customerId, prompt) {
  const usage = await getMonthlyUsage(customerId);
  const plan = await getPlan(customerId);

  if (usage.tokens >= plan.tokenLimit) {
    throw new Error("Usage limit reached for current billing period");
  }

  return callClaude(prompt, customerId);
}

If you're already paying for Claude access as a SubToAPI customer, this part is simpler: you issue one application key per customer tier through the dashboard, set reasonable rate limits per plan, and the usage metadata returned with each response gives you the numbers to feed into your own Stripe metering job — without maintaining a separate proxy to Anthropic. Check /pricing for how the Solo, Team, and Scale tiers map to seat-based billing if you want a reference model for your own plan structure, and /docs/quickstart to see the request/response format you'd be metering against.

Testing before you go live

Use Stripe's test mode and test clocks to simulate a full billing cycle — subscription creation, usage accrual, invoice generation, and renewal — without waiting a real month. Also test the failure paths deliberately: a declined card mid-cycle, a downgrade that should reduce a usage cap immediately, and a cancellation that should revoke access but still generate a final prorated invoice.

questions

Do I need Stripe's metered billing API, or can I use flat plans? Flat plans are simpler and fine if your Claude usage per customer is relatively predictable. Use metered billing only once you have real usage data showing wide variance between customers — otherwise you're adding complexity without a clear payoff.

Where should usage limits be enforced — in Stripe or in my app? In your app. Stripe handles payment and invoicing; your application should check a locally cached copy of the customer's plan and usage before each Claude API call, synced via Stripe webhooks rather than queried live.

Can I avoid building the usage-tracking layer myself? Yes, if you route Claude access through a gateway that already returns per-request usage metadata — you still need to report that data to Stripe, but you skip building the token-counting and attribution logic from scratch.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →