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

# Cambiar Plan

> Modifica el plan de una suscripción existente, permitiendo tanto actualizaciones como degradaciones a diferentes niveles de precios.<br/><br/>Nota&colon; Esto utilizará la información de pago existente del cliente para actualizar/degradar el plan.

## Cambios Programados de Plan

Use el parámetro `effective_at` para controlar cuándo entrará en vigor el cambio de plan:

| Valor               | Comportamiento                                                                                                                                        |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `immediately`       | Aplica el cambio de plan de inmediato. Este es el valor predeterminado.                                                                               |
| `next_billing_date` | Programa el cambio para la próxima fecha de facturación. El cliente conserva el acceso a su plan actual hasta que finalice el período de facturación. |

<Info>
  Los cambios de plan programados son ideales para degradaciones: los clientes mantienen los beneficios de su plan actual hasta el final del período de facturación, y luego cambian automáticamente al nuevo plan.
</Info>

Para cancelar un cambio de plan programado antes de que entre en vigor, use el endpoint [Cancelar Cambio de Plan Programado](/api-reference/subscriptions/cancel-change-plan).

## Manejo de Fallos de Pago

Use el parámetro `on_payment_failure` para controlar lo que sucede cuando falla el pago del cambio de plan:

| Valor            | Comportamiento                                                                                                       |
| ---------------- | -------------------------------------------------------------------------------------------------------------------- |
| `prevent_change` | Mantiene la suscripción en el plan actual hasta que el pago sea exitoso. El cambio de plan permanece pendiente.      |
| `apply_change`   | Aplica el cambio de plan inmediatamente, independientemente del resultado del pago. Este es el valor predeterminado. |

<Info>
  Si no se especifica `on_payment_failure`, el comportamiento predeterminado es el configurado a nivel de negocio en el panel de control.
</Info>

## Códigos de Descuento

Puedes aplicar uno o más **códigos de descuento acumulados** al cambiar de planes pasando el array `discount_codes` (máximo 20 entradas, aplicadas en el orden del array). El campo singular `discount_code` está obsoleto pero aún funciona para integraciones existentes; no se puede combinar con `discount_codes` en la misma solicitud.

| Valor de `discount_codes`           | Comportamiento                                                                                                  |
| ----------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| No proporcionado (`null` / omitido) | Los descuentos existentes con `preserve_on_plan_change=true` se preservan si son aplicables al nuevo producto.  |
| `[]` (array vacío)                  | **Todos** los descuentos existentes se eliminan de la suscripción.                                              |
| `["CODE_A", "CODE_B", ...]`         | Reemplaza cualquier descuento existente con este conjunto acumulado, validado y aplicado en el orden del array. |

<Tip>
  Usa códigos de descuento durante los cambios de plan para ofrecer precios promocionales en actualizaciones, o pasa códigos al migrar clientes a un nuevo nivel de plan.
</Tip>

<Tip>
  Use `prevent_change` para actualizaciones críticas donde desea asegurar el pago antes de otorgar acceso a características premium.
</Tip>


## OpenAPI

````yaml post /subscriptions/{subscription_id}/change-plan
openapi: 3.1.0
info:
  title: public
  description: ''
  license:
    name: Apache 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0
  version: 1.105.15
servers:
  - url: https://test.dodopayments.com/
    description: Test Mode Server Host
  - url: https://live.dodopayments.com/
    description: Live Mode Server Host
security: []
tags:
  - name: Products
  - name: Payments
  - name: Subscriptions
  - name: Addons
  - name: Customers
  - name: Refunds
  - name: Disputes
  - name: Events
  - name: License Keys
  - name: Entitlements
  - name: Licenses
  - name: Discounts
  - name: Meters
  - name: Credit Entitlements
  - name: Credit Entitlement Balances
  - name: Outgoing Webhooks
  - name: Checkout
  - name: Webhook Events
paths:
  /subscriptions/{subscription_id}/change-plan:
    post:
      tags:
        - Subscriptions
      operationId: update_subscription_plan_handler
      parameters:
        - name: subscription_id
          in: path
          description: Subscription Id
          required: true
          schema:
            type: string
          example: sub_Iuaq622bbmmfOGrVTqdXv
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateSubscriptionPlanReq'
        required: true
      responses:
        '200':
          description: >-
            Subscription plan changed. If on_payment_failure=prevent_change, the
            plan change is pending until payment succeeds.
        '409':
          description: >-
            A pending plan change already exists for this subscription
            (PendingPlanChangeExists)
        '422':
          description: Subscription is inactive or on-demand, plan change not supported
        '500':
          description: Something went wrong :(
      security:
        - API_KEY: []
      x-codeSamples:
        - lang: JavaScript
          source: |-
            import DodoPayments from 'dodopayments';

            const client = new DodoPayments({
              bearerToken: process.env['DODO_PAYMENTS_API_KEY'], // This is the default and can be omitted
            });

            await client.subscriptions.changePlan('sub_Iuaq622bbmmfOGrVTqdXv', {
              product_id: 'product_id',
              proration_billing_mode: 'prorated_immediately',
              quantity: 0,
            });
        - lang: Python
          source: |-
            import os
            from dodopayments import DodoPayments

            client = DodoPayments(
                bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"),  # This is the default and can be omitted
            )
            client.subscriptions.change_plan(
                subscription_id="sub_Iuaq622bbmmfOGrVTqdXv",
                product_id="product_id",
                proration_billing_mode="prorated_immediately",
                quantity=0,
            )
        - lang: Go
          source: "package main\n\nimport (\n\t\"context\"\n\n\t\"github.com/dodopayments/dodopayments-go\"\n\t\"github.com/dodopayments/dodopayments-go/option\"\n)\n\nfunc main() {\n\tclient := dodopayments.NewClient(\n\t\toption.WithBearerToken(\"My Bearer Token\"),\n\t)\n\terr := client.Subscriptions.ChangePlan(\n\t\tcontext.TODO(),\n\t\t\"sub_Iuaq622bbmmfOGrVTqdXv\",\n\t\tdodopayments.SubscriptionChangePlanParams{\n\t\t\tUpdateSubscriptionPlanReq: dodopayments.UpdateSubscriptionPlanReqParam{\n\t\t\t\tProductID:            dodopayments.F(\"product_id\"),\n\t\t\t\tProrationBillingMode: dodopayments.F(dodopayments.UpdateSubscriptionPlanReqProrationBillingModeProratedImmediately),\n\t\t\t\tQuantity:             dodopayments.F(int64(0)),\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n"
        - lang: Java
          source: >-
            package com.dodopayments.api.example;


            import com.dodopayments.api.client.DodoPaymentsClient;

            import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;

            import
            com.dodopayments.api.models.subscriptions.SubscriptionChangePlanParams;

            import
            com.dodopayments.api.models.subscriptions.UpdateSubscriptionPlanReq;


            public final class Main {
                private Main() {}

                public static void main(String[] args) {
                    DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();

                    SubscriptionChangePlanParams params = SubscriptionChangePlanParams.builder()
                        .subscriptionId("sub_Iuaq622bbmmfOGrVTqdXv")
                        .updateSubscriptionPlanReq(UpdateSubscriptionPlanReq.builder()
                            .productId("product_id")
                            .prorationBillingMode(UpdateSubscriptionPlanReq.ProrationBillingMode.PRORATED_IMMEDIATELY)
                            .quantity(0)
                            .build())
                        .build();
                    client.subscriptions().changePlan(params);
                }
            }
        - lang: Kotlin
          source: >-
            package com.dodopayments.api.example


            import com.dodopayments.api.client.DodoPaymentsClient

            import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient

            import
            com.dodopayments.api.models.subscriptions.SubscriptionChangePlanParams

            import
            com.dodopayments.api.models.subscriptions.UpdateSubscriptionPlanReq


            fun main() {
                val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv()

                val params: SubscriptionChangePlanParams = SubscriptionChangePlanParams.builder()
                    .subscriptionId("sub_Iuaq622bbmmfOGrVTqdXv")
                    .updateSubscriptionPlanReq(UpdateSubscriptionPlanReq.builder()
                        .productId("product_id")
                        .prorationBillingMode(UpdateSubscriptionPlanReq.ProrationBillingMode.PRORATED_IMMEDIATELY)
                        .quantity(0)
                        .build())
                    .build()
                client.subscriptions().changePlan(params)
            }
        - lang: Ruby
          source: |-
            require "dodopayments"

            dodo_payments = Dodopayments::Client.new(
              bearer_token: "My Bearer Token",
              environment: "test_mode" # defaults to "live_mode"
            )

            result = dodo_payments.subscriptions.change_plan(
              "sub_Iuaq622bbmmfOGrVTqdXv",
              product_id: "product_id",
              proration_billing_mode: :prorated_immediately,
              quantity: 0
            )

            puts(result)
        - lang: PHP
          source: |-
            <?php

            require_once dirname(__DIR__) . '/vendor/autoload.php';

            use Dodopayments\Client;
            use Dodopayments\Core\Exceptions\APIException;

            $client = new Client(
              bearerToken: getenv('DODO_PAYMENTS_API_KEY') ?: 'My Bearer Token',
              environment: 'test_mode',
            );

            try {
              $result = $client->subscriptions->changePlan(
                'sub_Iuaq622bbmmfOGrVTqdXv',
                productID: 'product_id',
                prorationBillingMode: 'prorated_immediately',
                quantity: 0,
                adaptiveCurrencyFeesInclusive: true,
                addons: [['addonID' => 'addon_id', 'quantity' => 0]],
                discountCode: 'discount_code',
                discountCodes: ['string'],
                effectiveAt: 'immediately',
                metadata: ['foo' => 'string'],
                onPaymentFailure: 'prevent_change',
              );

              var_dump($result);
            } catch (APIException $e) {
              echo $e->getMessage();
            }
        - lang: C#
          source: |-
            using DodoPayments.Client;
            using DodoPayments.Client.Models.Subscriptions;

            DodoPaymentsClient client = new();

            SubscriptionChangePlanParams parameters = new()
            {
                SubscriptionID = "sub_Iuaq622bbmmfOGrVTqdXv",
                ProductID = "product_id",
                ProrationBillingMode = ProrationBillingMode.ProratedImmediately,
                Quantity = 0,
            };

            await client.Subscriptions.ChangePlan(parameters);
        - lang: Rust
          source: |-
            use dodopayments::Client;

            #[tokio::main]
            async fn main() -> dodopayments::Result<()> {
                let client = Client::from_env()?;
                let subscription_id = "subscription_id";
                let result = client
                    .subscriptions()
                    .change_plan()
                    .subscription_id(subscription_id)
                    .body(dodopayments::models::SubscriptionsChangePlanParams {
                            product_id: Some("product_id".to_string()),
                            proration_billing_mode: Some("prorated_immediately".to_string()),
                            quantity: Some(0),
                            ..Default::default()
                        })
                    .await?;
                println!("{result:?}");
                Ok(())
            }
components:
  schemas:
    UpdateSubscriptionPlanReq:
      type: object
      required:
        - product_id
        - quantity
        - proration_billing_mode
      properties:
        adaptive_currency_fees_inclusive:
          type:
            - boolean
            - 'null'
          description: >-
            Whether adaptive currency fees should be included in the price
            (true) or added on top (false).

            If not specified, uses the subscription's stored setting.
        addons:
          type:
            - array
            - 'null'
          items:
            $ref: '#/components/schemas/AttachAddonReq'
          description: |-
            Addons for the new plan.
            Note : Leaving this empty would remove any existing addons
        discount_code:
          type:
            - string
            - 'null'
          description: >-
            DEPRECATED: Use discount_codes instead. Cannot be used together with
            discount_codes.
          deprecated: true
          x-stainless-deprecation-message: Use `discount_id` instead.
        discount_codes:
          type:
            - array
            - 'null'
          items:
            type: string
          description: >-
            Stacked discount codes to apply to the new plan. Max 20.

            Cannot be used together with discount_code.

            If provided, replaces any existing discount codes.

            Empty array removes all discounts.

            If not provided (None), existing discounts with
            preserve_on_plan_change=true are preserved.
        effective_at:
          $ref: '#/components/schemas/EffectiveAt'
          description: |-
            When to apply the plan change.
            - `immediately` (default): Apply the plan change right away
            - `next_billing_date`: Schedule the change for the next billing date
        metadata:
          oneOf:
            - type: 'null'
            - $ref: '#/components/schemas/Metadata'
              description: >-
                Metadata for the payment. If not passed, the metadata of the
                subscription will be taken
        on_payment_failure:
          oneOf:
            - type: 'null'
            - $ref: '#/components/schemas/OnPaymentFailure'
              description: >-
                Controls behavior when the plan change payment fails.

                - `prevent_change`: Keep subscription on current plan until
                payment succeeds

                - `apply_change` (default): Apply plan change immediately
                regardless of payment outcome


                If not specified, uses the business-level default setting.
        product_id:
          type: string
          description: Unique identifier of the product to subscribe to
        proration_billing_mode:
          $ref: '#/components/schemas/ProrationBillingMode'
          description: Proration Billing Mode
        quantity:
          type: integer
          format: int32
          description: Number of units to subscribe for. Must be at least 1.
          minimum: 0
    AttachAddonReq:
      type: object
      title: Attach Addon Request
      required:
        - addon_id
        - quantity
      properties:
        addon_id:
          type: string
        quantity:
          type: integer
          format: int32
          description: Number of units of this addon.
          minimum: 0
    EffectiveAt:
      type: string
      description: When to apply a subscription plan change.
      enum:
        - immediately
        - next_billing_date
    Metadata:
      type: object
      additionalProperties:
        type: string
      propertyNames:
        type: string
    OnPaymentFailure:
      type: string
      description: >-
        Specifies how to handle subscription plan changes when payment fails.


        This enum controls whether the subscription should be updated
        immediately

        or only after payment succeeds.
      enum:
        - prevent_change
        - apply_change
    ProrationBillingMode:
      type: string
      title: Proration Billing Mode
      enum:
        - prorated_immediately
        - full_immediately
        - difference_immediately
        - do_not_bill
  securitySchemes:
    API_KEY:
      type: http
      scheme: bearer

````