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

# Subscriptions

> Manage ongoing payment relationships with your customers using Flowglad Subscriptions.

Subscriptions represent an ongoing payment relationship with your customer. Flowglad provides a robust subscription model with carefully considered defaults to handle common billing scenarios effectively.

## What is a Subscription?

A Subscription in Flowglad tracks the details of a recurring charge for a customer, including what products or services they're paying for, how often, and their current status.

Key concepts:

* **Customers are always on a subscription, even if they aren't paying:** when a customer is created, they are subscribed to the **default plan** for their [pricing model](/features/pricing-models). If they purchase a subscription product while they are currently subscribed to your pricing model's free plan, their current subscription will change to be attached to the new price.
* **One Current Subscription per Customer (Default):** By default, a customer can only have one active subscription at a time (see "Current vs Non-Current Subscriptions" below). This encourages simpler billing management. If you need customers to have multiple simultaneous subscriptions, you can enable the `allow_multiple_subscriptions_per_customer` setting at the organization level in your dashboard [settings page](https://app.flowglad.com/settings).
* **Billing Cycle Anchor Date:** The `billingCycleAnchorDate` (set from the `startDate` on creation) determines the day of the month billing occurs. If this date doesn't exist in a given month (e.g., the 31st in February), billing occurs on the last day of that month.
* **Billing Periods:** Defined by the `startDate`, `interval` (e.g., `Month`, `Year`), and `intervalCount`. Flowglad automatically calculates the `currentBillingPeriodStart` and `currentBillingPeriodEnd` for each cycle.

## Subscription Structure

Each `Subscription` record has one or more `SubscriptionItem` records.

* **`Subscription` Record:** Holds the core details like the customer (`customerId`), overall status, billing cycle information (`interval`, `intervalCount`, `billingCycleAnchorDate`), trial period (`trialEnd`), and potentially default/backup payment methods. It also has a primary `priceId` which often corresponds to the initial item purchased. But note: the `SubscriptionItem`s define the actual billing components.
* **`SubscriptionItem` Record:** Represents a specific product or service line item within the subscription. Each item has its own `priceId`, `quantity`, and `unitPrice`. This allows for subscriptions with multiple components, potentially added or changed over time. The sum of active subscription items determines the amount billed each period (for non-usage-based items).

### Current vs Non-Current Subscriptions

Depending on its status, a subscription can either be **current** or not. A current subscription will grant feature access and usage credits. A non-current subscription will not.
Current subscriptions have one of the following statuses:

* `"active"`
* `"past_due"`
* `"trialing"`
* `"cancellation_scheduled"`
* `"unpaid"`

Subscriptions in all other statuses will be inactive.

## Creating a Subscription

There are two primary ways to create a subscription:

### 1. Via Checkout Session

Customers can initiate subscriptions themselves by completing a checkout session for a product with a `subscription` type price.

* **How:** This can be done through hosted product/price purchase pages or programmatically using the [`useBilling()` hook's `createCheckoutSession` method](/features/checkout-sessions#using-usebilling-hook).
* **Use Case:** Standard customer sign-ups and purchases where the customer interacts directly with a checkout flow initiated from within the product
* **Payment Method:** Checkout Sessions typically require collecting payment details (unless a trial is offered).

<Info>
  Learn more about setting up checkouts in the [Checkout Sessions documentation](/features/checkout-sessions).
</Info>

### 2. Via API

You can programmatically create subscriptions using the [API endpoint](/api-reference/subscriptions/create-subscription)

* **How:** Requires providing `customerId`, `priceId`, `startDate`, `interval`, and `intervalCount`.
* **Use Case:** Ideal for scenarios where you create subscriptions automatically based on actions within your application, such as user sign-up, plan changes initiated within your UI, or migrations.
* **Payment Method:** Creating subscriptions via the API **does not** require a `defaultPaymentMethodId` or `backupPaymentMethodId`. This is useful for starting customers on free trials without asking for card details upfront. The subscription status will initially be `Incomplete` if `autoStart` is false and there's no trial or payment method. It becomes `Trialing` if a `trialEnd` date is provided, or `Active` if `autoStart` is true and a default payment method exists for the customer or is provided.

## Subscription Lifecycle & Billing

Subscriptions transition through various statuses and billing cycles over their lifetime.

### Statuses

A subscription can be in one of several states (`SubscriptionStatus`):

* **`Trialing`:** Active during a free trial period. Considered a "current" subscription.
* **`Active`:** The standard state for a paying, up-to-date subscription. Considered "current".
* **`PastDue`:** Payment failed, but Flowglad may retry. Considered "current".
* **`Unpaid`:** Payment failed after retries; requires manual intervention or updated payment method. Considered "current".
* **`Incomplete`:** Created but needs setup (e.g., payment method added) before becoming active. Not "current".
* **`IncompleteExpired`:** A related Checkout Session expired before completion. Not "current".
* **`CancellationScheduled`:** Will be canceled at a future date (usually the end of the current billing period). Considered "current" until the cancellation date.
* **`Canceled`:** The subscription has ended and is no longer active. Not "current".

You can check if a subscription is in any of the "current" states (`Active`, `PastDue`, `Trialing`, `CancellationScheduled`, `Unpaid`) using helper functions or by checking the status directly.

### Billing Periods & Transitions

At the end of each `currentBillingPeriodEnd`, a transition occurs:

1. A new billing period is calculated based on the anchor date, interval, and interval count.
2. For upcoming charges, a `BillingRun` is generated.

### Charging Behavior

* **`runBillingAtPeriodStart`:** This boolean field on the `Subscription` determines *when* the charge for a billing period is attempted.
  * **Default for `subscription` Price Type:** `true`. Charges are typically attempted at the *start* of the billing period (e.g., paying for the upcoming month).
  * **Default for `usage` Price Type:** `false`. Charges are attempted at the *end* of the billing period after usage for that period has been recorded.
* **Overrides:** This default behavior can be overridden when creating or updating the subscription if needed.

## Canceling a Subscription

Flowglad offers flexibility in how subscriptions can be canceled.

### Cancellation Options

* **Immediately:** The subscription is canceled right away. Proration logic may apply depending on your settings (though explicit proration controls are still evolving).
* **At End of Current Billing Period:** The subscription remains active until the `currentBillingPeriodEnd`, at which point it transitions to `Canceled`. The status becomes `CancellationScheduled` until then.
* **At a Future Date (Coming Soon):** Functionality to cancel on a specific arbitrary date in the future is planned.

### Methods for Cancellation

1. **Flowglad Dashboard:** Manually cancel subscriptions directly within the Flowglad UI.
2. **API:** Programmatically cancel subscriptions using the [API endpoint](/api-reference/subscriptions/cancel-subscription) or SDK methods ([client](/sdks/react#cancelsubscription), [server](/sdks/server#cancelsubscription)).
3. **Customer Self-Service:** Allow customers to manage their own subscriptions.
   * **Hosted Billing Portal:** (available for livemode customers only) A no-code option accessible via a unique URL for your organization. The `billingPortalUrl` is returned in customer billing details from `useBilling` or the [get billing details API](/api-reference/customer/get-billing-details). It can also be found in the customer details page in your Flowglad dashboard.
   * **Headless Implementation:** Use the `useBilling()` hook's `cancelSubscription` function (ensure it's used within a `<FlowgladProvider>` context) to build a completely custom cancellation UI.

## Uncanceling a Subscription

If a subscription has been scheduled for cancellation (status `cancellation_scheduled`), you can reverse the cancellation before it takes effect. This restores the subscription to its previous state (either `active` or `trialing`) and ensures billing will continue as normal.

### When Uncancel is Available

Uncancel is available for subscriptions that have a **scheduled cancellation** (status `cancellation_scheduled`). This typically happens when you cancel a subscription with the "At End of Current Billing Period" option.
Once a subscription is immediately canceled (status `canceled`), it cannot be uncanceled. A new subscription would need to be created.

For paid subscriptions, a valid payment method must exist for the subscription. For free subscriptions, no payment method is required.

### Methods for Uncanceling

* **[React SDK](/sdks/react#uncancelsubscription):** Use the `uncancelSubscription` method from the `useBilling()` hook for client-side implementation
* **[Server SDK](/sdks/server#uncancelsubscription):** Use the `uncancelSubscription` method from `FlowgladServer` for server-side implementation
* **[API](/api-reference/subscriptions/uncancel-subscription):** Make a POST request to `/api/v1/subscriptions/{id}/uncancel`

See the SDK documentation for detailed code examples.

## Adjusting a Subscription

Flowglad supports upgrading and downgrading subscriptions mid-billing cycle with automatic proration handling. This allows customers to change their plan at any time without waiting for the next billing period.

### What is a Subscription Adjustment?

A subscription adjustment changes the products or services a customer is subscribed to. This can be:

* **Upgrade:** Moving to a higher-priced plan (e.g., from Basic to Pro)
* **Downgrade:** Moving to a lower-priced plan (e.g., from Pro to Basic)
* **Lateral change:** Switching to a different plan at the same price point

### Adjustment Timing

When an adjustment occurs depends on the `timing` parameter:

* **Auto (default):** Flowglad automatically determines the best timing by comparing the total monetary value of subscription items:

  * Upgrades (new total > current total) apply immediately with proration (customer gets new features right away)
  * Downgrades (new total \< current total) apply at the end of the current billing period (customer keeps current plan until they've used what they paid for)
  * Same-price changes (new total = current total) apply immediately (no financial impact)

  The total is calculated as `unitPrice × quantity` summed across all subscription items.

* **Immediately:** The adjustment takes effect right away. For upgrades, the customer is charged the prorated difference for the remainder of the billing period. For downgrades, the plan changes immediately but no refund is issued.

* **At End of Current Billing Period:** The adjustment is scheduled for the end of the billing period. This is only valid for downgrades (changes with zero or negative net charge).

### Proration

Proration ensures fair billing when plans change mid-cycle. Flowglad uses a "fair value" calculation:

1. Calculate the value of the old plan for the time already used
2. Calculate the value of the new plan for the remaining time in the billing period
3. Determine the total fair value and compare against what has already been paid
4. Charge only the difference (for upgrades)

**Example:** A customer on a \$100/month plan upgrades to a \$200/month plan halfway through the billing period:

* Old plan value (first half): \$50
* New plan value (second half): \$100
* Total fair value: \$150
* Already paid: \$100
* Proration charge: \$50

<Note>
  Downgrades do not issue refunds. When using `auto` timing, downgrades are scheduled for the end of the billing period so the customer continues to receive the value of their current plan.
</Note>

You can disable proration by setting `prorate: false` when adjusting. This applies the plan change immediately but delays the pricing change until the next billing period. This effectively gives the customer the upgraded features for free until the period ends.

<Warning>
  The `prorate` option only applies to `immediately` and `auto` timing. When using `at_end_of_period`, there is no proration since the change takes effect at the start of the next billing cycle.
</Warning>

### Methods for Adjusting

* **[React SDK](/sdks/subscription-management#adjust-subscriptions):** Use the `adjustSubscription` method from the `useBilling()` hook for client-side implementation
* **[Server SDK](/sdks/subscription-management#adjust-subscriptions):** Use the `adjustSubscription` method from `FlowgladServer` for server-side implementation

### Restrictions

Subscription adjustments have the following restrictions:

* The subscription must be in an active state (not `canceled`, `incomplete_expired`, etc.)
* The subscription must be a renewing subscription (not a one-time purchase)
* The subscription cannot be a free plan (use `createSubscription` to upgrade from free)
* The subscription cannot have the `doNotCharge` flag set
* A valid payment method is required for proration charges (upgrades with `prorate: true`)
* The new price must belong to the same pricing model as the subscription
* Only recurring (subscription-type) prices can be used
* For downgrades with [resource features](/features/resources) (e.g., team seats), claimed resources must fit within the new capacity—excess claims must be released before the adjustment can proceed

<Info>
  Resource claims (like team seats) persist across subscription adjustments. When upgrading, claims are preserved and new capacity is immediately available. When downgrading, Flowglad validates that active claims don't exceed the new capacity. See [Resources](/features/resources#adjusting-subscriptions-with-resources) for detailed examples.
</Info>

<Warning>
  For subscriptions on a free trial without a payment method attached, proration upgrades will fail because there is no way to charge for the prorated amount. To upgrade a trialing subscription without a payment method, either:

  1. Collect a payment method first using a checkout session
  2. Use `prorate: false` to skip the immediate charge (customer gets features now, pays at next billing period)
</Warning>

### Usage-Based Pricing and Adjustments

Subscription adjustments only affect recurring (subscription-type) prices. **Usage-based pricing is not prorated during adjustments.**

* Usage charges continue to accumulate throughout the billing period regardless of any subscription adjustments
* Usage is billed at the end of the billing period based on actual consumption
* If you adjust a subscription mid-period, the customer will still be charged for all usage accrued during that period

<Info>
  To include usage-based pricing in a subscription, add usage prices as separate subscription items when creating the subscription. These items are billed based on metered usage rather than the adjustment proration logic.
</Info>
