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

# Registre uso medido

> Reporte um evento de uso contra uma assinatura para que as cobranças medidas sejam adicionadas à próxima fatura.

export const SchemaLangNote = ({lang}) => {
  const text = ({
    es: "Los nombres de campos y el esquema de solicitud/respuesta que se muestran a continuación están en inglés — se generan a partir de la especificación OpenAPI. El texto explicativo de esta página está traducido.",
    pt: "Os nomes dos campos e o esquema de requisição/resposta exibidos abaixo estão em inglês — são gerados a partir da especificação OpenAPI. O texto explicativo desta página está traduzido."
  })[lang] || "Field names and the request/response schema shown below are in English — they are generated from the OpenAPI specification.";
  return <Note>{text}</Note>;
};

Use `POST /subscription/usage` para reportar o consumo medido contra uma assinatura. O faturamento por uso permite cobrar um valor variável além da tarifa fixa do plano — por exemplo uma assinatura base mais uma cobrança por requisição ou por gigabyte.

<SchemaLangNote lang="pt" />

<Note>
  Os **medidores** de uso e a sua **precificação por plano** são configurados no Dashboard, em **Assinaturas → Medidores de uso**, não pela API. Este endpoint só ingere os eventos de uso brutos. Consulte [Faturamento por uso e híbrido](/pt/guides/subscriptions#faturamento-por-uso-e-híbrido) para o modelo completo.
</Note>

## Como as cobranças medidas chegam a uma fatura

1. Você define um medidor (ex.: `api_requests`) com um modo de agregação, e o precifica em um plano.
2. Ao longo do período de faturamento você chama `POST /subscription/usage` para cada evento de uso.
3. Na renovação, o Therius agrega os eventos daquele período conforme o modo de agregação do medidor, subtrai as unidades incluídas do plano, aplica o esquema de precificação e soma o resultado à fatura como uma [linha](/pt/api-reference/subscriptions/invoices#line-items) própria.

O período de faturamento para o qual um evento conta é determinado pelo timestamp `occurredAt` dele.

Envie um header `Idempotency-Key` opcional quando o seu job de reporte puder repetir — uma repetição com o mesmo par `(meterCode, Idempotency-Key)` devolve o evento original com `duplicate: true` em vez de registrar um segundo.

<RequestExample>
  ```bash cURL theme={"dark"}
  curl -X POST https://api.therius.io/v1/subscription/usage \
    -H "Authorization: Bearer prv_production_your_key_here" \
    -H "Content-Type: application/json" \
    -H "Idempotency-Key: batch-2026-09-02T10:00Z" \
    -d '{
      "subscriptionId": "sub_abc123def456",
      "meterCode": "api_requests",
      "quantity": 500
    }'
  ```
</RequestExample>

<ResponseExample>
  ```json 200 OK theme={"dark"}
  {
    "id": "3f1c9a2e-8b7d-4e2a-9c31-6a0b5d4e7f88",
    "meterCode": "api_requests",
    "quantity": 500,
    "occurredAt": "2026-09-02T10:00:00Z",
    "duplicate": false
  }
  ```
</ResponseExample>


## OpenAPI

````yaml POST /subscription/usage
openapi: 3.1.0
info:
  title: Therius API
  description: REST API for payments, subscriptions, and billing plans.
  version: 1.0.0
servers:
  - url: https://api.therius.io/v1
    description: Production
  - url: https://api-sandbox.therius.io/v1
    description: Sandbox
security:
  - bearerAuth: []
paths:
  /subscription/usage:
    post:
      tags:
        - Subscriptions
      summary: Record a metered usage event
      description: >-
        Report a usage event against a subscription for a meter defined on its
        plan. At each renewal Therius aggregates the period's events per the
        meter's aggregation mode, prices them, and adds the result to the
        invoice. Meters and their per-plan pricing are configured in the
        Dashboard (Subscriptions → Usage Meters); this endpoint only ingests the
        raw events.
      operationId: recordSubscriptionUsage
      parameters:
        - name: Idempotency-Key
          in: header
          description: >-
            Optional. A replay with the same `(meterCode, Idempotency-Key)` pair
            returns the original event instead of recording a second one. Use it
            when your reporting job may retry.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - subscriptionId
                - meterCode
                - quantity
              properties:
                merchantCode:
                  type: string
                  description: Your merchant account identifier.
                subscriptionId:
                  type: string
                  description: UUID of the subscription the usage is attributed to.
                meterCode:
                  type: string
                  description: >-
                    The `code` of a usage meter belonging to your merchant
                    account, e.g. `api_requests`.
                  example: api_requests
                quantity:
                  type: number
                  description: Non-negative quantity for this event, in the meter's units.
                  example: 500
                occurredAt:
                  type: string
                  format: date-time
                  description: >-
                    Optional RFC 3339 timestamp of when the usage occurred.
                    Defaults to the time the request is received. Determines
                    which billing period the event falls into.
      responses:
        '200':
          description: Event recorded, or the original event on an idempotent replay.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                    description: UUID of the usage event.
                  meterCode:
                    type: string
                    description: The meter the event was recorded against.
                  quantity:
                    type: number
                    description: The recorded quantity.
                  occurredAt:
                    type: string
                    format: date-time
                    description: >-
                      Timestamp the event was attributed to (the billing-period
                      key).
                  duplicate:
                    type: boolean
                    description: >-
                      `true` when this response is an idempotent replay of a
                      previously recorded event.
        '400':
          description: >-
            Missing or invalid `subscriptionId`, `meterCode`, `quantity`, or
            `occurredAt`.
        '401':
          description: Missing or invalid API key.
        '403':
          description: Production access is not enabled for this account.
        '404':
          description: Subscription or meter not found under your merchant account.
        '429':
          description: Rate limit exceeded.
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >-
        Your secret API key: `Bearer prv_production_xxx` (production) or `Bearer
        prv_sandbox_xxx` (sandbox).

````