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

# Cambia piano

> Modifica il piano di un abbonamento esistente, consentendo sia gli aggiornamenti che i downgrade a diversi livelli di prezzo.<br/><br/>Nota&colon; Questo utilizzerà le informazioni di pagamento esistenti del cliente per aggiornare/downgradare il piano.

## Modifiche Pianificate al Piano

Usa il parametro `effective_at` per controllare quando la modifica del piano ha effetto:

| Valore              | Comportamento                                                                                                                                           |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `immediately`       | Applica subito la modifica del piano. Questo è il comportamento predefinito.                                                                            |
| `next_billing_date` | Pianifica la modifica per la prossima data di fatturazione. Il cliente mantiene l'accesso al piano attuale fino al termine del periodo di fatturazione. |

<Info>
  Le modifiche pianificate al piano sono ideali per i downgrade: i clienti mantengono i benefici del loro piano attuale fino alla fine del periodo di fatturazione, per poi passare automaticamente al nuovo piano.
</Info>

Per annullare una modifica pianificata del piano prima che entri in vigore, utilizza l'endpoint [Annulla Modifica Pianificata del Piano](/api-reference/subscriptions/cancel-change-plan).

## Gestione dei Fallimenti di Pagamento

Usa il parametro `on_payment_failure` per controllare cosa succede quando il pagamento per la modifica del piano fallisce:

| Valore           | Comportamento                                                                                                                   |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `prevent_change` | Mantieni l'abbonamento sul piano attuale fino a quando il pagamento ha successo. La modifica del piano rimane in sospeso.       |
| `apply_change`   | Applica immediatamente la modifica del piano indipendentemente dall'esito del pagamento. Questo è il comportamento predefinito. |

<Info>
  Se `on_payment_failure` non è specificato, il comportamento predefinito dipende dal tuo settaggio aziendale configurato nella dashboard.
</Info>

## Codici Sconto

Puoi applicare uno o più **codici sconto cumulabili** quando cambi piano passando l'array `discount_codes` (massimo 20 voci, applicate nell'ordine dell'array). Il campo singolare `discount_code` è deprecato ma funziona ancora per le integrazioni esistenti; non può essere combinato con `discount_codes` nella stessa richiesta.

| Valore `discount_codes`       | Comportamento                                                                                                     |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Non fornito (`null` / omesso) | Gli sconti esistenti con `preserve_on_plan_change=true` sono preservati se applicabili al nuovo prodotto.         |
| `[]` (array vuoto)            | **Tutti** gli sconti esistenti sono rimossi dall'abbonamento.                                                     |
| `["CODE_A", "CODE_B", ...]`   | Sostituisce eventuali sconti esistenti con questo set cumulabile, convalidato e applicato nell'ordine dell'array. |

<Tip>
  Usa i codici sconto durante i cambiamenti di piano per offrire prezzi promozionali sugli upgrade, o passa i codici quando migrano i clienti a un nuovo livello di piano.
</Tip>

<Tip>
  Usa `prevent_change` per upgrade critici in cui vuoi assicurarti il pagamento prima di concedere l'accesso alle funzionalità 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.106.2
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
  - name: Payment Connector Webhooks
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
      title: Metadata
      description: >-
        Arbitrary key-value metadata. Values can be string, integer, number, or
        boolean.
      additionalProperties:
        oneOf:
          - type: string
            title: String
          - type: integer
            title: Integer
            format: int64
          - type: number
            title: Number
            format: double
          - type: boolean
            title: Boolean
        title: Metadata Value
        description: Metadata value can be a string, integer, number, or boolean
    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

````