コンテンツにスキップ
アカウントを作成
または
サインイン
Stripe ドキュメントのロゴ
/
AI に質問する
アカウントを作成
サインイン
始める
支払い
売上
プラットフォームおよびマーケットプレイス
資金管理
開発者向けリソース
概要
Stripe Payments について
構築済みのシステムをアップグレード
支払いの分析
オンライン決済
概要ユースケースを見つけるManaged Payments
Payment Links を使用する
決済ページを構築
    概要
    クイックスタート
    デザインをカスタマイズする
    追加情報を収集する
    税金を徴収する
    決済フローを動的に更新
      配送オプションを動的にカスタマイズ
      ラインアイテムを動的に更新する
      トライアル期間を動的に更新する
      Dynamically update discounts
    商品カタログを管理する
    サブスクリプション
    決済手段を管理
    顧客が現地通貨で支払いできるようにする
    割引、アップセル、オプション品目を追加する
    将来の支払いを設定する
    支払い中に支払い詳細を保存する
    サーバーで支払いを手動で承認する
    支払い後
    Elements with Checkout Sessions API ベータ版の変更ログ
    従来の Checkout からの移行
    Checkout を移行して Prices を使用
高度なシステムを構築
アプリ内実装を構築
決済手段
決済手段を追加
決済手段を管理
Link による購入の迅速化
支払いインターフェイス
Payment Links
Checkout
Web Elements
アプリ内 Elements
決済シナリオ
複数の通貨を扱う
カスタムの決済フロー
柔軟なアクワイアリング
オーケストレーション
店頭支払い
端末
決済にとどまらない機能
会社を設立する
仮想通貨
Financial Connections
Climate
ホーム支払いBuild a checkout pageDynamically update checkout

注

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

Dynamically update discounts非公開プレビュー

Update discounts in response to changes customers make during checkout.

プライベートプレビュー版

This feature is in private preview. 決済フローの動的更新へのアクセスをリクエストしてください。

Learn how to dynamically add or remove discounts on a Checkout Session.

ご利用事例

This guide demonstrates how to integrate with your internal discounts system to create dynamic amount-off discounts, but you can also:

  • Apply loyalty discounts: Automatically apply discounts based on customer loyalty tier or purchase history.
  • Cart value promotions: Add discounts when the order total exceeds specific thresholds (for example, $10 off orders over $100).
  • Time-sensitive offers: Apply limited-time promotional discounts or remove expired discount codes.
  • Location-based discounts: Apply region-specific discounts based on the customer’s shipping address.
  • Customer-specific offers: Create personalized discount amounts based on customer segments or previous purchase behavior.

SDK を設定する
サーバー側

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

Command Line
Ruby
gem install stripe -v 15.1.0-beta.2

サーバー SDK の更新
サーバー側

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

Ruby
# 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;'

Checkout セッションの更新権限の設定
サーバー側

Pass in permissions.update_discounts=server_only when you create the Checkout Session to enable updating discounts from your server. Passing this option disables client-side discount application, ensuring that all discount logic passes through your server.

Command Line
cURL
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
サーバー側

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

セキュリティのヒント

Client-side code runs in an environment fully controlled by the user. A malicious user can bypass your client-side validation, intercept, and modify requests, or even craft entirely new requests to your server.

エンドポイントを設計する際は、以下を考慮することをお勧めします。

  • Design endpoints for specific customer interactions instead of making them overly generic (for example, “apply loyalty discount” rather than a general “update” action). Specific endpoints help keep the purpose clear and make validation logic easier to write and maintain.
  • 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 Stripe’s API.
Ruby
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

クライアント SDK の更新
クライアント側

custom_checkout_server_updates_1 ベータヘッダーを使用して stripe.js を初期化します。

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

サーバー更新の呼び出し
クライアント側

Trigger the update from your front end by making a request to your server, and wrapping it in runServerUpdate. If the request is successful, the Session object updates 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; });

組み込みをテストする

Follow these steps to test your integration, and ensure your dynamic discounts work correctly.

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

  2. Simulate various discount scenarios to verify that your recomputeDiscounts function handles different scenarios correctly.

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

    • Checkout Session (セッション) を取得します。
    • Validates discount requests.
    • Recomputes updated discounts based on your business logic.
    • Updates the Checkout Session with the new discounts when your custom conditions are met. Make sure the update response contains the new discounts. By default, the response doesn’t contain the discounts field, unless the request expands the object.
  4. Verify client-side logic by completing the checkout process multiple times in your browser. Pay attention to how the UI updates after applying a discount. Make sure that:

    • runServerUpdate 関数が想定どおりに呼び出される。
    • Discounts apply correctly based on your business logic.
    • The checkout total updates to reflect the applied discount.
    • Error messages display properly when a discount application failed.
  5. Test various discount scenarios including invalid discount requests or simulate server errors to test error handling, both server-side and client-side.

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