# Checkout existing subscription

> For the complete machine-readable documentation index, see [llms.txt](https://apidocs.chargebee.com/llms.txt).


[Idempotency Supported](/docs/api/v1/idempotency)

You can checkout an existing subscription(typically in the trial state) by passing in the plan, quantity and addon details(like [Update a Subscription](/docs/api/v1/subscriptions/update-a-subscription))

When the redirect URL is notified of the result, we would advise you to [retrieve the subscription](/docs/api/v1/subscriptions/retrieve-a-subscription) and verify the details.

#### Related Tutorial[](#related-tutorial)

-   [Upgrade existing subscription using Chargebee's hosted page](https://www.chargebee.com/tutorials/chargebee-js-checkout-existing-subscription/)

As mentioned before this behavior is very similar to the update subscription API call. All the web hook events will be fired only after the submission of payment details by the customer and successful checkout of subscription. Any errors related to the payment form that is submitted is handled as a response within the form so that the user is kept informed about the reason for failure to take corrective action.

## Sample Request

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v1/hosted_pages/checkout_existing \
     -u {site_api_key}:\
     -d "subscription[id]"="__test__5SK0bLNFRFuCRrBP6" \
     -d "subscription[plan_id]"="sub_plan1"
```

#### .NET

```dotnet
using ChargeBee.Api;
using ChargeBee.Models;

ApiConfig.Configure("{site}","{site_api_key}");
EntityResult result = HostedPage.CheckoutExisting()
		.SubscriptionId("__test__5SK0bLNFRFuCRrBP6")
		.SubscriptionPlanId("sub_plan1")
		.Request();

HostedPage hostedPage = result.HostedPage;
```

#### Go

```go
package main
import (
    "fmt"
    "github.com/chargebee/chargebee-go/v3"
    hostedpageAction "github.com/chargebee/chargebee-go/v3/actions/hostedpage"
    "github.com/chargebee/chargebee-go/v3/models/hostedpage"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := hostedpageAction.CheckoutExisting(&hostedpage.CheckoutExistingRequestParams{
        Subscription : &hostedpage.CheckoutExistingSubscriptionParams{
            Id : "__test__5SK0bLNFRFuCRrBP6",
            PlanId : "sub_plan1",
        },
    }).Request()
    if err != nil {
        fmt.Println(err)
    } else {
        HostedPage := res.HostedPage
    }
}
```

#### Go

```go
package main

import (
  "fmt"
  "github.com/chargebee/chargebee-go/v4"
)

func main() {
  config := &chargebee.ClientConfig{
    SiteName: "{site}",
    ApiKey: "{site_api_key}",
  }    
  client := chargebee.NewClient(config)
  req := &chargebee.HostedPageCheckoutExistingRequest{
    Subscription : &chargebee.HostedPageCheckoutExistingSubscription{
        Id : "__test__5SK0bLNFRFuCRrBP6",
        PlanId : "sub_plan1",
    },
}
  res, err := client.HostedPage.CheckoutExisting(req)
      if err != nil {
        fmt.Println(err)
    } else {
        HostedPage := res.HostedPage
    }
}
```

#### Java

```java
import com.chargebee.*;
import com.chargebee.ListResult;
import com.chargebee.models.*;
import com.chargebee.models.enums.*;
import java.io.IOException;

public class Sample {

    public static void main(String args[]) throws IOException, Exception {
        Environment.configure("{site}", "{site_api_key}");
        Result result = HostedPage.checkoutExisting()
            .subscriptionId("__test__5SK0bLNFRFuCRrBP6")
            .subscriptionPlanId("sub_plan1")
            .request();

        HostedPage hostedPage = result.hostedPage();
    }
}
```

#### Java

```java
import com.chargebee.v4.client.ChargebeeClient;
import com.chargebee.v4.models.hostedPage.HostedPage;
import com.chargebee.v4.models.hostedPage.params.HostedPageCheckoutExistingParams;
import com.chargebee.v4.models.hostedPage.responses.HostedPageCheckoutExistingResponse;

public class HostedPageCheckoutExisting {

    public static void main(String[] args) {
        ChargebeeClient client = ChargebeeClient.builder()
            .apiKey("{site_api_key}")
            .siteName("{site}")
            .build();

        HostedPageCheckoutExistingParams.SubscriptionParams subscriptionParams =
            HostedPageCheckoutExistingParams.SubscriptionParams.builder()
                .id("__test__5SK0bLNFRFuCRrBP6")
                .planId("sub_plan1")
                .build();

        HostedPageCheckoutExistingParams params = HostedPageCheckoutExistingParams.builder()
            .subscription(subscriptionParams)
            .build();

        HostedPageCheckoutExistingResponse response = client.hostedPages().checkoutExisting(params);

        HostedPage hostedPage = response.getHostedPage();
    }
}
```

#### Node.js

```node
import Chargebee from "chargebee";

const chargebee = new Chargebee({
    site: "{site}",
    apiKey: "{site_api_key}",
});

try {
    const result = await chargebee.hostedPage.checkoutExisting({
        subscription: {
            id: "__test__5SK0bLNFRFuCRrBP6",
            plan_id: "sub_plan1"
        }
    });

    console.log(result);
    const hostedPage = result.hosted_page;
} catch (err) {
    console.log(err);
}
```

#### PHP

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use Chargebee\ChargebeeClient;

$chargebee = new ChargebeeClient(options: [
    "site" => "{site}",
    "apiKey" => "{site_api_key}",
]);
$result = $chargebee->hostedPage()->checkoutExisting([
    "subscription" => [
        "id" => "__test__5SK0bLNFRFuCRrBP6",
        "plan_id" => "sub_plan1"
    ]
]);
$hostedPage = $result->hosted_page;
```

#### Python

```python
from chargebee import Chargebee

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
response = cb_client.HostedPage.checkout_existing(
    cb_client.HostedPage.CheckoutExistingParams(
        subscription=cb_client.HostedPage.CheckoutExistingSubscriptionParams(
            id="__test__5SK0bLNFRFuCRrBP6",
            plan_id="sub_plan1"
        )
    )
)
hosted_page = response.hosted_page
```

#### Ruby

```ruby
require 'chargebee'

ChargeBee.configure(:site => "{site}",
  :api_key => "{site_api_key}")

result = ChargeBee::HostedPage.checkout_existing({
  :subscription => {
    :id => "__test__5SK0bLNFRFuCRrBP6",
    :plan_id => "sub_plan1"
  }
})

hosted_page = result.hosted_page
```

## Sample Response

```json
{
  "hosted_page": {
    "created_at": 1517506795,
    "embed": true,
    "expires_at": 1517510395,
    "id": "__test__IOc7dyRIztXRW3StXU1aEv72qcdxcuoscu",
    "layout": "in_app",
    "object": "hosted_page",
    "state": "created",
    "type": "checkout_existing",
    "url": "https://yourapp.chargebee.com/pages/v3/__test__IOc7dyRIztXRW3StXU1aEv72qcdxcuoscu/checkout",
    "content": {}
  }
}
```

## URL Format

**POST** https://[site].chargebee.com/api/v1/hosted_pages/checkout_existing

## Input Parameters

- `replace_addon_list` (optional, boolean, default=false)
  Should be true if the existing addons should be replaced with the ones that are being passed.

- `billing_cycles` (optional, integer, min=0)
  The number of billing cycles the subscription runs before canceling. If not provided, then the billing cycles set for the plan is used.

- `redirect_url` (optional, string, max chars=250)
  The customers will be redirected to this URL upon successful checkout. The hosted page id and state will be passed as parameters to this URL. Although the customer will be redirected to the `redirect_url` after successful checkout, we do not recommend relying on it for completing critical post-checkout actions. This is because redirection may not happen due to unforeseen reasons. Chargebee recommends listening to appropriate webhooks such as `[subscription_created](/docs/api/v1/events)`
  
  or `[invoice_generated](/docs/api/v1/events)` to verify a successful checkout.
  
  **Note** : - Redirect URL configured in Settings > Hosted Pages Settings would be overriden by this redirect URL.  
  _Eg : http://yoursite.com?id=&state=succeeded_
  
  -   This parameter is not applicable for iframe messaging.

- `cancel_url` (optional, string, max chars=250)
  The customers will be redirected to this URL upon canceling checkout. The hosted page id and state will be passed as parameters to this URL.
  
  **Note** : - Cancel URL configured in Settings > Hosted Pages Settings would be overriden by this cancel URL.  
  _Eg : http://yoursite.com?id=&state=cancelled_
  
  -   This parameter is not applicable for iframe messaging and [in-app](https://www.chargebee.com/docs/2.0/checkout.html) checkout.

- `pass_thru_content` (optional, string, max chars=2048)
  You can pass through any content specific to the hosted page request and get it back after user had submitted the hosted page.

- `embed` (optional, boolean, default=true)
  If true then hosted page formatted to be shown in iframe. If false, it is formatted to be shown as a separate page.
  
  **Note** : For [in-app](https://www.chargebee.com/docs/checkout-v3.html) checkout, default is false.

- `iframe_messaging` (optional, boolean, default=false)
  If true then iframe will communicate with the parent window. Applicable only for embedded(iframe) hosted pages. If you're using iframe\_messaging you need to implement onSuccess & onCancel callbacks.
  
  **Note** : This parameter is not applicable for [in-app](https://www.chargebee.com/docs/checkout-v3.html) checkout.

- `subscription` (optional, string)
  Parameters for subscription
  - `id` (required, string, max chars=50)
    A unique and immutable identifier for the subscription. If not provided, it is autogenerated.
  - `plan_id` (optional, string, max chars=100)
    Identifier of the plan for this subscription
  - `plan_quantity` (optional, integer, default=1, min=1)
    Represents the plan quantity for this subscription.
  - `start_date` (optional, timestamp(UTC) in seconds)
    The new start date of a `future` subscription. Applicable only for `future` subscriptions.
  - `trial_end` (optional, timestamp(UTC) in seconds)
    The time at which the trial has ended or will end for the subscription. This is only allowed when the subscription `status` is `future` , `in_trial` , or `cancelled`. Also, the value must not be earlier than `changes_scheduled_at` or `start_date`. **Note**: This parameter can be backdated (set to a value in the past) only when the subscription is in `cancelled` or `in_trial` `status`. Do this to keep a record of when the trial ended in case it ended at some point in the past. When `trial_end` is backdated, the subscription immediately goes into `active` or `non_renewing` status.
  - `coupon` (optional, string, max chars=100)
    Used to uniquely identify the coupon in your website/application and to integrate with Chargebee.
    
    **Note:**
    
    When the coupon ID contains a special character; for example: `#`, the API returns an error. Make sure that you [encode](https://www.urlencoder.org/) the coupon ID in the path parameter before making an API call.

- `card` (optional, enumerated string)
  Parameters for card
  - `gateway` (optional, enumerated string)
    Name of the gateway this payment source is stored with.
    Possible enum values:
      - `chargebee`
        Chargebee test gateway.
      - `stripe`
        Stripe is a payment gateway.
      - `braintree`
        Braintree is a payment gateway.
      - `authorize_net`
        Authorize.net is a payment gateway
      - `paypal_pro`
        PayPal Pro Account is a payment gateway.
      - `pin`
        Pin is a payment gateway
      - `eway`
        eWAY Account is a payment gateway.
      - `eway_rapid`
        eWAY Rapid is a payment gateway.
      - `worldpay`
        WorldPay is a payment gateway
      - `balanced_payments`
        Balanced is a payment gateway
      - `beanstream`
        Bambora(formerly known as Beanstream) is a payment gateway.
      - `bluepay`
        BluePay is a payment gateway.
      - `elavon`
        Elavon Virtual Merchant is a payment solution.
      - `first_data_global`
        First Data Global Gateway Virtual Terminal Account
      - `hdfc`
        HDFC Account is a payment gateway.
      - `migs`
        MasterCard Internet Gateway Service payment gateway.
      - `nmi`
        NMI is a payment gateway.
      - `ogone`
        Ingenico ePayments (formerly known as Ogone) is a payment gateway.
      - `paymill`
        PAYMILL is a payment gateway.
      - `paypal_payflow_pro`
        PayPal Payflow Pro is a payment gateway.
      - `sage_pay`
        Sage Pay is a payment gateway.
      - `tco`
        2Checkout is a payment gateway.
      - `wirecard`
        WireCard Account is a payment service provider.

- `addons` (optional, array)
  Parameters for addons
  - `id` (optional, string, max chars=100)
    Identifier of the addon. Multiple addons can be passed.
  - `quantity` (optional, integer)
    Quantity of the addon. Applicable for addons with `pricing_model` other than `flat_fee` .

## Returns

- `hosted_page` (Hosted page object)
  Resource object representing hosted\_page
