コンテンツにスキップ
アカウントを作成
または
サインイン
Stripe ドキュメントのロゴ
/
AI に質問する
アカウントを作成
サインイン
始める
支払い
売上
プラットフォームおよびマーケットプレイス
資金管理
開発者向けリソース
概要
Stripe Payments について
構築済みのシステムをアップグレード
支払いの分析
オンライン決済
概要ユースケースを見つけるUse Managed Payments
Payment Links を使用する
構築済みの決済ページを使用する
Build a custom integration with Elements
    概要
    Compare Checkout Sessions and PaymentIntents
    Quickstart guides
    高度なシステムを設計
    デザインをカスタマイズする
    決済手段を管理
    追加情報を収集する
    サブスクリプションの実装
    Dynamic updates
      Shipping options
      項目
      Trial durations
      割引
      Payment amounts
      Line item quantities
    割引を追加する
    支払いで税金を徴収
    顧客が現地通貨で支払いできるようにする
    顧客の支払い方法を保存および取得する
    領収書と支払い済みの請求書を送信する
    サーバーで支払いを手動で承認する
    支払いのオーソリとキャプチャーを分離する
    Elements with Checkout Sessions API ベータ版の変更ログ
アプリ内実装を構築
決済手段
決済手段を追加
決済手段を管理
Link による購入の迅速化
支払いインターフェイス
Payment Links
Checkout
Web Elements
アプリ内決済
決済シナリオ
複数の通貨を扱う
カスタムの決済フロー
柔軟なアクワイアリング
オーケストレーション
店頭支払い
端末
決済にとどまらない機能
会社を設立する
仮想通貨
Financial Connections
Climate
不正利用について
Radar の不正防止
不審請求の申請の管理
本人確認
ホーム支払いBuild a custom integration with ElementsDynamic updates

注

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

Dynamically update discounts

Learn how to apply and modify discount codes during checkout.

Private preview

Dynamic discounts is in private preview. Request access to dynamic updates to checkout.

Checkout Session で割引を動的に追加または削除する方法をご紹介します。

ご利用事例

このガイドでは、社内の割引システムを導入して動的な金額割引を作成する方法を説明します。合わせて、次についても理解できます。

  • ロイヤルティ割引の適用: 顧客ロイヤルティ段階または購入履歴に基づき、割引を自動的に適用します。
  • カート金額のプロモーション: 注文合計が特定の基準値を超えた場合に割引を追加します (たとえば、100 ドルを超える注文から 10 ドル割引など)。
  • 時間的制約のあるオファー: 期間限定のプロモーション割引を適用したり、期限切れの割引コードを削除したりできます。
  • ロケーションベースの割引: 顧客の配送先住所に基づいて、地域別に割引を適用します。
  • 顧客固有のオファー: 顧客セグメントまたは以前の購買行動に基づき、個人に合わせた割引を作成します。

Payment Intents API

If you use the Payment Intents API, you can apply discounts by manually calculating and modifying the payment amount, or by creating a new PaymentIntent with adjusted amounts.

Set up the SDK
Server-side

Stripe の公式ライブラリを使用して、アプリケーションから Stripe API にアクセスします。

Command Line
Ruby
Python
PHP
Node.js
.NET
Go
Java
No results
gem install stripe -v 15.1.0-beta.2

Update the server SDK
Server-side

To use this preview feature, first update your SDK to use the checkout_server_update_beta=v1 beta version header.

Ruby
Python
PHP
Node
.NET
Go
Java
No results
# Set your secret key. Remember to switch to your live secret key in production. # See your keys here: https://dashboard.stripe.com/apikeys Stripe.api_key =
'sk_test_BQokikJOvBiI2HlWgH4olfQ2'
Stripe.api_version = '2025-03-31.basil; checkout_server_update_beta=v1;'

Configure update permissions for the Checkout Session
Server-side

When you create the Checkout Session, pass the permissions.update_discounts=server_only option to disable applying client-side discounts and to enable updating discounts from your server.

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
:"
\ -H "Stripe-Version: 2025-03-31.basil; checkout_server_update_beta=v1;" \ -d ui_mode=custom \ -d "permissions[update_discounts]"=server_only \ -d "line_items[0][price]"=
{{PRICE_ID}}
\ -d "line_items[0][quantity]"=1 \ -d mode=payment \ --data-urlencode return_url="https://example.com/return"

Dynamically update discounts
Server-side

Create an endpoint on your server to apply discounts on the Checkout Session. You’ll call this from the front end in a later step.

セキュリティのヒント

Client-side code runs in an environment that’s controlled by the user. A malicious user can bypass your client-side validation, intercept and modify requests, or create new requests to your server.

When creating an endpoint, we recommend the following:

  • Create endpoints for specific customer interactions instead of making them generic. For example, “apply loyalty discount” instead of a general “update” action. Specific endpoints can help with writing and maintaining validation logic.
  • Don’t pass session data directly from the client to your endpoint. Malicious clients can modify request data, making it an unreliable source for determining the Checkout Session state. Instead, pass the session ID to your server and use it to securely retrieve the data from the Stripe API.
Ruby
Python
PHP
Node.js
.NET
Go
Java
No results
require 'sinatra' require 'json' require 'stripe' set :port, 4242 # Set your secret key. Remember to switch to your live secret key in production! # See your keys here: https://dashboard.stripe.com/apikeys Stripe.api_key =
"sk_test_BQokikJOvBiI2HlWgH4olfQ2"
# Return a boolean indicating whether the discounts are valid. def validate_discounts(discounts, session # Basic validation - ensure we only have one discount if any return true if discounts.empty? || discounts == "" # Ensure only one discount is being applied return false if discounts.is_a?(Array) && discounts.length > 1 # Add your own validation logic here # For example, validate promo codes against your internal system true end # Return an array of the updated discounts or the original ones if no update is needed. def recompute_discounts(discounts, session) # If removing discounts, return empty return [] if discounts.empty? || discounts == "" # Example: Access your internal discounts system # This could be based on customer ID, promo codes, cart value, etc. customer_id = session.customer || session.client_reference_id cart_total = session.amount_total # Example internal discount calculation discount_amount = calculate_customer_discount(customer_id, cart_total) if discount_amount > 0 # Create a dynamic discount using coupon_data [{ coupon_data: { name: "Customer Discount", amount_off: discount_amount, currency: session.currency || 'usd' } }] else # No discount applicable [] end end # Example function to integrate with your internal discounts system def calculate_customer_discount(customer_id, cart_total) # Example logic - replace with your actual discount system # This could check: # - Customer loyalty tier # - Active promotions # - Cart value thresholds # - Seasonal discounts # Example: 10% off for carts over 100 USD, max 20 USD discount if cart_total > 10000 # 100 USD in cents discount = [cart_total * 0.1, 2000].min # Max 20 USD discount discount.to_i else 0 end end post '/update-discounts' do content_type :json request.body.rewind request_data = JSON.parse(request.body.read) checkout_session_id = request_data['checkout_session_id'] discounts = request_data['discounts'] # 1. Retrieve the Checkout Session session = Stripe::Checkout::Session.retrieve(checkout_session_id) # 2. Validate the discounts if !validate_discounts(discounts, session) return { type: 'error', message: 'Your discounts are invalid. Please refresh your session.' }.to_json end # 3. Recompute the discounts with your custom logic discounts = recompute_discounts(discounts, session) # 4. Update the Checkout Session with the new discounts if discounts Stripe::Checkout::Session.update(checkout_session_id, { discounts: discounts, }) return { type: 'object', value: { succeeded: true } }.to_json else return { type: 'error', message: "We could not update your discounts. Please try again." }.to_json end end

Update the client SDK
Client-side

Initialize Stripe.js with the custom_checkout_server_updates_1 beta header.

checkout.js
const stripe = Stripe(
'pk_test_TYooMQauvdEDq54NiTphI7jx'
, { betas: ['custom_checkout_server_updates_1'], });

Request server updates
Client-side

From your front end, send an update request to your server and wrap it in runServerUpdate. A successful request updates the Session object with the new discount.

index.html
<button id="apply-customer-discount"> Apply Customer Discount </button>
checkout.js
document.getElementById('apply-customer-discount') .addEventListener("click", async (event) => { const updateCheckout = () => { return fetch("/apply-customer-discount", { method: "POST", headers: { "Content-type": "application/json", }, body: JSON.stringify({ checkout_session_id: checkout.session().id, }) }); }; const response = await checkout.runServerUpdate(updateCheckout); if (!response.ok) { // Handle error state return; } // Update UI to reflect the applied discount event.target.textContent = "Discount Applied!"; event.target.disabled = true; });

Test the integration

導入内容をテストして、動的な割引が正しく機能することを確認するには、以下のステップに従います。

  1. 本番環境を反映したサンドボックス環境を設定します。この環境では、Stripe サンドボックスの API キーを使用してください。

  2. さまざまな割引シナリオをシミュレーションして、recomputeDiscounts 関数がさまざまなシナリオを正しく処理することを確認できます。

  3. ログツールやデバッグツールを使用してサーバーが以下を行っていることを確認し、サーバー側のロジックを検証します。

    • Checkout Session (セッション) を取得します。
    • 割引リクエストを検証します。
    • ご自身の事業のロジックに基づき、更新された割引を再計算します。
    • カスタム条件が満たされた場合に Checkout Sessionを新しい割引で更新します。更新のレスポンスに新しい割引が示されていることを確認します。デフォルトでは、リクエストがオブジェクトを拡張しない限り、レスポンスには割引のフィールドは示されません。
  4. ブラウザーで決済プロセスを複数回実行し、クライアント側のロジックを検証します。割引の適用後に UI がどのように更新されるかに注意してください。以下を確認してください。

    • runServerUpdate 関数が想定どおりに呼び出される。
    • 割引は事業のロジックに基づき正しく適用されます。
    • Checkout の合計が更新され、適用される割引が反映されます。
    • 割引の申し込みが失敗した場合は、エラーメッセージが正しく表示されます。
  5. 無効な割引リクエストなど、さまざまな割引シナリオをテストするか、サーバーエラーをシミュレーションして、サーバー側とクライアント側の両方でエラー処理をテストします。

このページはお役に立ちましたか。
はいいいえ
  • お困りのことがございましたら 、サポートにお問い合わせください。
  • 早期アクセスプログラムにご参加ください。
  • 変更ログをご覧ください。
  • ご不明な点がございましたら、お問い合わせください。
  • LLM ですか?llms.txt を読んでください。
  • Powered by Markdoc