← Blog

Claude API Invoice Generation from Usage Data

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

If you're billing customers, clients, or internal teams based on how much they use Claude, you need a reliable way to turn raw API usage into invoices. The short answer: capture the usage object returned with every Claude API response, store it per customer or per API key, aggregate it over a billing period, multiply by your pricing, and feed the result into an invoicing tool like Stripe Billing or a PDF generator.

There's no built-in "generate invoice" endpoint in the Claude API itself — Anthropic gives you token counts, not billing documents. So invoice generation is really a three-part pipeline: metering (recording usage events), aggregation (summing them per customer per period), and rendering (turning totals into an invoice). This article walks through each part with working code, and where relevant, points out how a layer like SubToAPI removes the metering step entirely by giving each application key its own usage metadata out of the box.

What usage data Claude actually gives you

Every messages API response includes a usage field with input and output token counts:

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-4-5",
    "max_tokens": 200,
    "messages": [{"role": "user", "content": "Summarize this ticket."}]
  }'

Response excerpt:

{
  "usage": {
    "input_tokens": 142,
    "output_tokens": 58
  }
}

That's the only ground truth you get. Everything else — which customer made the call, what it should cost, how it rolls up into a monthly invoice — is on you to build, unless you're routing requests through a layer that already tags usage per key.

Step 1: Record every usage event

Don't try to reconstruct usage later from logs. Write a usage event to your database (or a dedicated events table) immediately after each successful call.

async function callClaudeAndLog(customerId, messages) {
  const res = 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: 500,
      messages,
    }),
  });

  const data = await res.json();

  await db.usageEvents.insert({
    customerId,
    model: "claude-sonnet-4-5",
    inputTokens: data.usage.input_tokens,
    outputTokens: data.usage.output_tokens,
    createdAt: new Date(),
  });

  return data;
}

Store customerId alongside the raw token counts — not a pre-computed dollar amount. Prices change, and you want the ability to re-price historical usage if you adjust your margin.

Step 2: Aggregate usage per billing period

At invoice time, sum tokens per customer for the billing window and apply your rate card. Keep input and output tokens separate since Claude's pricing (and likely your own resale pricing) differs between them.

function computeInvoiceLines(usageEvents, rates) {
  const totals = {};

  for (const e of usageEvents) {
    totals[e.customerId] ??= { inputTokens: 0, outputTokens: 0 };
    totals[e.customerId].inputTokens += e.inputTokens;
    totals[e.customerId].outputTokens += e.outputTokens;
  }

  return Object.entries(totals).map(([customerId, t]) => {
    const inputCost = (t.inputTokens / 1_000_000) * rates.inputPerMillion;
    const outputCost = (t.outputTokens / 1_000_000) * rates.outputPerMillion;
    return {
      customerId,
      inputTokens: t.inputTokens,
      outputTokens: t.outputTokens,
      amountDue: Math.round((inputCost + outputCost) * 100) / 100,
    };
  });
}

Run this on a cron job at the end of each billing cycle, or on-demand when a customer requests a usage report.

Step 3: Turn totals into an actual invoice

Once you have per-customer totals, you have two realistic paths:

Either way, the invoice line items are just the token totals and dollar amounts from Step 2 — the hard part was always getting clean, trustworthy usage data per customer, not the document itself.

Skipping the metering step entirely

If you're reselling Claude access to multiple customers or teams, building and maintaining your own usage-tracking table is extra infrastructure you probably didn't want to own. SubToAPI issues a separate sub_live_... API key per application or customer, and every key's usage is tracked automatically — tokens in, tokens out, request counts — visible in the dashboard without you writing a single logging line.

That means your invoice pipeline shrinks to one step: pull usage metadata per key for the billing period and multiply by your rate. No event table, no risk of a dropped log write causing an under-billed customer. Check the quickstart to see how keys and usage metadata are structured, and the messages docs for the exact response shape, which matches Claude's own usage object so your aggregation code barely changes.

For teams managing several client accounts, the Team plan lets you create one key per client (€19/seat) and read each one's usage independently — which is effectively a built-in metering system for invoice generation, without the custom database work described above.

Practical tips for accurate invoices

Does the Claude API have a built-in invoicing or billing endpoint?

No. The Claude API returns token usage in each response, but generating invoices, applying rates, and sending bills is left to the developer or a billing tool like Stripe.

How do I bill different customers differently for the same Claude usage?

Tag every API call with a customer identifier at log time, store raw token counts per event, then apply a per-customer rate card when aggregating for invoices. Using separate API keys per customer, as SubToAPI supports, makes this tracking automatic.

Should I invoice based on tokens or on a flat per-request fee?

Token-based billing is more accurate since request cost varies with prompt and response length, but it requires more infrastructure. Flat per-request pricing is simpler to invoice but risks under-charging for long conversations — many SaaS products use a hybrid: a flat base fee plus metered overage.

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 →