# Quickstart (/docs/usage-billing/quickstart)

This quickstart bills one customer for AI tokens: 100,000 tokens included each month, 0.00002 USD per token after that, with 50 USD of prepaid credit used first. It takes about ten minutes in test mode.

You need:

- Usage billing turned on for your account (ask Comecero).
- A **test** secret token, in `COMECERO_SECRET_TOKEN`. See [authentication](/docs/basic-concepts/authentication).
- A test subscription in USD for the customer, in `SUBSCRIPTION_ID`. Its renewals set the billing periods.
- Node.js 18 or later (it has `fetch`).

Save the scripts below as `.mjs` files and run them with `node`, for example `node setup.mjs`.

Run the setup once. If you run it again:

- The metric and the rate plan answer `409`, because they already exist. The script goes on.
- The agreement and the entitlements are saved again. These routes are upserts and answer `201` even on an update.
- The credit is added only once, because of its `idempotency_key`.
- A new usage key is made each time.

## 1. Set up the customer [#1-set-up-the-customer]

````javascript
// setup.mjs: run with COMECERO_SECRET_TOKEN and SUBSCRIPTION_ID set.
const API = "https://api.comecero.com/api/v1/usage";
const headers = {
  Authorization: `Bearer ${process.env.COMECERO_SECRET_TOKEN}`,
  "Content-Type": "application/json",
};

async function call(method, path, body) {
  const response = await fetch(API + path, { method, headers, body: body && JSON.stringify(body) });
  const answer = await response.json().catch(() => ({}));
  // 409 means it already exists, so a second run of this script goes on.
  if (!response.ok && response.status !== 409) {
    throw new Error(`${method} ${path}: ${response.status} ${answer.error?.message ?? ""}`);
  }
  return answer;
}

// What you count. event_key is the metric_key your app sends.
await call("POST", "/metrics", {
  metric_id: "met_ai_tokens",
  name: "AI tokens",
  event_key: "ai_tokens",
  unit_label: "token",
  aggregation: "sum",
  allowed_properties: ["model"],
});

// The price: 100,000 tokens included each period, then 0.00002 USD per token.
await call("POST", "/rate_plans", {
  rate_plan_id: "ai_tokens_standard",
  version: 1,
  metric_id: "met_ai_tokens",
  currency: "USD",
  pricing_model: "flat_per_unit",
  included_allowance: 100000,
  overage_price: 0.00002,
});

// Links your id for the customer to their Comecero subscription.
// customer_id is the id your app sends to the meter as external_customer_id.
await call("POST", "/agreements", {
  agreement_id: "agr_cust_8412",
  customer_id: "cust_8412",
  subscription_id: process.env.SUBSCRIPTION_ID,
  currency: "USD",
  effective_from: new Date().toISOString(),
});

// A prepaid balance for the customer. It must exist before the
// metered entitlement that names it in funding_source_entitlement_id.
await call("POST", "/entitlements", {
  entitlement_id: "credit_cust_8412",
  kind: "credit",
  billing_agreement_id: "agr_cust_8412",
});

// The tokens they are billed for, paid from that credit first.
await call("POST", "/entitlements", {
  entitlement_id: "ent_cust_8412_ai_tokens",
  billing_agreement_id: "agr_cust_8412",
  metric_id: "met_ai_tokens",
  rate_plan_id: "ai_tokens_standard",
  rate_plan_version: 1,
  funding_source_entitlement_id: "credit_cust_8412",
  overage_policy: "allow",
});

// 50 USD of credit. The idempotency_key adds it once, however often this runs.
const credit = await call("POST", "/entitlements/credit_cust_8412/credits", {
  amount: 50,
  idempotency_key: "quickstart-welcome-credit",
  description: "Welcome credit",
});
console.log("credit balance:", credit.balance);

// A usage key for your server. It is shown only in this answer: store it now.
const key = await call("POST", "/keys", { name: "Quickstart server" });
console.log("usage key (store it in your secrets):", key.key);
````

The script prints the usage key once. Put it in `COMECERO_USAGE_KEY` for the next step. It starts with `apk_test_`, because it was made with a test token.

<Callout>
A new key and a new metric reach the usage meter within a few minutes, often at once. Until the key has synced, the meter answers `403`. Until the metric has synced, its events come back `rejected` with `unknown_metric`. Wait a few minutes and send again.
</Callout>

## 2. Send usage [#2-send-usage]

````javascript
// send.mjs: run with COMECERO_USAGE_KEY set.
const response = await fetch("https://usage.comecero.com/v1/events", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.COMECERO_USAGE_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    events: [
      {
        operation_id: "chat_1001", // your id for this usage: a resend is never counted twice
        external_customer_id: "cust_8412", // the agreement's customer_id
        metric_key: "ai_tokens",
        quantity: "1250", // a decimal string
        timestamp: new Date().toISOString(),
        properties: { model: "large" },
      },
      {
        operation_id: "chat_1002",
        external_customer_id: "cust_8412",
        metric_key: "ai_tokens",
        quantity: "830",
      },
    ],
  }),
});

const answer = await response.json();
console.log(response.status, answer.counted, "counted,", answer.duplicate, "duplicate");
for (const result of answer.results) {
  if (result.status !== "counted" && result.status !== "duplicate") console.log(result);
}
````

Run it twice. The first time both events are `counted`. The second time both are `duplicate`: the same `operation_id` is counted once for a metric. In a real app, send events in batches and resend on `429` or `5xx`, as in [Send usage](/docs/usage-billing/send-usage#from-your-server).

`external_customer_id` must be the agreement's `customer_id`. The meter counts events for any id, but only ids with an agreement are billed.

## 3. Read usage so far and the balance [#3-read-usage-so-far-and-the-balance]

````javascript
// read.mjs: run with COMECERO_SECRET_TOKEN set.
const API = "https://api.comecero.com/api/v1/usage";
const headers = { Authorization: `Bearer ${process.env.COMECERO_SECRET_TOKEN}` };

const current = await fetch(`${API}/agreements/agr_cust_8412/current`, { headers }).then((r) => r.json());
for (const line of current.entitlements) {
  console.log(`${line.metric_name}: ${line.used} of ${line.included} included (${line.percent}%), ${line.amount} ${current.currency} so far`);
}

const balance = await fetch(`${API}/entitlements/credit_cust_8412/balance`, { headers }).then((r) => r.json());
console.log("credit left:", balance.balance);
````

````text
AI tokens: 2080 of 100000 included (2%), 0 USD so far
credit left: 50
````

Usage so far is cached for 5 minutes, so it can be a few minutes behind. `amount` is the price of the usage above the allowance so far, before prepaid credit. The credit is used when the period is billed, at the subscription's renewal. See [Get usage this period so far](/api/usage-agreements/get-usage-so-far) and [Get an entitlement's balance](/api/usage-entitlements/get-entitlement-balance).

## 4. Get alerts [#4-get-alerts]

Create an event subscription for `usage:threshold_reached`, so your server hears when the customer passes 50%, 80% and 100% of the tokens included. Set `active` to `true`: a new event subscription is off until you do. See the [webhooks guide](/docs/guides/webhooks).

````bash
curl -X POST https://api.comecero.com/api/v1/event_subscriptions \
  -H "Authorization: Bearer $COMECERO_SECRET_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "event_type": "usage:threshold_reached",
    "method": "http",
    "format": "json",
    "destination": "https://example.com/webhooks/comecero",
    "active": true
  }'
````

See [usage alerts](/docs/usage-billing/follow-usage#usage-alerts) and [Usage threshold reached](/api/webhooks/usage-threshold-reached) for the event's data.

## What happens next [#what-happens-next]

When the subscription renews, Comecero bills the period: the first 100,000 tokens are included, the price of the rest is taken from the 50 USD credit, and anything above that usually goes on the renewal invoice, next to the plan's price, and is charged with it. You don't start billing yourself. Read the result with [List an agreement's billing runs](/api/usage-billing-runs/list-agreement-runs) (`GET /api/v1/usage/agreements/agr_cust_8412/runs`). See [Credits and burndown](/docs/usage-billing/credits) and [How usage is billed](/docs/usage-billing/how-usage-is-billed).

When it works in test mode, do the same with a live token. Live objects, `apk_live_` keys and live usage are kept apart from test ones. A test key only sends usage for metrics made in test mode.
