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

# Actualiza el método de pago de una suscripción

> Reemplaza la tarjeta de una suscripción. Cambiar la tarjeta es una CIT y puede necesitar 3D Secure — registra una tarjeta que ya CIT'aste, o ejecuta una CIT de valor cero aquí.

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/{id}/payment-method` reemplaza la tarjeta de una suscripción y su mandato
de credencial almacenada, de modo que cada futura renovación (una Merchant Initiated Transaction, MIT)
cite el `networkTransactionId` / `networkReferenceId` correcto.

Cambiar la tarjeta de una suscripción es **siempre una Cardholder Initiated Transaction (CIT)**,
y una CIT puede requerir 3D Secure. Hay dos formas de suministrar la nueva tarjeta:

<SchemaLangNote lang="es" />

<CardGroup cols={2}>
  <Card title="Modo record — card.tokenData" icon="shield-check">
    El token es una tarjeta que **ya completó una CIT** en otro lugar. Tú ejecutas la CIT (con
    3DS si el emisor lo pide) a través de `/payment/authorization` o `/payment/purchase`, luego
    adjuntas el token resultante aquí. Sin llamada al gateway, sin 3DS en este endpoint.
    **Usa esto para cualquier tarjeta que necesite 3D Secure.**
  </Card>

  <Card title="Modo CIT — card.nonceData / card.cardData" icon="credit-card">
    Ejecuta una CIT de valor cero aquí para validar la tarjeta y establecer un mandato fresco, y puede
    **reactivar una suscripción `suspended`**. Esta CIT **no puede llevar a cabo un desafío de 3D Secure**
    — una tarjeta que requiere 3DS fallará.
  </Card>
</CardGroup>

Cualquiera de los dos modos reinicia la secuencia de reintentos de la bandera y dispara `subscription.payment_method_updated`.

## Modo record (recomendado)

Como la propia CIT de este endpoint no puede hacer un desafío de 3DS, la forma confiable de cambiar una tarjeta
es ejecutar tú mismo la CIT donde 3DS *sí* está soportado, luego registrarla:

<Steps>
  <Step title="Ejecuta una CIT con capacidad 3DS">
    Llama a `/payment/authorization` (una autorización de valor cero o pequeña) o `/payment/purchase` con
    `card.nonceData.tokenize: true` (o `card.cardData.tokenize: true`) **y** un `shopper.id`.
    Maneja cualquier `actionRequired` / desafío de 3DS con el SDK JS exactamente como lo harías para un
    pago normal. En caso de éxito la respuesta devuelve un vault token y
    `card.networkTransactionId` / `card.networkReferenceId`.
  </Step>

  <Step title="Adjunta el token a la suscripción">
    `POST /subscription/{id}/payment-method` con `card.tokenData.token` establecido en ese vault
    token. Therius lee el mandato que el token almacenó en su CIT — no necesitas pasar
    `networkTransactionId` tú mismo. (Pásalo explícitamente solo cuando la tarjeta fue CIT'ada
    fuera de Therius.)
  </Step>
</Steps>

<Note>
  El modo record **no puede reactivar una suscripción `suspended`** — no ejecuta ningún cobro para
  confirmar que la nueva tarjeta funciona. Para una suscripción suspendida, usa el modo CIT (abajo), o ejecuta un
  cobro de recuperación tú mismo primero.
</Note>

Proporciona **exactamente un** instrumento de tarjeta — ver el panel de parámetros de arriba para la lista completa de campos (`tokenData.token` para modo record; `nonceData`/`cardData` para modo CIT; `networkTransactionId`/`networkReferenceId` opcionales para una tarjeta CIT'ada fuera de Therius).

## Respuesta

Devuelve `200 OK` con el objeto de suscripción actualizado.

### Eventos de webhook disparados

| Evento                                | Cuándo                                                                                                                                          |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `subscription.payment_method_updated` | Siempre, en caso de éxito. La carga lleva `mode: "record"` para el modo record.                                                                 |
| `subscription.reactivated`            | Solo en modo CIT — se dispara adicionalmente cuando la suscripción estaba `suspended` y la nueva CIT + el cobro de recuperación tuvieron éxito. |

## Errores

| Código | Significado                                                                                                                                                                          |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `400`  | Falta la tarjeta; modo record en una suscripción `suspended`; el token no lleva ningún mandato de CIT y no se pasó ningún `networkTransactionId`; o la suscripción está `cancelled`. |
| `402`  | Modo CIT — la autorización de la tarjeta fue rechazada.                                                                                                                              |
| `404`  | Suscripción no encontrada.                                                                                                                                                           |
| `422`  | Ningún instrumento de tarjeta / instrumento inválido, o un nonce expirado/usado.                                                                                                     |

<RequestExample>
  ```bash Record mode theme={"dark"}
  curl -X POST https://api.therius.io/v1/subscription/sub_abc123def456/payment-method \
    -H "Authorization: Bearer prv_production_your_key_here" \
    -H "Content-Type: application/json" \
    -d '{
      "merchantCode": "MERCHANT_001",
      "card": { "tokenData": { "token": "vt_9f2c..." } }
    }'
  ```

  ```bash CIT mode theme={"dark"}
  curl -X POST https://api.therius.io/v1/subscription/sub_abc123def456/payment-method \
    -H "Authorization: Bearer prv_production_your_key_here" \
    -H "Content-Type: application/json" \
    -d '{
      "merchantCode": "MERCHANT_001",
      "card": { "nonceData": { "nonce": "<fresh nonce from JS SDK>" } }
    }'
  ```
</RequestExample>

<ResponseExample>
  ```json 200 OK theme={"dark"}
  {}
  ```
</ResponseExample>


## OpenAPI

````yaml POST /subscription/{id}/payment-method
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/{id}/payment-method:
    post:
      tags:
        - Subscriptions
      summary: Update the card on a subscription
      operationId: updateSubscriptionPaymentMethod
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - merchantCode
                - card
              properties:
                merchantCode:
                  type: string
                  description: Your merchant account identifier.
                card:
                  $ref: '#/components/schemas/SubscriptionCardUpdate'
      responses:
        '200':
          description: Payment method updated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Subscription'
components:
  schemas:
    SubscriptionCardUpdate:
      description: >-
        Card input for replacing the card on a subscription. Changing the card
        is always a CIT and a CIT may require 3D Secure — pick the mode that
        fits:


        • **Record mode** (`tokenData`): the token is a card that already
        completed a CIT elsewhere. Run your own 3DS-capable CIT via
        `/payment/authorization` or `/payment/purchase` (with
        `card.<x>.tokenize: true` + `shopper.id`), then attach the resulting
        `vt_...` token here. No gateway call, no 3DS. The mandate is read from
        the token; pass `networkTransactionId` / `networkReferenceId` explicitly
        only for a card CIT'd outside Therius. Cannot reactivate a `suspended`
        subscription.


        • **CIT mode** (`nonceData` / `cardData`): runs a zero-value CIT here
        and can reactivate a `suspended` subscription — but this CIT cannot
        carry out a 3D Secure challenge, so a card that requires 3DS will fail.
        Use record mode for those.


        Provide exactly ONE of `cardData`, `nonceData`, or `tokenData`.
      allOf:
        - $ref: '#/components/schemas/CardInstrument'
        - type: object
          properties:
            networkTransactionId:
              type: string
              description: >-
                Record mode only. The scheme mandate reference (Network
                Transaction ID) returned by the original CIT. Optional when the
                token already carries its mandate; required when recording a
                card that was 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).

````