# Build a subscriptions integration

Create and manage subscriptions to accept recurring payments.

There are several ways to build a subscriptions integration with Stripe Billing. Before you begin, see [Design a subscriptions integration](https://docs.stripe.com/billing/subscriptions/design-an-integration.md) to understand the key decisions and required resources. Then, choose how you want to collect payments:

- **Checkout**: Use a prebuilt payment page that Stripe hosts or that you embed in your site. This option requires the least code.
- **Elements**: Build a custom payment form with UI components. Use the Checkout Sessions API for built-in support for tax, discounts, shipping, and currency conversion, or use the Subscriptions API to create subscriptions and confirm their first payments in your own flow.
- **Mobile**: Collect subscription payments in an iOS, Android, or React Native app.

To compare and learn more, see the options for accepting [online payments](https://docs.stripe.com/payments/online-payments.md).

> #### Sell subscriptions without code
> 
> If you don’t want to write code, you can set up basic subscriptions [manually in the Dashboard](https://docs.stripe.com/no-code/subscriptions.md) or use [payment links](https://docs.stripe.com/payment-links.md).

# Stripe-hosted page


# Full hosted page


#### Integration effort
Complexity: 2/5
#### UI customization
Limited customization
- 20 preset fonts
- 3 preset border radius
- Custom background and border color
- Custom logo

#### Integration type

Use prebuilt hosted pages to collect payments and manage your *subscriptions* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis).

[Try it out](https://checkout.stripe.dev/)

Build a *subscription* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis) flow using [Stripe Checkout](https://docs.stripe.com/payments/checkout.md) to sell fixed-price subscriptions.

- **Pricing**: Model your business by building a product catalog.
- **Signup and payment**: Add a checkout button that creates a Checkout Session and redirects customers to a Stripe-hosted payment page, and add a success page to your site. Stripe displays the payment form, collects payment details, and creates the customer and subscription.
- **Lifecycle and access**: Listen for subscription events and provision access to your service.
- **Customer management**: Set up the Stripe-hosted customer portal and add a button that sends customers to the portal to manage their subscription.
- **Testing**: Test payment methods and monitor subscription change events.

You also learn how to use [flexible billing mode](https://docs.stripe.com/billing/subscriptions/billing-mode.md) to access additional billing behavior and features.

After you complete the integration, you can extend it with features such as [taxes](https://docs.stripe.com/payments/checkout/taxes.md), [discounts](https://docs.stripe.com/billing/subscriptions/coupons.md#using-coupons-in-checkout), and [free trial periods](https://docs.stripe.com/billing/subscriptions/trials/free-trials.md).

## Set up Stripe

Install the Stripe client of your choice:

#### Ruby

```bash
# Available as a gem
sudo gem install stripe
```

```ruby
# If you use bundler, you can add this line to your Gemfile
gem 'stripe'
```

Optionally, install the Stripe CLI. The CLI provides [webhook](https://docs.stripe.com/webhooks.md#test-webhook) testing, and you can run it to create your products and prices.

Install the Stripe CLI using the installation script for your operating system. Script installations enable [automatic updates](https://docs.stripe.com/cli/upgrade) by default.

On macOS or Linux:

```bash
curl -fsSL https://cli.stripe.com/install.sh | sh
```

On Windows, run the following command in PowerShell:

```powershell
irm https://cli.stripe.com/install.ps1 | iex
```

After installation, open a new terminal and log in to your Stripe account:

```bash
stripe login
```

After you install the CLI, you can also install [agent tooling](https://docs.stripe.com/cli/agent/setup), or set up [autocompletion](https://docs.stripe.com/cli/completion).

> For more installation options for Windows, macOS, Linux, and Docker, see the [Stripe CLI readme](https://github.com/stripe/stripe-cli#installation) on GitHub.

## Create the pricing model [Dashboard or Stripe CLI]

[Recurring pricing models](https://docs.stripe.com/products-prices/pricing-models.md) represent the products or services you sell, how much they cost, what currency you accept for payments, and the service period for subscriptions. To build the pricing model, create [products](https://docs.stripe.com/api/products.md) (what you sell) and [prices](https://docs.stripe.com/api/prices.md) (how much and how often to charge for your products).

This example uses flat-rate pricing with two different service-level options: Basic and Premium. For each service-level option, you need to create a product and a recurring price. To add a one-time charge for something like a setup fee, create a third product with a one-time price.

Each product bills at monthly intervals. The price for the Basic product is 5 USD. The price for the Premium product is 15 USD. See the [flat rate pricing](https://docs.stripe.com/subscriptions/pricing-models/flat-rate-pricing.md) guide for an example with three tiers.

#### Dashboard

Go to the [Add a product](https://dashboard.stripe.com/test/products/create) page and create two products. Add one price for each product, each with a monthly recurring billing period:

- Premium product: Premium service with extra features

  - Price: Flat rate | 15 USD

- Basic product: Basic service with minimum features

  - Price: Flat rate | 5 USD

After you create the prices, record the price IDs so you can use them in other  steps. Price IDs look like this: `price_G0FvDp6vZvdwRZ`.

When you’re ready, use the **Copy to live mode** button at the top right of the page to clone your product from [a sandbox to live mode](https://docs.stripe.com/keys.md#test-live-modes).

#### API

You can use the API to create the [Products](https://docs.stripe.com/api/products.md) and [Prices](https://docs.stripe.com/api/prices.md).

Create the Premium product:

```curl
# tax_code: Required for Managed Payments. Optional otherwise. This example uses the tax code for SaaS for personal use.
curl https://api.stripe.com/v1/products \
  -u "<<YOUR_SECRET_KEY>>:" \
  --data-urlencode "name=Billing Guide: Premium Service" \
  -d "description=Premium service with extra features" \
  -d tax_code=txcd_10103000
```

Create the Basic product:

```curl
# tax_code: Required for Managed Payments. Optional otherwise. This example uses the tax code for SaaS for personal use.
curl https://api.stripe.com/v1/products \
  -u "<<YOUR_SECRET_KEY>>:" \
  --data-urlencode "name=Billing Guide: Basic Service" \
  -d "description=Basic service with minimum features" \
  -d tax_code=txcd_10103000
```

Record the product ID for each product. They look like this:

```json
{
  "id": "prod_H94k5odtwJXMtQ",
  "object": "product",
  "active": true,
  "attributes": [

  ],
  "created": 1587577341,
  "description": "Premium service with extra features",
  "images": [

  ],
  "livemode": false,
  "metadata": {
  },
  "name": "Billing Guide: Premium Service",
  "statement_descriptor": null,
  "type": "service",
  "unit_label": null,
  "updated": 1587577341
}
```

Use the product IDs to create a price for each product. The [unit_amount](https://docs.stripe.com/api/prices/object.md#price_object-unit_amount) number is in cents, so `1500` = 15 USD, for example.

Create the Premium price:

```curl
curl https://api.stripe.com/v1/prices \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "product={{PREMIUM_PRODUCT_ID}}" \
  -d unit_amount=1500 \
  -d currency=usd \
  -d "recurring[interval]=month"
```

Create the Basic price:

```curl
curl https://api.stripe.com/v1/prices \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "product={{BASIC_PRODUCT_ID}}" \
  -d unit_amount=500 \
  -d currency=usd \
  -d "recurring[interval]=month"
```

Record the price ID for each price so you can use them in subsequent steps. They look like this:

```json
{
  "id": "price_HGd7M3DV3IMXkC",
  "object": "price",
  "product": "prod_HGd6W1VUqqXGvr",
  "type": "recurring",
  "currency": "usd",
  "recurring": {
    "interval": "month",
    "interval_count": 1,
    "trial_period_days": null,
    "usage_type": "licensed"
  },
  "active": true,
  "billing_scheme": "per_unit",
  "created": 1589319695,
  "livemode": false,
  "lookup_key": null,
  "metadata": {},
  "nickname": null,
  "unit_amount": 1500,
  "unit_amount_decimal": "1500",
  "tiers": null,
  "tiers_mode": null,
  "transform_quantity": null
}
```

If you offer multiple billing periods, use Checkout to [upsell](https://docs.stripe.com/payments/checkout/upsells.md) customers on longer billing periods and collect more revenue upfront.

For other pricing models, see [Billing examples](https://docs.stripe.com/products-prices/pricing-models.md).

## Optional: Collect taxes [Server]

If your business collects sales tax, VAT, or GST, set `automatic_tax[enabled]=true` in the request that creates the Checkout Session in the next step. This enables [Stripe Tax](https://docs.stripe.com/tax.md) to calculate tax.

To configure your head office address, product tax codes, price tax behavior, and registrations, see [Collect taxes for recurring payments](https://docs.stripe.com/billing/taxes/collect-taxes.md).

Stripe only calculates tax in jurisdictions where you have an active [tax registration](https://docs.stripe.com/tax/registering.md). Without a registration in the customer’s location, the calculation returns zero tax. To learn more, see [Understand zero tax amounts](https://docs.stripe.com/tax/zero-tax.md).

Treat this step as part of the integration for any business that collects sales tax, VAT, or GST, and confirm whether the business does before leaving it out.

## Create a Checkout Session [Client and server]

Add a checkout button to your website that calls a server-side endpoint to create a Checkout Session.

```html
<html>
  <head>
    <title>Checkout</title>
  </head>
  <body>
    <form action="/create-checkout-session" method="POST">
      <!-- Note: If using PHP set the action to /create-checkout-session.php -->

      <input type="hidden" name="priceId" value="{{PRICE_ID}}" />
      <button type="submit">Checkout</button>
    </form>
  </body>
</html>
```

On the back end of your application, define an endpoint that [creates the session](https://docs.stripe.com/api/checkout/sessions/create.md) for your front end to call. You need these values:

- The price ID of the subscription the customer is signing up for (your front end passes this value)
- Your `success_url`, which is a page on your website that Checkout returns your customer to after they complete the payment

You can optionally:

- Configure a [billing cycle anchor](https://docs.stripe.com/billing/subscriptions/billing-cycle.md) to your subscription in this call.
- Use [custom text](https://docs.stripe.com/payments/checkout/custom-components.md?platform=web&payment-ui=stripe-hosted#customize-text) to include your subscription and cancellation terms, and a link to where your customers can update or cancel their subscription. We recommend configuring [email reminders and notifications](https://docs.stripe.com/invoicing/send-email.md#email-configuration) for your subscribers.

If you created a one-time price in [step 2](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md#create-pricing-model), pass that price ID as well. After creating a Checkout Session, redirect your customer to the [URL](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-url) returned in the response.

You can enable more accurate and predictable subscription behavior when you create a Checkout Session by setting the [billing mode](https://docs.stripe.com/billing/subscriptions/billing-mode.md) type to `flexible`. You must use the [Stripe API version 2025-06-30.basil](https://docs.stripe.com/upgrades.md) or later.

> You can use [lookup_keys](https://docs.stripe.com/products-prices/manage-prices.md#lookup-keys) to fetch prices rather than price IDs. For an example, see the [sample application](https://github.com/stripe-samples/subscription-use-cases/tree/main/fixed-price-subscriptions).

#### Ruby

```ruby

# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')

# The price ID passed from the front end.
#   price_id = params['priceId']
price_id = '{{PRICE_ID}}'

session = client.v1.checkout.sessions.create({
  success_url: 'https://example.com/success.html?session_id={CHECKOUT_SESSION_ID}',
  mode: 'subscription',
  line_items: [{
    # For usage-based billing, don't pass quantity
    quantity: 1,
    price: price_id
  }],
  subscription_data: {
    billing_mode: { type: 'flexible' }
  }
})

# Redirect to the URL returned on the session
#   redirect session.url, 303
```

This example customizes the `success_url` by appending the session ID. Learn more about [customizing your success page](https://docs.stripe.com/payments/checkout/custom-success-page.md).

From your [Dashboard](https://dashboard.stripe.com/settings/payment_methods), enable the payment methods you want to accept from your customers. Checkout supports [several payment methods](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#product-support).

## Provision and monitor subscriptions [Server]

After the subscription signup succeeds, the customer returns to your website at the `success_url`, which initiates a `checkout.session.completed` *webhook* (A configurable endpoint that executes when it receives certain event notifications from an event destination). When you receive a `checkout.session.completed` event, use [entitlements](https://docs.stripe.com/billing/entitlements.md) to provision the subscription. Continue to provision each month (if billing monthly) as you receive `invoice.paid` events. If you receive an `invoice.payment_failed` event, notify your customer and send them to the customer portal to update their payment method.

To determine the next step for your system’s logic, check the event type and parse the payload of each [event object](https://docs.stripe.com/api/events/object.md), such as `invoice.paid`. Store the IDs of the `Subscription` and `Customer` or `Account` objects in your database for verification.

For testing purposes, you can monitor events in the [Events tab](https://dashboard.stripe.com/workbench/events) of [Workbench](https://docs.stripe.com/workbench.md). For production, set up a webhook endpoint and subscribe to appropriate event types. If you don’t know your `STRIPE_WEBHOOK_SECRET` key, go to the destination details view of the [Webhooks tab](https://dashboard.stripe.com/workbench/webhooks) in Workbench to view it.

#### Ruby

```ruby

# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')

post '/webhook' do
  webhook_secret = '{{STRIPE_WEBHOOK_SECRET}}' # Example: whsec_c7681Dm
  payload = request.body.read
  if !webhook_secret.empty?
    # Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
    sig_header = request.env['HTTP_STRIPE_SIGNATURE']
    event = nil

    begin
      event = Stripe::Webhook.construct_event(
        payload, sig_header, webhook_secret
      )
    rescue JSON::ParserError => e
      # Invalid payload
      status 400
      return
    rescue Stripe::SignatureVerificationError => e
      # Invalid signature
      puts '⚠️  Webhook signature verification failed.'
      status 400
      return
    end
  else
    data = JSON.parse(payload, symbolize_names: true)
    event = Stripe::Event.construct_from(data)
  end
  # Get the type of webhook event sent
  event_type = event['type']
  data = event['data']
  data_object = data['object']

  case event_type
  when 'checkout.session.completed'
    # Payment is successful and the subscription is created.
    # Provision the subscription and save the customer ID to your database.
  when 'invoice.paid'
    # Continue to provision the subscription as payments continue to be made.
    # Store the status in your database and check when a customer accesses your service.
    # This approach helps you avoid hitting rate limits.
  when 'invoice.payment_failed'
    # The payment failed or the customer doesn't have a valid payment method.
    # The subscription becomes past_due. Notify your customer and send them to the
    # customer portal to update their payment information.
  else
    puts "Unhandled event type: #{event.type}"
  end

  status 200
end
```

The minimum event types to monitor:

| Event name                   | Description                                                                                        |
| ---------------------------- | -------------------------------------------------------------------------------------------------- |
| `checkout.session.completed` | Sent when a customer successfully completes the Checkout Session, informing you of a new purchase. |
| `invoice.paid`               | Sent each billing period when a payment succeeds.                                                  |
| `invoice.payment_failed`     | Sent each billing period if there’s an issue with your customer’s payment method.                  |

For even more events to monitor, see [Subscription webhooks](https://docs.stripe.com/billing/subscriptions/webhooks.md).

## Configure the customer portal [Dashboard]

The [customer portal](https://docs.stripe.com/customer-management.md) lets your customers directly manage their existing subscriptions and invoices.

Use the [Dashboard](https://dashboard.stripe.com/test/settings/billing/portal) to configure the portal. At a minimum, make sure to [configure the portal](https://docs.stripe.com/customer-management.md) so that customers can update their payment methods.

## Create a portal session [Server]

Define an endpoint that [creates the customer portal session](https://docs.stripe.com/api/customer_portal/sessions/create.md) for your front end to call.  Include the ID of the customer created by the Checkout Session that you saved while processing the `checkout.session.completed` webhook. You can also set a default redirect link for the portal in the Dashboard.

Pass an optional `return_url` value for the page on your site to redirect your customer to after they finish managing their subscription:

#### Accounts v2

#### Ruby

```ruby

# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')

# This is the URL that users are redirected to after they're done
# managing their billing.
return_url = '{{DOMAIN_URL}}' # Example: http://example.com
customer_account_id = '{{CUSTOMER_ACCOUNT_ID}}' # Example: acct_GBV60HKsE0mb5v

session = client.v1.billing_portal.sessions.create({
  customer_account: customer_account_id,
  return_url: return_url,
})

# Redirect to the URL for the session
#   redirect session.url, 303
```

#### Customers v1

#### Ruby

```ruby

# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
# Find your keys at https://dashboard.stripe.com/apikeys.
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')

# This is the URL that users are redirected to after they're done
# managing their billing.
return_url = '{{DOMAIN_URL}}' # Example: http://example.com
customer_id = '{{CUSTOMER_ID}}' # Example: cus_GBV60HKsE0mb5v

session = client.v1.billing_portal.sessions.create({
  customer: customer_id,
  return_url: return_url,
})

# Redirect to the URL for the session
#   redirect session.url, 303
```

## Send customers to the customer portal [Client]

On your front end, add a button to the page at the `success_url` that provides a link to the customer portal:

```html
<html>
  <head>
    <title>Manage Billing</title>
  </head>
  <body>
    <form action="/customer-portal" method="POST">
      <!-- Note: If using PHP set the action to /customer-portal.php -->
      <button type="submit">Manage Billing</button>
    </form>
  </body>
</html>
```

After exiting the customer portal, the customer returns to your website at the `return_url`. Continue to [monitor events](https://docs.stripe.com/billing/subscriptions/webhooks.md) to track the status of the customer’s subscription.

If you configure the customer portal to allow actions such as canceling a subscription, [monitor additional events](https://docs.stripe.com/customer-management/integrate-customer-portal.md#webhooks).

## Test your integration

### Test payment methods

Use the following table to test different payment methods and scenarios.

| Payment method    | Scenario                                                                                                                                                                                                                                                                                      | How to test                                                                                                                                                                                                 |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BECS Direct Debit | Your customer successfully pays with BECS Direct Debit.                                                                                                                                                                                                                                       | Fill out the form using the account number `900123456` and BSB `000000`. The confirmed PaymentIntent initially transitions to `processing`, then transitions to the `succeeded` status three minutes later. |
| BECS Direct Debit | Your customer’s payment fails with an `account_closed` error code.                                                                                                                                                                                                                            | Fill out the form using the account number `111111113` and BSB `000000`.                                                                                                                                    |
| Credit card       | The card payment succeeds and doesn’t require authentication.                                                                                                                                                                                                                                 | Fill out the credit card form using the credit card number `4242 4242 4242 4242` with any expiration, CVC, and postal code.                                                                                 |
| Credit card       | The card payment requires *authentication* (Strong Customer Authentication (SCA) is a regulatory requirement in effect as of September 14, 2019, that impacts many European online payments. It requires customers to use two-factor authentication like 3D Secure to verify their purchase). | Fill out the credit card form using the credit card number `4000 0025 0000 3155` with any expiration, CVC, and postal code.                                                                                 |
| Credit card       | The card is declined with a decline code like `insufficient_funds`.                                                                                                                                                                                                                           | Fill out the credit card form using the credit card number `4000 0000 0000 9995` with any expiration, CVC, and postal code.                                                                                 |
| SEPA Direct Debit | Your customer successfully pays with SEPA Direct Debit.                                                                                                                                                                                                                                       | Fill out the form using the account number `AT321904300235473204`. The confirmed PaymentIntent initially transitions to processing, then transitions to the succeeded status three minutes later.           |
| SEPA Direct Debit | Your customer’s PaymentIntent status transitions from `processing` to `requires_payment_method`.                                                                                                                                                                                              | Fill out the form using the account number `AT861904300235473202`.                                                                                                                                          |

### Monitor events

Set up webhooks to listen to subscription change events, such as upgrades and cancellations. You can view [subscription webhook events](https://docs.stripe.com/billing/subscriptions/webhooks.md) in the [Dashboard](https://dashboard.stripe.com/test/events) or with the [Stripe CLI](https://docs.stripe.com/webhooks.md#test-webhook).

Learn more about [testing your Billing integration](https://docs.stripe.com/billing/testing.md).

## See also

- [Offer customers a free trial period](https://docs.stripe.com/billing/subscriptions/trials/free-trials.md)
- [Apply discounts](https://docs.stripe.com/billing/subscriptions/coupons.md#using-coupons-in-checkout)
- [Manage prorations](https://docs.stripe.com/billing/subscriptions/prorations.md)
- [Integrate entitlements to manage access to your product’s features](https://docs.stripe.com/billing/entitlements.md)


