コンテンツにスキップ
アカウントを作成またはサインイン
Stripe ドキュメントのロゴ
/
AI に質問する
アカウントを作成サインイン
導入方法
決済管理
売上管理
プラットフォームとマーケットプレイス
資金管理
開発者向けリソース
API & SDKヘルプ
概要すべての商品を見る
API について
構築を開始する
アカウントを作成する
クイックスタート
開発の開始
LLM を活用して構築
ノーコードで Stripe を使用する
Stripe に移行
一般的なユースケース
概要スタートアップとしてシンプルな決済を受け付けるSaaS スタートアップとしてサブスクリプションを販売する使用量ベースの料金設定でサブスクリプションソリューションを構築する対面支払いを受け付ける請求書を送信して支払いを回収する
アメリカ
日本語
ホーム導入方法

注

このページはまだ日本語ではご利用いただけません。より多くの言語で文書が閲覧できるように現在取り組んでいます。準備が整い次第、翻訳版を提供いたしますので、もう少しお待ちください。

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:

ライセンス手数料
ユーザーごと100 USD
使用状況手数料
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

メーターは、請求期間中のメーターイベントを集計する方法を指定するものです。メーターイベントは、顧客がシステムで実行するすべてのアクション (API リクエストなど) を表します。メーターは料金に関連付けられており、請求内容の基礎になります。

Alpaca AI の例では、メーターイベントは顧客がクエリで使用するトークンの数です。メーターは 1 カ月あたりのトークンの合計です。

Stripe ダッシュボードまたは API を使用してメーターを設定できます。Stripe CLI で API を使用してメーターを作成するには、Stripe CLI を始める を参照してください。

  1. メーターページで、メーターを作成をクリックします。
  2. メーターを作成ページで、以下を実行します。
    • メーター名には、表示用および社内用のメーターの名前を入力します。Alpaca AI の例では、「Alpaca AI tokens」と入力します。
    • イベント名に、使用量を Stripe に報告するときにメーターイベントに表示する名前を入力します。Alpaca AI の例では、「alpaca_ai_tokens」と入力します。
    • ドロップダウンで 集計方法 を設定します。
      • Alpaca AI の例では、合計を選択します。これにより、報告された「値の合計」 (この例では顧客が使用するトークンの数)が出され、請求する使用量が決定されます。
      • 報告されたイベントの「数」に基づいて請求する 件数 を選択します。
      • 最後 を選択すると、報告された「last value」に基づいて請求できます。
      • プレビューペインを使用して、使用状況イベントの例を設定し、集計方法を確認します。
    • メーターを作成をクリックします。
    • (オプション) 詳細設定で、使用状況データにタグ付けするディメンションを指定します。セグメント固有のアラートをきめ細かく生成したり、属性の組み合わせに基づいて使用状況を細かく価格設定したりするには、分析とレポート作成用に入力されたディメンションを使用して使用状況データを送信します。ディメンションの例としては、LLM モデル、トークンタイプ、地域、イベントタイプなどがあります。

Create the pricing model

Stripe ダッシュボードまたは API を使用して、商品 とその料金オプションを含む 料金体系モデル を作成します。価格 は、単価、通貨、請求期間を定義します。

Alpaca AI の例では、100 ユニットあたり 0.04 USD の従量制料金で、月ごとに請求を行う商品を作成します。前のステップで作成したメーターを使用します。

  1. 商品カタログ ページで、商品を作成 をクリックします。
  2. 商品を追加 ページで、以下を実行します。
    1. 名前 には、商品の名前を入力します。Alpaca AI の例では、Alpaca AI 使用状況 と入力します。
    2. (オプション) 説明 には、Checkout、カスタマーポータル、見積もり に表示する説明を追加します。
    3. 継続 を選択します。
    4. 請求期間 で、その他の料金体系オプション を選択します。
  3. 価格を追加 ページで、以下を実行します。
    1. 料金体系モデルを選択 で、従量制 を選択します。
    2. 料金体系を選択:
      • Alpaca AI の例では、段階ごとおよび卒業済み を選択します。
      • グリッドの最初の行で、最初のユニット を 0、最後のユニット を 1,000、ユニットごと を 0 USD、定額手数料 を 0 USD に設定します。
      • グリッドの 2 行目で、最初のユニット を 1,001、最後のユニット を ∞、ユニットごと を 0.04 USD、定額手数料 を 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. メーター で、以前に作成したメーターを選択します。Alpaca AI の例では、ドロップダウンから Alpaca AI トークン を選択します。
    4. 請求期間 を選択します。Alpaca AI の例では、月次 を選択します。
    5. 次へ をクリックします。
    6. 商品を追加 をクリックします。

次に、100 USD 月額料金を作成します。

  1. 商品カタログ ページで、商品を作成 をクリックします。
  2. 商品を追加 ページで、以下を実行します。
    • 名前 には、商品の名前を入力します。Alpaca AI の例では、Alpaca AI ライセンス手数料 と入力します。
    • (オプション) 説明 には、Checkout、カスタマーポータル、見積もり に表示する説明を追加します。
    • 継続 を選択します。
    • 請求期間 で、その他の料金体系オプション を選択します。
  3. 価格を追加 ページで、以下を実行します。
    • 継続 を選択します*。
    • 金額 には、100 USD と入力します。
    • 通貨 には、USD を選択します。
    • 請求期間 で、月次 を選択します。
    • 次へ をクリックします。
    • 商品を追加 をクリックします。

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

クーポンは、ダッシュボードまたは API で作成します。

  1. ダッシュボードで、商品ページを開きます。
  2. クーポンをクリックします。
  3. +新規をクリックします。
  4. クーポンを作成ダイアログで、クーポンのパラメーターを入力します。
  5. クーポンを作成をクリックします。

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

設定詳細
名前領収書や請求書に表示されるクーポン名。
ID オプションAPI でのクーポンの一意の ID。このフィールドを空白にすると、Stripe によって ID が生成されます。
タイプクーポンがサブスクリプションを、一定額またはパーセントのいずれで割り引くのかを決定します。

割引率または割引額

クーポンの実際の割引額を示します。

複数の通貨で販売している場合、1 つのクーポンで異なる通貨に異なる割引額を定義できます。多通貨のクーポンは、多通貨の価格と同じルールに従います。

特定の商品に適用 オプションクーポンを適用できるアイテムのタイプを制限します。
期間クーポンの有効期限を示します。
引き換え回数制限 オプション顧客がクーポンを引き換えできる期間と回数を制限できます。
コード オプションクーポンのプロモーションコードを作成できます。

Set eligible products

割引対象の商品を設定するには、特定の商品に適用フィールドに対象の商品を追加します。そのクーポンに関連付けられたプロモーションコードも、この対象商品のリストに制限されます。

特定の商品に適用されるクーポンを設定し、サブスクリプションに該当する商品が含まれない場合には、そのサブスクリプションにクーポン追加しても割引は適用されません。

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

クーポンを作成したら、サブスクリプションにクーポンを適用して割引を作成します。サブスクリプションを作成する際、または顧客の既存のサブスクリプションを更新する際にクーポンを適用できます。

  1. In the Dashboard, open the Subscriptions page.
  2. 該当するサブスクリプションをクリックします。
  3. アクションをクリックします。
  4. サブスクリプションを更新をクリックします。
  5. クーポンを追加をクリックします。
  6. ドロップダウンメニューから 1 つ以上のクーポンを選択し、送信をクリックします。

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

Checkout セッションでサブスクリプションにクーポンを適用する場合、API の discounts パラメーターを設定します。適用された割引でセッションを作成するには、discounts 配列の coupon パラメーターにクーポン ID を渡します。

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.

注

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
ソースからインストールする
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

その他のインストールオプションについては、Stripe CLI を使ってみるをご覧ください。

Create a Customer

Stripe では各サブスクリプションに対して 顧客が必要です。 アプリケーションのフロントエンドで、ユーザーから必要な情報を収集し、それをバックエンドに渡します。

住所の詳細を収集する必要がある場合は、Address Element を使用することで顧客の配送先住所または請求先住所を収集できます。Address Element の詳細については、Address Element ページをご覧ください。

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());

サーバー上で、Stripe Customer オブジェクトを作成します。

注

Checkout セッションで使用するために、顧客 ID を必ず保存してください

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

デフォルトでは、Stripe は 決済手段設定 を使用して、Express Checkout Element で有効になっている決済手段を決定します。payment_method_types 属性を使用して、Checkout Session で特定の決済手段を設定することもできます。

サポートされている決済手段

決済手段タイプ card を使用すると、Apple Pay と Google Pay が自動的に有効になります。Link を使用する場合は、必ず card 決済手段タイプも渡します。

決済手段決済手段の種類
Amazon Payamazon_pay
Apple Paycard
Google Paycard
Klarnaklarna
Linkリンク、カード
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

Client Secret を解決する clientSecret Promise を作成するか、機密事項として直接設定します。initCheckout を呼び出し、clientSecret を渡します。initCheckout は、Checkout インスタンスに解決するプロミスを返します。

checkout オブジェクトは、チェックアウトページの基盤として機能し、Checkout Session のデータや Session を更新するためのメソッドを含みます。

actions.getSession() によって返されるオブジェクトには、価格情報が含まれます。セッションの 合計 と lineItems を UI で読み込んで表示することをお勧めします。

これにより、最小限のコード変更で新機能を有効にできます。たとえば、手動通貨価格 を追加しても、合計 を表示する場合、 UI を変更する必要はありません。

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

Express Checkout Element は Stripe.js の機能として自動的に使用できるようになります。決済ページに Stripe.js スクリプトを含めるには、HTML ファイルの head にこれを追加します。常に js.stripe.com から Stripe.js を直接読み込むことにより、PCI への準拠が維持されます。スクリプトをバンドルに含めたり、そのコピーを自身でホストしたりしないでください。

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

サーバーから Client Secret を取得します。

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'
);

サーバーから Client Secret を取得する fetchClientSecret 関数を作成します。

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

Checkout インスタンスを作成します。

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

Create and mount the Express Checkout Element

Express Checkout Element には、HTTPS 接続を介して決済情報を Stripe に安全に送信する iframe が含まれています。導入を機能させるには、決済ページのアドレスの先頭を https://, ではなく http://, にする必要があります。

決済ページに Express Checkout Element を配置する場所が必要です。支払いフォームで、一意の ID を持つ空の DOM ノード (コンテナー) を作成します。

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>

フォームが読み込まれたら、Express Checkout Element のインスタンスを作成し、コンテナーの DOM ノードにマウントします。

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

サーバーで作成した Checkout Session によって、項目、合計金額、利用可能な決済手段が自動的に決定されます。Express Checkout Element はこの情報を使用して、適切なインターフェイスを表示します。

決済確定の処理

顧客が決済を確定したときに confirm event をリッスンします。

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

動的な更新を処理する

顧客の選択 (配送先住所や配送料金の変更など) に基づいて Checkout 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

チェックアウト インスタンスから confirm を呼び出す支払うボタンをレンダリングして、決済を送信します。

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.
このページはお役に立ちましたか。
はいいいえ
  • お困りのことがございましたら 、サポートにお問い合わせください。
  • 変更ログをご覧ください。
  • ご不明な点がございましたら、お問い合わせください。
  • LLM ですか?llms.txt を読んでください。
  • Powered by Markdoc