> ## Documentation Index
> Fetch the complete documentation index at: https://getlago.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Build Lago billing with a coding agent

> Use Claude Code or Codex to build and verify one contract billing flow in your application.

Build one billable flow from your application and prove the amount. Your first check is complete when Lago's usage quantity and amount on the Contract match your own calculation, and retrying the same event changes neither. You can do the repository work and local tests without a Lago account. Use the [Lago CLI](https://github.com/getlago/lago-cli) `lago v2` commands for terminal work and the [v2 OpenAPI contract](https://swagger.getlago.com/openapi-v2.yaml) for exact schemas.

> [!NOTE]
>
> API v2 is in beta. Endpoints return the `X-Lago-Endpoint-Status: beta` header.

The v2 setup follows one chain: billable metric → Product → Rate Card and Rates → Plan with applied Rate Cards → customer → Contract → events. Read [How v2 differs from v1](https://getlago.com/docs/v2/guide/introduction/contracts-vs-subscriptions.md) if your agent knows the v1 model. v2 has no plan charges.

## 1. Map billing in your application

Tell your agent your pricing rules. Have it inspect the repository and identify:

* Who pays, what action creates usage, and which saved record proves it happened.
* Which system owns contracts, calculates prices, issues invoices, and collects payments today.
* The customer, contract, and usage IDs that link that action to its bill.
* One example bill and any risk of charging a customer twice.

Agree on the price and which existing customers, if any, will move to Lago before editing code.

**Prompt. Replace `[pricing rules]` with your billing period, currency, base fee, included usage, and overage rate:**

```text theme={"dark"}
Our pricing is [pricing rules].

Inspect this repository. Show:
- Who pays, the action, and its saved record and ID.
- Who owns contracts, invoices, and payments.
- One example bill calculated from source usage.
- Evidence, assumptions, and duplicate-charge risks.
Do not edit code or contact Lago.
```

## 2. Build and test locally

Once you agree on the billing plan, have your agent:

* Map the app's customer and contract IDs to a Lago customer `external_id` and a Contract `external_id`.
* Send usage server-side to [`POST /api/v2/events`](https://getlago.com/docs/v2/api-reference/events/create) or [`POST /api/v2/events/batch`](https://getlago.com/docs/v2/api-reference/events/batch), addressed with `external_contract_id`. v2 rejects the v1 identifier field with a `422`.
* Test the example bill and a retry offline, without contacting Lago.
* Keep current billing in place unless you agreed to change it. Review the diff and tests before any live write.

On retries, reuse the saved record's original `transaction_id` **and** `timestamp`. On the ClickHouse event store, the timestamp is part of the [deduplication key](https://getlago.com/docs/v2/guide/events/ingesting-usage.md#idempotency-and-deduplication), so a retry without it is billed again.

**Prompt. Replace `[approved billing plan]` with the metric, billing period, price, and who will own invoices and payments:**

```text theme={"dark"}
Implement [approved billing plan] in this repository.
- Map customer and contract IDs from app records.
- Send usage server-side to POST /api/v2/events
  addressed with external_contract_id.
- Reuse transaction_id and timestamp on retry.
- Test the example bill and duplicate delivery offline.
- Keep current billing unchanged.
- Show the diff, tests, and bill before live calls.
```

## 3. Connect to the right Lago organization

First, [get access to a Lago Cloud organization or self-hosted instance and its API key](https://getlago.com/docs/v2/guide/ai-agents/for-agents.md#connect-to-lago-when-you-are-ready). The organization needs the product catalog enabled. Set `LAGO_API_KEY` in your terminal or secret manager without putting it in a prompt or source control. Install CLI 1.3.0 or later where you run your agent:

```bash theme={"dark"}
brew install getlago/tap/lago
lago version
```

On other systems, use the [CLI release archives](https://github.com/getlago/lago-cli/releases). Connect to your target:

```bash Cloud US theme={"dark"}
lago init --api-key "$LAGO_API_KEY" --region us
```

```bash Cloud EU theme={"dark"}
lago init --api-key "$LAGO_API_KEY" --region eu
```

```bash Self-hosted theme={"dark"}
lago init --api-key "$LAGO_API_KEY" --region self-hosted \
  --api-url https://lago.example.com
```

For self-hosted Lago, `--api-url` is the API service's base URL, without `/api/v1` or `/api/v2`. `lago v2` commands send requests to `/api/v2` on that host. Confirm the resolved organization and host before changing billing configuration:

```bash theme={"dark"}
lago whoami
lago doctor
```

A CLI dry run sends nothing. `--mode test` is a CLI label, not a sandbox inside your organization. Use a separate test organization or an isolated self-hosted instance for live tests. Keep demo customers and plans out of shared production billing.

Inspect the existing catalog before proposing changes:

```bash theme={"dark"}
lago v2 billable-metrics list --all --output json
lago v2 products list --all --output json
lago v2 rate-cards list --all --output json
lago v2 catalog-plans list --all --output json
```

Describe the catalog as YAML and review it with `lago v2 apply`. Each object takes the fields of its v2 create request and is matched by `code`. For example, a $100 monthly fee plus $0.01 per completed job:

```yaml billing/catalog.yml theme={"dark"}
# Illustrative catalog. Replace codes, prices and dates with your own.
billable_metrics:
  - code: completed_jobs
    name: Completed jobs
    aggregation_type: count_agg
    recurring: false

products:
  - code: platform_fee
    name: Platform fee
    product_type: fixed
  - code: jobs
    name: Completed jobs
    product_type: metered
    billable_metric_code: completed_jobs

rate_cards:
  - code: platform_fee_usd
    product_code: platform_fee
    name: Platform fee USD
    currency: USD
    billing_timing: arrears
    rates:
      - code: platform_fee_usd_2027_01
        effective_from: "2027-01-01T00:00:00Z"
        rate_model: standard
        rate_properties: { amount: "100" }
        billing_interval_unit: month
        billing_interval_count: 1
  - code: jobs_usd
    product_code: jobs
    name: Completed jobs USD
    currency: USD
    billing_timing: arrears
    rates:
      - code: jobs_usd_2027_01
        effective_from: "2027-01-01T00:00:00Z"
        rate_model: standard
        rate_properties: { amount: "0.01" }
        billing_interval_unit: month
        billing_interval_count: 1

plans:
  - code: jobs_monthly
    name: Jobs monthly
    currency: USD
    applied_rate_cards:
      - rate_card_code: platform_fee_usd
        units: "1"
      - rate_card_code: jobs_usd
```

```bash theme={"dark"}
lago v2 apply billing/ --dry-run
```

The dry run prints what it would create or update and sends nothing. Check the currency, billing timing, rate models, amounts, billing intervals and `effective_from` dates. A Rate's `effective_from` cannot be before today in your organization's timezone. A fixed Product needs `units` on its applied Rate Card. Apply the Rate Cards to the Plan before any Contract uses it: a Plan attached to a Contract is locked. `apply` records the objects it manages in `billing/.lago-state/`. Commit that folder with the YAML. See the [pricing models](https://getlago.com/docs/v2/guide/rate-cards/pricing-models/overview.md) and [Plans](https://getlago.com/docs/v2/guide/plans/overview.md).

Before sending usage, identify or create the [Lago customer](https://getlago.com/docs/v2/api-reference/customers/create.md) and a [Contract](https://getlago.com/docs/v2/guide/contracts/overview.md) on that Plan. Use external IDs from your application. Review both requests as dry runs:

```bash theme={"dark"}
lago v2 customers create --input @billing/customer.json --dry-run
lago v2 contracts create --input @billing/contract.json --dry-run
```

`billing/contract.json` wraps its fields in `contract`: `external_id`, `contract_code`, `external_customer_id`, `plan_code`, and optionally `started_at` and `billing_anchor_date`. A future `started_at` creates a `pending` Contract. Without it, the Contract starts now. Rate Cards with `billing_timing: advance` bill at the start of a period, so test this sequence in your isolated organization first.

**Prompt. Replace `[target organization]` with the organization name and API host, and `[approved pricing]` with your reviewed price and metric:**

```text theme={"dark"}
For [target organization], run read-only lago v2 checks.
Show the resolved host and organization.
Compare the Lago catalog with [approved pricing].
Write the catalog YAML: metric, products, rate cards
with rates, and a plan with applied rate cards.
Run lago v2 apply --dry-run. Prepare customer and
contract requests as dry runs.
Show exact requests and conflicts. Make no live writes.
```

## 4. Check what Lago recorded

Choose one customer and billing period. Calculate the expected **usage quantity and amount** from saved app records, then read Lago's current usage for that Contract:

```bash theme={"dark"}
lago v2 contracts current-usage "$CONTRACT_EXTERNAL_ID" \
  --apply-taxes false --output json
```

Current usage covers the Contract's open billing windows. It is not a preview of one invoice. Each entry in `rate_cards` carries its `rate_card_code`, `product_code`, `units` and `amount_cents`. Add `--rate-card-code` or `--product-code` to narrow the result.

Check:

* Units and `amount_cents` of the metered Rate Card against your calculation. If usage is zero, wait for processing and read again before investigating.
* In an isolated test environment, retry one event with its original `transaction_id` and `timestamp`. The units should not increase.
* For the **full bill**, check the fixed Rate Card entry and any taxes. When the period closes, compare each fee on the [invoice](https://getlago.com/docs/v2/guide/invoicing/overview.md) with your calculation. v2 has no invoice preview.

**Prompt. Replace `[customer ID]`, `[contract ID]`, and `[source record ID]` with IDs from the same isolated test organization:**

```text theme={"dark"}
Use these IDs from the isolated test organization:
- Customer: [customer ID]
- Contract: [contract ID]
- Source record: [source record ID]
Calculate quantity and amount from the app record.
Read lago v2 contracts current-usage; compare units,
amount, and billing window.
Retry this event in the isolated test organization
  with its original transaction_id and timestamp.
Read usage again; check the units did not rise.
Stop on an identity or amount mismatch.
List untested invoice parts.
```

## If the result differs

| Symptom | First check |
| - | - |
| `lago` runs Docker Compose | Run `lago version`; remove a self-hosted shell alias shadowing the CLI. |
| `lago v2` is not a command | Upgrade the CLI to 1.3.0 or later. |
| Authentication or wrong organization | Run `lago doctor` and `lago whoami`; verify API host and key. |
| `422` on an event | Address the event with `external_contract_id`, not the v1 identifier field. |
| Event exists but usage is zero | Check the Contract status and start, `external_contract_id`, metric code, event timestamp, and aggregation property. An `external_contract_id` that matches no Contract is ingested and then skipped. |
| A retry increases usage | Compare both the original `transaction_id` and `timestamp`. |
| Usage or invoice differs from expected money | Check the active Rate and its `effective_from`, rate phases, [Contract overrides](https://getlago.com/docs/v2/guide/contracts/overrides.md), billing timing, billing interval, and taxes. |

**Prompt. Replace `[contract ID]`, `[billing period]`, `[expected amount]`, and `[observed amount]` with the values you are investigating:**

```text theme={"dark"}
For [contract ID] in [billing period], our app expects
[expected amount] and Lago shows [observed amount].
Recalculate source usage and check:
- Active rates, rate phases, and contract overrides.
- Billing timing, billing interval, and taxes.
Show the first proven difference and customer impact.
Do not change billing or send another event.
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.