Weiter zum Inhalt
Konto erstellen oder anmelden
Das Logo der Stripe-Dokumentation
/
KI fragen
Konto erstellenAnmelden
Jetzt starten
Zahlungen
Umsatz
Plattformen und Marktplätze
Geldmanagement
Entwicklerressourcen
APIs und SDKsHilfe
ÜbersichtAlle Produkte anzeigen
Informationen zu APIs
Beginnen Sie mit der Entwicklung
Konto erstellen
Quickstarts
Entwicklung starten
Entwicklung per LLM
Stripe verwenden, ohne Code zu erstellen
Auf Stripe umsteigen
Häufige Anwendungsszenarien
ÜbersichtAls Start-up einfache Zahlungen akzeptierenAls Saas-Start-up Abonnements verkaufenEntwickeln einer Abonnement-Lösung mit nutzungsbasierten PreisenPersönliche ZahlungsannahmeRechnungen senden, um Zahlungen einzuziehen
Vereinigte Staaten
Deutsch
StartseiteJetzt starten

Notiz

Bis jetzt ist diese Seite noch nicht in dieser Sprache verfügbar. Wir arbeiten aber verstärkt daran, unsere Dokumentation in weiteren Sprachen bereitzustellen, und werden die Übersetzung sofort anzeigen, sobald diese verfügbar ist.

Build a subscriptions solution for an AI startup with a usage-based pricing model

Create a customized payments integration to handle billing for usage-based pricing models.

This guide describes how SaaS startups can build a usage-based pricing model with a customized UI and payment flow with Stripe. As an example, the guide uses a fictional AI company called Alpaca AI, that’s integrating with Stripe to provide a fixed fee and overages pricing model for their Llama Chat model. Alpaca AI charges customers a flat rate per month for a base package, and any usage beyond that limit is billed separately.

Create a Stripe account

Before integrating with Stripe, you must create a Stripe account.

  1. Create an account by entering your email address, full name, country, and creating a password.
  2. Fill out your business profile.
  3. In the Dashboard, click Verify your email. A verification email is sent to your email address.
  4. Verify your email address.

Set up testing environment

Before processing live transactions, test your integration with Stripe’s testing tools, including sandboxes and test clocks. Set these up early so you can iterate and tune your integration before going live.

Create a sandbox

First, create a sandbox. Configure the sandbox to match your live mode configuration, so you can test and stage changes on an ongoing basis.

Create a test clock

Next, create a test clock to simulate the forward movement of time in sandbox. As you increment the test clock, resources such as Subscriptions change state and trigger webhook events.

  1. In the Stripe Dashboard, go to the test clocks page in the Dashboard.
  2. Click + New simulation.
  3. In the Create new simulation modal, enter a name for the simulation. You can use this to describe the simulation you’re testing, like Annual renewal or Free trial.
  4. Set the frozen time of the clock. This is the starting point for your simulation. You can set this to a time in the future or in the past, but you can only move it forward in time after you set it.

To simulate subscription scenarios, click the Add dropown and select Customer. You only need to enter a name for the customer but for some scenarios, like tax collection and calculation, you need to add other information, like billing and shipping addresses.

Next, click the Add dropown and select Subscription. Configure the subscription to suit your scenario.

You can add additional customers and subscriptions to follow the rest of this guide.

Set up a pricing model

In this example, Alpaca AI charges customers for access to their LLM services by using a fixed fee and overages pricing model, with the following rates:

License Fee
Per user100 USD
Usage Fee
0-10000 USD
1000+0.04 USD

To implement this model, you create a meter to record the usage, products and prices to represent your service, a customer, and a customer subscription.

Create a meter

Meters specify how to aggregate meter events over a billing period. Meter events represent all actions that customers take in your system (for example, API requests). Meters attach to prices and form the basis of what’s billed.

For the Alpaca AI example, meter events are the number of tokens a customer uses in a query. The meter is the sum of tokens over a month.

You can use the Stripe Dashboard or API to configure a meter. To use the API with the Stripe CLI to create a meter, get started with the Stripe CLI.

  1. On the Meters page, click Create meter.
  2. On the Create meter page, do the following:
    • For Meter name, enter the name of the meter to display and for organization purposes. For the Alpaca AI example, enter “Alpaca AI tokens.”
    • For Event name, enter the name to display in meter events when reporting usage to Stripe. For the Alpaca AI example, enter “alpaca_ai_tokens.”
    • Set the Aggregation method in the dropdown:
      • For the Alpaca AI example, select Sum. This will sum the values reported (in this example, number of tokens a customer uses) to determine the usage to bill for.
      • Choose Count to bill based on the number of events reported.
      • Choose Last to bill based on the last value reported.
      • Use the preview pane to set example usage events and verify the aggregation method.
    • Click Create meter.
    • (Optional) Under Advanced settings, specify the Dimensions that you want to tag your usage data with. To generate granular segment specific alerts, or to granularly price usage based on a combination of attributes, submit your usage data with dimensions that are populated for analytics and reporting. Some example dimensions are LLM model, token type, region, and event type.

Create the pricing model

Use the Stripe Dashboard or API to create a pricing model that includes your Products and their pricing options. Prices define the unit cost, currency, and billing period.

For the Alpaca AI example, you create a product with a metered price of 0.04 USD per hundred units, billed at a monthly interval. Use the meter that you created in the previous step.

  1. On the Product catalog page, click Create product.
  2. On the Add a product page, do the following:
    1. For Name, enter the name of your product. For the Alpaca AI example, enter Alpaca AI usage.
    2. (Optional) For Description, add a description that appears in Checkout, in the customer portal and in quotes.
    3. Select Recurring.
    4. Under Billing period, select More pricing options.
  3. On the Add price page, do the following:
    1. Under Choose your pricing model, select Usage-based.
    2. Choose your pricing structure:
      • For the Alpaca AI example, select Per Tier and Graduated.
      • In the first row of the grid, set First unit to 0, Last unit to 1,000, Per unit to 0 USD, and Flat fee to 0 USD.
      • In the second row of the grid, set First unit to 1,001, Last unit to ∞, Per unit to 0.04 USD, and Flat fee to 0 USD.
      • After you create the first product, create another product to charge customers the 100 USD fee at the beginning of the month. A customer’s second invoice contains their usage fees from the previous month and their license fee for the upcoming month.
      • (Optional) To bill customers the initial license fee at the end of the month, update the first row of the grid to set the Flat fee to 100 USD.
    3. Under Meter, select the meter you created previously. For the Alpaca AI example, select Alpaca AI tokens from the dropdown.
    4. Select the Billing period. For the Alpaca AI example, select Monthly.
    5. Click Next.
    6. Click Add Product.

Next, create the 100 USD monthly fee.

  1. On the Product catalog page, click Create product.
  2. On the Add a product page, do the following:
    • For Name, enter the name of your product. For the Alpaca AI example, enter Alpaca AI license fee.
    • (Optional) For Description, add a description that appears in Checkout, in the customer portal and in quotes.
    • Select Recurring.
    • Under Billing period, select More pricing options.
  3. On the Add price page, do the following:
    • Select *Recurring.
    • For Amount, enter 100 USD.
    • For Currency, select USD.
    • For Billing Period, select Monthly.
    • Click Next.
    • Click Add Product.

Set up promotion codes

To set up a promotion code, you create a coupon and promotion code, then apply the promotion code to a subscription.

Create a coupon

Create coupons in the Dashboard or with the API:

  1. In the Dashboard, open the Products page.
  2. Click Coupons.
  3. Click +New.
  4. In the Create a coupon dialog, enter the coupon’s parameters.
  5. Click Create coupon.

The following are all the settings for coupons. The name is the only setting you can edit after you create the coupon.

SettingDescription
NameThe name of the coupon that appears on receipts and invoices.
ID optionalA unique identifier for the coupon in the API. If you leave this field blank, Stripe generates an ID for you.
TypeDetermines whether a coupon discounts a subscription by a fixed amount or by a percentage.

Percentage off or Discount amount

Indicates how much the coupon actually discounts.

If you sell in multiple currencies, a single coupon can define different discount amounts for different currencies. Multi-currency coupons follow the same rules as multi-currency prices.

Apply to specific products optionalLimits the type of items that the coupon can apply to.
DurationIndicates how long the coupon is valid for.
Redemption limits optionalAllows you to limit when a customer can redeem the coupon and the number of times a coupon can be redeemed.
Codes optionalAllows you to create promotion codes for the coupon.

Set eligible products

To set the products that are eligible for discounts, add the relevant product in the Apply to specific product field. Any promotion codes that are associated with the coupon are also restricted to this list of eligible products.

If you configure a coupon to apply to specific products and a subscription doesn’t have any applicable products, no discount is applied when you add the coupon to the subscription.

When you make changes to a subscription, Stripe calculates the proration and applies any existing discounts. You can’t discount proration line items further on the invoice that’s generated.

Apply coupons to subscriptions

After you’ve created coupons, create a discount by applying them to a subscription. You can apply the coupon when you create the subscription or by updating a customer’s existing subscription.

  1. In the Dashboard, open the Subscriptions page.
  2. Click the relevant subscription.
  3. Click Actions.
  4. Click Update subscription.
  5. Click Add coupon.
  6. Select one or more coupons from the dropdown menus and click Submit.

You can still create a subscription when a customer doesn’t have a stored payment method if no immediate payment is required after you apply coupons to it.

Apply coupons to Checkout

Apply coupons to subscriptions in a Checkout Session by setting the discounts parameter in the API. To create a session with an applied discount, pass the coupon ID in the coupon parameter of the discounts array.

Command Line
curl
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
curl https://api.stripe.com/v1/checkout/sessions \ -u
sk_test_BQokikJOvBiI2HlWgH4olfQ2
:
\ -d "payment_method_types[]"=card \ -d "line_items[][price]"=
"{{PRICE_ID}}"
\ -d "line_items[][quantity]"=1 \ -d mode=subscription \ -d "discounts[][coupon]"="{{COUPON_ID}}" \ -d success_url="https://example.com/success" \ -d cancel_url="https://example.com/cancel"

Build a checkout page and subscribe your customer

Use Stripe Elements and the Checkout Sessions API to build a checkout page as part of a fully customized subscriptions integration.

To set up a subscription you need to create a Customer. You can collect address and payment details with the Express Checkout Element. Then, you can use that information to create the subscription with the Checkout Sessions API.

Notiz

To test this in a sandbox, you can attach the customer you created to the test clock you created while setting up the testing environment.

Set up Stripe

Install the Stripe client of your choice:

Command Line
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
# Available as a gem sudo gem install stripe
Gemfile
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
# If you use bundler, you can add this line to your Gemfile gem 'stripe'

And then install the Stripe CLI. The CLI provides webhook testing and you can run it to make API calls to Stripe. This guide shows how to use the CLI to set up a pricing model.

Command Line
homebrew
Install from source
No results
# Install Homebrew to run this command: https://brew.sh/ brew install stripe/stripe-cli/stripe # Connect the CLI to your dashboard stripe login

For additional install options, see Get started with the Stripe CLI.

Create a Customer

Stripe needs a Customer for each subscription. In your application front end, collect any necessary information from your users and pass it to the back end.

If you need to collect address details, the Address Element enables you to collect a shipping or billing address for your customers. For more information on the Address Element, see the Address Element page.

register.html
<form id="signup-form"> <label> Email <input id="email" type="email" placeholder="Email address" value="test@example.com" required /> </label> <button type="submit"> Register </button> </form>
register.js
const emailInput = document.querySelector('#email'); fetch('/create-customer', { method: 'post', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email: emailInput.value, }), }).then(r => r.json());

On the server, create the Stripe Customer object.

Notiz

Make sure you store the Customer ID to use in the Checkout Session

Command Line
cURL
Stripe CLI
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
curl https://api.stripe.com/v1/customers \ -u "
sk_test_BQokikJOvBiI2HlWgH4olfQ2
:"
\ -d email={{CUSTOMER_EMAIL}} \ -d name={{CUSTOMER_NAME}} \ -d "shipping[address][city]"=Brothers \ -d "shipping[address][country]"=US \ -d "shipping[address][line1]"="27 Fredrick Ave" \ -d "shipping[address][postal_code]"=97712 \ -d "shipping[address][state]"=CA \ -d "shipping[name]"={{CUSTOMER_NAME}} \ -d "address[city]"=Brothers \ -d "address[country]"=US \ -d "address[line1]"="27 Fredrick Ave" \ -d "address[postal_code]"=97712 \ -d "address[state]"=CA

Enable payment methods

By default, Stripe uses your payment methods settings to determine which payment methods are enabled in the Express Checkout Element. You can also configure specific payment methods on your Checkout Session using the payment_method_types attribute.

Supported payment methods

Apple Pay and Google Pay are automatically enabled when using the card payment method type. When using Link, you must also pass the card payment method type.

Payment methodPayment method type
Amazon Payamazon_pay
Apple Paycard
Google Paycard
Klarnaklarna
Linklink, card
PayPalpaypal

Create the Checkout Session

On the back end of your application, define an endpoint that creates the session for your front end to call. You need the price ID of the subscription the customer is signing up for—your front end passes this value.

Command Line
cURL
Stripe CLI
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
curl https://api.stripe.com/v1/checkout/sessions \ -u "
sk_test_BQokikJOvBiI2HlWgH4olfQ2
:"
\ -d customer={{CUSTOMER_ID}} \ -d ui_mode=custom \ -d "line_items[0][price]"={{PRICE_ID}} \ -d "line_items[0][quantity]"=1 \ -d return_url={{RETURN_URL}} \ -d mode=subscription

Initialize Checkout

Create either a clientSecret promise that resolves with the client secret or set it as the secret directly. Call initCheckout, passing in clientSecret. initCheckout returns a promise that resolves to a Checkout instance.

The checkout object acts as the foundation of your checkout page, and contains data from the Checkout Session and methods to update the Session.

The object returned by actions.getSession() contains your pricing information. We recommend reading and displaying the total, and lineItems from the session in your UI.

This lets you turn on new features with minimal code changes. For example, adding manual currency prices requires no UI changes if you display the total.

checkout.js
const clientSecret = fetch('/create-checkout-session', {method: 'POST'}) .then((response) => response.json()) .then((json) => json.checkoutSessionClientSecret); const checkout = stripe.initCheckout({clientSecret}); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const session = loadActionsResult.actions.getSession(); const checkoutContainer = document.getElementById('checkout-container'); checkoutContainer.append(JSON.stringify(session.lineItems, null, 2)); checkoutContainer.append(document.createElement('br')); checkoutContainer.append(`Total: ${session.total.total.amount}`); }
index.html
<div id="checkout-container"></div>

Set up a trial period

To offer a free 7-day trial period of your service, pass in trial_period_days when you create the Checkout Session.

Command Line
cURL
Stripe CLI
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
curl https://api.stripe.com/v1/checkout/sessions \ -u "
sk_test_BQokikJOvBiI2HlWgH4olfQ2
:"
\ -d customer={{CUSTOMER_ID}} \ -d ui_mode=custom \ -d "line_items[0][price]"={{PRICE_ID}} \ -d "line_items[0][quantity]"=1 \ -d return_url={{RETURN_URL}} \ -d mode=subscription \ -d "subscription_data[trial_period_days]"=7

Set up Stripe Elements

The Express Checkout Element is automatically available as a feature of Stripe.js. Include the Stripe.js script on your checkout page by adding it to the head of your HTML file. Always load Stripe.js directly from js.stripe.com to remain PCI compliant. Don’t include the script in a bundle or host a copy of it yourself.

checkout.html
<head> <title>Checkout</title> <script src="https://js.stripe.com/clover/stripe.js"></script> </head>

Retrieve the client secret from your server:

checkout.js
// Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe(
'pk_test_TYooMQauvdEDq54NiTphI7jx'
);

Create a fetchClientSecret function to retrieve the client secret from your server:

checkout.js
const clientSecret = fetch('/create-checkout-session', {method: 'POST'}) .then((response) => response.json()) .then((json) => json.client_secret);

Create the Checkout instance:

checkout.js
const checkout = stripe.initCheckout({ clientSecret });

Create and mount the Express Checkout Element

The Express Checkout Element contains an iframe that securely sends the payment information to Stripe over an HTTPS connection. The checkout page address must also start with https://, rather than http://, for your integration to work.

The Express Checkout Element needs a place to live on your payment page. Create an empty DOM node (container) with a unique ID in your payment form.

checkout.html
<div id="express-checkout-element"> <!-- Express Checkout Element will be inserted here --> </div> <div id="error-message"> <!-- Display an error message to your customers here --> </div>

When the form has loaded, create an instance of the Express Checkout Element and mount it to the container DOM node:

checkout.js
// Create and mount the Express Checkout Element const expressCheckoutElement = checkout.createExpressCheckoutElement(); expressCheckoutElement.mount('#express-checkout-element');

Collect customer details and display line items

The Checkout Session you created on the server automatically determines the line items, total amount, and available payment methods. The Express Checkout Element uses this information to display the appropriate interface.

Handle payment confirmation

Listen to the confirm event when your customer finalizes their payment:

checkout.js
const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { expressCheckoutElement.on('confirm', (event) => { loadActionsResult.actions.confirm({expressCheckoutConfirmEvent: event}); }); }

Handle dynamic updates

If you need to update the Checkout Session based on customer selections (such as shipping address or shipping rate changes), you can listen to events and update the session:

checkout.js
expressCheckoutElement.on('shippingaddresschange', async (event) => { const response = await fetch('/update-session-shipping', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ sessionId: checkout.session.id, shippingAddress: event.address }) }); const result = await response.json(); if (result.error) { event.reject(); } else { event.resolve(); } }); expressCheckoutElement.on('shippingratechange', async (event) => { const response = await fetch('/update-session-shipping-rate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ sessionId: checkout.session.id, shippingRateId: event.shippingRate.id }) }); const result = await response.json(); if (result.error) { event.reject(); } else { event.resolve(); } });

Submit the payment

Render a Pay button that calls confirm from the checkout instance to submit the payment.

index.html
<button id="pay-button">Pay</button> <div id="confirm-errors"></div>
checkout.js
const checkout = stripe.initCheckout({clientSecret}); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const {actions} = loadActionsResult; const button = document.getElementById('pay-button'); const errors = document.getElementById('confirm-errors'); button.addEventListener('click', () => { // Clear any validation errors errors.textContent = ''; actions.confirm().then((result) => { if (result.type === 'error') { errors.textContent = result.error.message; } }); }); }

Listen for webhook events

To set up your back-end logic, you need to set up an endpoint that can listen for webhook events sent by Stripe. These events are triggered whenever the status in Stripe changes, such as subscriptions creating new invoices. In your application, set up an HTTP handler to accept a POST request containing the webhook event, and verify the signature of the event.

During development, use the Events tab in Workbench to monitor and filter events.

For production, set up a webhook endpoint URL in the Dashboard, or use the Webhook Endpoints API.

See Subscription events for more details about subscription-specific webhooks.

Provision access

Grant customers access to your service upon successful payment. In most cases, you can provision access to you service when:

  • You receive the invoice.paid event.
  • The subscription status is active. You can check the status in the Subscriptions page in the Dashboard or by using the API to retrieve the subscription and checking the status field.

For more details about subscription-specific webhooks, Subscription events.

Test your integration

Test your integration before going live.

ScenarioTests
Successful subscription flows
  • Use test card number 4242424242424242 for successful payments
  • Verify subscription creation and customer provisioning
Failure scenarios
  • Use test card number 4000000000000002 to test generic card declines
  • Verify error handling and customer communication
  • Test insufficient funds scenarios with 4000000000009995
Time-based events
  • Use test clocks to simulate subscription renewals
  • Test trial period expiration
  • Verify webhook event handling
Promotion codes
  • Apply promotion codes during checkout
  • Verify correct discount application
  • Test code expiration and usage limits
Proration
  • Test proration calculations for scenarios such as mid-cycle upgrades by using test clocks
  • Verify proration invoice handling by previewing invoices
Cancellations
  • Test cancellation logic during trial periods
  • Verify cancellations initiated from the Customer Portal

Go live

  1. In the Dashboard, open your Account settings.
  2. Enter your business type, tax details, business details, personal verification information, and customer-facing information (for example, a statement descriptor).
  3. Add bank details to confirm where your money will be paid out.
  4. Set up two-step authentication to secure your account.
  5. You can optionally add automatic tax collection or revenue-based climate donations.
  6. Review the information you entered, and click Agree and submit.
  7. After you activate your profile, Stripe updates you from sandbox mode to live mode.

Learn more about activating your Stripe account.

Next steps

After setting up your integration, we recommend you implement the following features:

  • Set up the customer portal to let your customers manage their subscriptions and payment information.
  • Set up Smart Retries to let Stripe’s AI choose the best times to retry failed payment attempts to increase the chance of successfully paying an invoice.
  • Set up billing automations to build custom, automated workflows to streamline your business processes, enhance customer communication, and improve revenue recovery efforts.
War diese Seite hilfreich?
JaNein
  • Benötigen Sie Hilfe? Kontaktieren Sie den Kundensupport.
  • Schauen Sie sich unser Änderungsprotokoll an.
  • Fragen? Sales-Team kontaktieren.
  • LLM? Lesen Sie llms.txt.
  • Unterstützt von Markdoc