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

# Atualize o método de pagamento de uma assinatura

> Substitua o cartão de uma assinatura. Mudar o cartão é uma CIT e pode precisar de 3D Secure — registre um cartão cuja CIT você já fez, ou execute uma CIT de valor zero aqui.

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` substitui o cartão de uma assinatura e o mandato de
credencial armazenada dela, de modo que toda futura renovação (uma Merchant Initiated Transaction, MIT)
cite o `networkTransactionId` / `networkReferenceId` correto.

Mudar o cartão de uma assinatura é **sempre uma Cardholder Initiated Transaction (CIT)**,
e uma CIT pode exigir 3D Secure. Há duas formas de fornecer o novo cartão:

<SchemaLangNote lang="pt" />

<CardGroup cols={2}>
  <Card title="Modo record — card.tokenData" icon="shield-check">
    O token é um cartão que **já concluiu uma CIT** em outro lugar. Você executa a CIT (com
    3DS se o emissor pedir) por meio de `/payment/authorization` ou `/payment/purchase`, depois
    anexa o token resultante aqui. Nenhuma chamada ao gateway, nenhum 3DS neste endpoint.
    **Use isto para qualquer cartão que precise de 3D Secure.**
  </Card>

  <Card title="Modo CIT — card.nonceData / card.cardData" icon="credit-card">
    Executa uma CIT de valor zero aqui para validar o cartão e estabelecer um mandato novo, e pode
    **reativar uma assinatura `suspended`**. Essa CIT **não pode realizar um desafio de 3D Secure**
    — um cartão que exige 3DS falhará.
  </Card>
</CardGroup>

Qualquer um dos modos reinicia a sequência de novas tentativas da bandeira e dispara `subscription.payment_method_updated`.

## Modo record (recomendado)

Como a própria CIT deste endpoint não pode fazer um desafio de 3DS, a forma confiável de mudar um cartão
é executar você mesmo a CIT onde 3DS *é* suportado, depois registrá-la:

<Steps>
  <Step title="Execute uma CIT com capacidade 3DS">
    Chame `/payment/authorization` (uma autorização de valor zero ou pequena) ou `/payment/purchase` com
    `card.nonceData.tokenize: true` (ou `card.cardData.tokenize: true`) **e** um `shopper.id`.
    Trate qualquer `actionRequired` / desafio de 3DS com o SDK JS exatamente como você faria para um
    pagamento normal. Em caso de sucesso a resposta devolve um vault token e
    `card.networkTransactionId` / `card.networkReferenceId`.
  </Step>

  <Step title="Anexe o token à assinatura">
    `POST /subscription/{id}/payment-method` com `card.tokenData.token` definido como esse vault
    token. O Therius lê o mandato que o token armazenou na CIT dele — você não precisa passar
    `networkTransactionId` você mesmo. (Passe-o explicitamente apenas quando o cartão teve a CIT feita
    fora do Therius.)
  </Step>
</Steps>

<Note>
  O modo record **não pode reativar uma assinatura `suspended`** — ele não executa nenhuma cobrança para
  confirmar que o novo cartão funciona. Para uma assinatura suspensa, use o modo CIT (abaixo), ou execute uma
  cobrança de recuperação você mesmo primeiro.
</Note>

Forneça **exatamente um** instrumento de cartão — veja o painel de parâmetros acima para a lista completa de campos (`tokenData.token` para modo record; `nonceData`/`cardData` para modo CIT; `networkTransactionId`/`networkReferenceId` opcionais para um cartão cuja CIT foi feita fora do Therius).

## Resposta

Devolve `200 OK` com o objeto de assinatura atualizado.

### Eventos de webhook disparados

| Evento                                | Quando                                                                                                                                         |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `subscription.payment_method_updated` | Sempre, em caso de sucesso. A carga leva `mode: "record"` para o modo record.                                                                  |
| `subscription.reactivated`            | Apenas no modo CIT — disparado adicionalmente quando a assinatura estava `suspended` e a nova CIT + a cobrança de recuperação tiveram sucesso. |

## Erros

| Código | Significado                                                                                                                                                                         |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`  | Cartão ausente; modo record em uma assinatura `suspended`; o token não carrega nenhum mandato de CIT e nenhum `networkTransactionId` foi passado; ou a assinatura está `cancelled`. |
| `402`  | Modo CIT — a autorização do cartão foi recusada.                                                                                                                                    |
| `404`  | Assinatura não encontrada.                                                                                                                                                          |
| `422`  | Nenhum instrumento de cartão / instrumento inválido, ou um 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).

````