> ## 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.

# Crea y activa una suscripción

> Inscribe a un cliente en un plan y cobra el primer ciclo de facturación. Realiza la CIT inicial que registra el mandato recurrente.

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>;
};

`POST /subscription` inscribe a un cliente en un plan y establece el mandato recurrente que
ancla cada futura Merchant Initiated Transaction (MIT). Inscribir a un cliente es una
Cardholder Initiated Transaction (CIT), y una CIT puede requerir 3D Secure. Dos modos:

<SchemaLangNote lang="es" />

<CardGroup cols={2}>
  <Card title="Modo CIT — nonceData / cardData" icon="credit-card">
    Therius ejecuta la CIT inicial + el primer cobro aquí. El cliente debe estar presente. Esta CIT
    **no puede llevar a cabo un desafío de 3D Secure** — una tarjeta que requiere 3DS fallará.
  </Card>

  <Card title="Modo record — tokenData" icon="shield-check">
    El token es una tarjeta que **ya completó una CIT** (incluyendo 3DS) a través de
    `/payment/authorization` o `/payment/purchase`. No se ejecuta una segunda CIT aquí.
    **Usa esto para cualquier tarjeta que necesite 3D Secure.**
  </Card>
</CardGroup>

Suministra la tarjeta como **exactamente un** instrumento — `nonceData`, `cardData` (solo servidores
que cumplen PCI DSS), o `tokenData`.

<Warning>
  `cardOnFile` e `instalments` se ignoran aquí — Therius es dueño del mandato. En modo record
  `networkTransactionId` / `networkReferenceId` se leen del token; pásalos solo para una
  tarjeta CIT'ada fuera de Therius.
</Warning>

## Modo record

Ejecuta tú mismo una CIT con capacidad 3DS, luego adjunta el resultado:

<Steps>
  <Step title="Ejecuta la CIT vía /payment/*">
    Llama a `/payment/authorization` (monto 0 = verificación de cuenta) o `/payment/purchase`
    con `card.<x>.tokenize: true` + un `shopper.id`, y maneja cualquier desafío de 3DS con el
    SDK JS como lo harías para un pago normal. La respuesta devuelve un token `vt_...`.
  </Step>

  <Step title="Crea la suscripción">
    `POST /subscription` con `card.tokenData.token`. Para el ciclo 1:
    <br />• prueba o `startAt` diferido → no se cobra nada;
    <br />• cobraste el primer ciclo en tu CIT (`/payment/purchase`) → pasa también
    `firstPaymentId` (el `id` de pago de la respuesta de esa llamada); Therius marca la primera
    factura como pagada y la enlaza, sin cobro;
    <br />• tu CIT fue una verificación de valor cero → omite `firstPaymentId`; Therius cobra
    el ciclo 1 como una MIT contra el mandato registrado (revierte la suscripción con un `402`
    si se rechaza).
    <br />El objeto `firstCycle` de la respuesta informa lo que ocurrió.
  </Step>
</Steps>

Ver el panel de parámetros de arriba para la lista completa de campos — `planId`, `customerEmail` y un instrumento de tarjeta (`nonceData`/`cardData`/`tokenData` — exactamente uno) son obligatorios; `customerName`/`customerDocument`, `firstPaymentId` (modo record), `startAt`, `parentSubscriptionId`/`propagateLifecycle` y `metadata` son opcionales.

## Respuesta

Una solicitud exitosa devuelve `201 Created` con el objeto de suscripción completo, incluyendo el `id` de la suscripción, el `status` inicial, las fechas de inicio y fin del período actual, y la primera factura.

### Estado en la creación

| Estado     | Cuándo ocurre                                                                            |
| ---------- | ---------------------------------------------------------------------------------------- |
| `active`   | El plan no tiene prueba; el primer cobro tuvo éxito.                                     |
| `trialing` | El plan tiene un `trialPeriodDays` configurado.                                          |
| `past_due` | La CIT inicial falló. Raro — normalmente se devuelve un `402` en el rechazo en su lugar. |

## Errores

| Código | Significado                                                                                                                                                         |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`  | Plan no encontrado o inactivo; o (modo record) el token no lleva ningún mandato de CIT, o `firstPaymentId` no se resuelve a un pago liquidado que cobró este token. |
| `402`  | El cobro de la CIT inicial fue rechazado (modo CIT), o la MIT del primer ciclo fue rechazada (modo record — la suscripción se revierte).                            |
| `409`  | `Idempotency-Key` duplicado con un cuerpo de solicitud en conflicto.                                                                                                |
| `422`  | Error de validación — p. ej. no se proporcionó ningún instrumento de tarjeta, un nonce expirado/usado, o un plan inválido.                                          |

<RequestExample>
  ```bash cURL theme={"dark"}
  curl -X POST https://api.therius.io/v1/subscription \
    -H "Authorization: Bearer prv_production_your_key_here" \
    -H "Idempotency-Key: $(uuidgen)" \
    -H "Content-Type: application/json" \
    -d '{
      "merchantCode": "MERCHANT_001",
      "planId": 42,
      "customerEmail": "ada@example.com",
      "customerName": "Ada Lovelace",
      "card": { "nonceData": { "nonce": "<fresh nonce from JS SDK>" } }
    }'
  ```
</RequestExample>

<ResponseExample>
  ```json 201 Created theme={"dark"}
  {}
  ```
</ResponseExample>


## OpenAPI

````yaml POST /subscription
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:
    post:
      tags:
        - Subscriptions
      summary: Create and activate a subscription
      operationId: createSubscription
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - merchantCode
                - planId
                - customerEmail
                - card
              properties:
                merchantCode:
                  type: string
                  description: Your merchant account identifier.
                planId:
                  type: integer
                  description: >-
                    ID of an active plan. Determines amount, currency, interval
                    and trial.
                customerEmail:
                  type: string
                  description: >-
                    Subscriber email. Used for billing and dunning
                    notifications.
                customerName:
                  type: string
                  description: Subscriber full name, as it should appear on invoices.
                customerDocument:
                  type: string
                  description: >-
                    Subscriber national ID / tax document, where a market
                    requires it (e.g. Brazil CPF/CNPJ).
                card:
                  $ref: '#/components/schemas/SubscriptionCard'
                firstPaymentId:
                  type: string
                  description: >-
                    Record mode only, when a first payment is due. The payment
                    `id` from the `/payment/authorization` or
                    `/payment/purchase` call in which you ran this card CIT -
                    Therius verifies it charged the same vaulted token in the
                    plan currency, then marks cycle 1 paid and links it (no
                    charge). Omit and Therius charges cycle 1 as an MIT against
                    the recorded mandate.
                startAt:
                  type: string
                  description: >-
                    RFC 3339 future timestamp to defer the first charge. Omit to
                    activate (or start the trial) immediately.
                parentSubscriptionId:
                  type: string
                  description: >-
                    UUID of an existing subscription to attach this one to as a
                    child (add-on hierarchies).
                propagateLifecycle:
                  type: boolean
                  description: >-
                    When `true`, pause/cancel on `parentSubscriptionId` cascades
                    to this subscription. Requires `parentSubscriptionId`.
                metadata:
                  type: object
                  additionalProperties:
                    type: string
                  description: >-
                    Arbitrary string key/value pairs, echoed on subscription
                    responses and webhooks.
      responses:
        '201':
          description: >-
            Subscription created. Body is the Subscription plus `firstInvoice`,
            and `firstCycle` in record mode (what happened to cycle 1).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Subscription'
components:
  schemas:
    SubscriptionCard:
      description: >-
        Card input for creating a subscription. Enrolling a customer is a CIT
        and a CIT may require 3D Secure — pick the mode that fits:


        • **CIT mode** (`nonceData` / `cardData`): Therius runs the initial CIT
        + first charge here. The customer must be present. This CIT cannot carry
        out a 3D Secure challenge, so a 3DS-required card will fail — use record
        mode for those.


        • **Record mode** (`tokenData`): the token is a card that already
        completed a CIT — including any 3DS — through `/payment/authorization`
        or `/payment/purchase` (with `card.<x>.tokenize: true` + `shopper.id`).
        No second CIT runs. The mandate is read from the token; pass
        `networkTransactionId` / `networkReferenceId` explicitly only for a card
        CIT'd outside Therius. For cycle 1: with a trial or deferred start
        nothing is charged; with `firstPaymentId` set Therius marks the first
        invoice paid and links that payment; otherwise Therius charges cycle 1
        as an MIT against the recorded mandate.


        Provide exactly ONE of `cardData`, `nonceData`, or `tokenData`.
        `cardOnFile` and `instalments` are not accepted — Therius owns the
        mandate.
      allOf:
        - $ref: '#/components/schemas/CardInstrument'
        - type: object
          properties:
            networkTransactionId:
              type: string
              description: >-
                Record mode only. The Network Transaction ID from the original
                CIT. Optional when the token already carries its mandate;
                required when recording a card CIT'd outside Therius.
            networkReferenceId:
              type: string
              description: >-
                Record mode only. The Mastercard TLID (or scheme equivalent)
                from the original CIT, alongside `networkTransactionId`.
                Defaults to `networkTransactionId` when omitted.
    Subscription:
      type: object
      description: >-
        A customer enrollment in a plan. `plan` is embedded on
        single-subscription responses. Invoice/event history is not included
        here - use the invoice endpoints.
      properties:
        id:
          type: string
          description: Subscription UUID.
        merchantId:
          type: integer
          description: The merchant account that owns the subscription.
        planId:
          type: integer
          description: ID of the plan this subscription is enrolled in.
        customerEmail:
          type: string
          description: Subscriber email, used for billing and dunning notifications.
        customerName:
          type: string
          description: Subscriber name as it appears on invoices.
        customerDocument:
          type: string
          description: >-
            Subscriber national ID / tax document, where a market requires it
            (e.g. Brazil CPF/CNPJ).
        cardBrand:
          type: string
          description: Brand of the card on the mandate, e.g. `visa`.
        status:
          type: string
          enum:
            - pending
            - trialing
            - active
            - past_due
            - suspended
            - paused
            - cancelled
            - completed
          description: >-
            `pending` - awaiting first charge; `trialing` - in a free trial;
            `active` - billing normally; `past_due` - a renewal failed and
            dunning is running; `suspended` - dunning exhausted, needs a new CIT
            (`POST /subscription/{id}/payment-method` in CIT mode) to recover;
            `paused` - billing stopped on request, resumable; `cancelled` -
            terminated; `completed` - reached `maxBillingCycles`.
        currentPeriodStart:
          type: string
          format: date-time
          description: Start of the current billing period.
        currentPeriodEnd:
          type: string
          format: date-time
          description: End of the current billing period.
        nextBillingDate:
          type: string
          format: date-time
          description: When the next renewal charge is scheduled.
        trialStart:
          type: string
          format: date-time
          description: Trial start, when the plan has a trial.
        trialEnd:
          type: string
          format: date-time
          description: Trial end - the first real charge date.
        dunningAttemptCount:
          type: integer
          description: Failed-renewal retry attempts made in the current dunning sequence.
        activatedAt:
          type: string
          format: date-time
          description: When the subscription first became `active`.
        cancelledAt:
          type: string
          format: date-time
        pausedAt:
          type: string
          format: date-time
        suspendedAt:
          type: string
          format: date-time
        startAt:
          type: string
          format: date-time
          description: Deferred start, when creation set a future `startAt`.
        cyclesCompleted:
          type: integer
          description: Number of billing cycles charged so far.
        completedAt:
          type: string
          format: date-time
          description: When the subscription reached `maxBillingCycles`.
        parentSubscriptionId:
          type: string
          description: Parent subscription UUID, for add-on hierarchies.
        propagateLifecycle:
          type: boolean
          description: Whether pause/cancel on the parent cascades to this subscription.
        pendingPlanId:
          type: integer
          description: >-
            Plan the subscription will switch to at the next cycle, set by a
            `next_billing` change-plan.
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
        plan:
          $ref: '#/components/schemas/Plan'
    CardInstrument:
      description: >-
        The payment instrument. Provide exactly ONE of `cardData`, `nonceData`,
        or `tokenData` — they are interchangeable alternatives, not fields to
        send together. `cardData` carries a raw PAN and requires your server to
        be PCI DSS compliant; `nonceData` is a single-use nonce from the Therius
        JS SDK; `tokenData` reuses a stored `vt_...` vault token.
      oneOf:
        - title: Raw card (PCI DSS)
          type: object
          required:
            - cardData
          properties:
            cardData:
              $ref: '#/components/schemas/CardData'
        - title: SDK nonce
          type: object
          required:
            - nonceData
          properties:
            nonceData:
              $ref: '#/components/schemas/NonceData'
        - title: Vault token
          type: object
          required:
            - tokenData
          properties:
            tokenData:
              $ref: '#/components/schemas/TokenData'
    Plan:
      type: object
      description: >-
        A reusable billing plan. `amount` is a flat integer in the currency
        minor units (with separate `currency` + `exponent`) - not an Amount
        object.
      properties:
        id:
          type: integer
          description: The plan unique integer ID.
        merchantId:
          type: integer
          description: The merchant account that owns the plan.
        name:
          type: string
        description:
          type: string
        interval:
          type: string
          enum:
            - day
            - week
            - month
            - year
          description: Billing interval unit. Immutable after creation.
        intervalCount:
          type: integer
          description: >-
            Number of `interval` units between charges - `month` + `3` bills
            quarterly.
        amount:
          type: integer
          description: >-
            Recurring charge in the currency minor units (e.g. `2999` = $29.99
            at exponent 2). Immutable after creation.
        currency:
          type: string
          description: ISO 4217 currency code. Immutable after creation.
        exponent:
          type: integer
          description: >-
            Decimal places for `amount` / `introAmount` - `2` for USD, `0` for
            JPY.
        trialPeriodDays:
          type: integer
          description: Free-trial length in days before the first charge. `0` for no trial.
        introAmount:
          type: integer
          description: >-
            Introductory charge in minor units for the first
            `introBillingCycles` cycles, if set.
        introBillingCycles:
          type: integer
          description: >-
            How many initial cycles are billed at `introAmount` before the rate
            reverts to `amount`.
        maxBillingCycles:
          type: integer
          description: >-
            Total cycles after which the subscription auto-completes. `0` =
            open-ended.
        availableCountries:
          type: array
          items:
            type: string
          description: >-
            ISO 3166-1 alpha-2 codes the plan is offered in. Empty = available
            everywhere.
        isActive:
          type: boolean
          description: >-
            Whether the plan accepts new subscribers. Existing subscriptions are
            unaffected when this is `false`.
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    CardData:
      type: object
      description: >-
        Raw card details. Only if your server is PCI DSS compliant to handle raw
        PANs — otherwise collect the card with the Therius JS SDK and send
        `nonceData`.
      properties:
        cardNumber:
          type: string
          description: Full PAN, digits only.
          example: '4111111111111111'
        cardholderName:
          type: string
          description: Name as it appears on the card.
          example: Ada Lovelace
        expiryMonth:
          type: string
          description: Two-digit expiry month, e.g. `12`.
          example: '12'
        expiryYear:
          type: string
          description: Four-digit expiry year, e.g. `2030`.
          example: '2030'
        cvv:
          type: string
          description: Card verification value (3 or 4 digits).
          example: '123'
        tokenize:
          type: boolean
          description: >-
            Set to `true` to save this card as a reusable token. Requires
            `shopper.id` in the request.
        cardAddress:
          $ref: '#/components/schemas/CardAddress'
        documentNumber:
          type: string
          description: Cardholder tax/document ID, required by some LATAM acquirers.
        typeOverride:
          type: string
          description: Override the detected card type, e.g. `debit`.
    NonceData:
      type: object
      description: >-
        Single-use nonce from the Therius JS SDK — no card data touches your
        server. Nonces are single-use and expire after a short window.
      properties:
        nonce:
          type: string
          description: The nonce string returned by the SDK.
        cardholderName:
          type: string
          description: Cardholder name.
        cardAddress:
          $ref: '#/components/schemas/CardAddress'
        tokenize:
          type: boolean
          description: >-
            Save the card as a token after payment. Requires `shopper.id` in the
            request.
        typeOverride:
          type: string
          description: Override the detected card type.
    TokenData:
      type: object
      description: A `vt_...` vault token for a card the shopper previously tokenized.
      properties:
        token:
          type: string
          description: Token ID returned from a prior tokenization.
        cvv:
          type: string
          description: CVV, if re-collection is required by the acquirer.
        cardAddress:
          $ref: '#/components/schemas/CardAddress'
    CardAddress:
      type: object
      properties:
        line1:
          type: string
        line2:
          type: string
        city:
          type: string
        state:
          type: string
        postalCode:
          type: string
        country:
          type: string
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >-
        Your secret API key: `Bearer prv_production_xxx` (production) or `Bearer
        prv_sandbox_xxx` (sandbox).

````