Weiter zum Inhalt
Konto erstellen
oder
anmelden
Das Logo der Stripe-Dokumentation
/
KI fragen
Konto erstellen
Anmelden
Jetzt starten
Zahlungen
Umsatz
Plattformen und Marktplätze
Geldmanagement
Entwicklerressourcen
Übersicht
Informationen zu Stripe Payments
Aktualisieren Sie Ihre Integration
Zahlungsanalysefunktionen
Online-Zahlungen
ÜbersichtIhren Use case findenZahlungen verwalten
Payment Links verwenden
Bezahlseite erstellen
    Übersicht
    Quickstarts
    Erscheinungsbild anpassen
    Zusätzliche Informationen erfassen
    Steuern einziehen
    Bezahlvorgang dynamisch aktualisieren
      Versandoptionen dynamisch anpassen
      Einzelposten dynamisch aktualisieren
      Testzeiträume dynamisch anpassen
      Dynamically update discounts
    Ihren Produktkatalog verwalten
    Abonnements
    Zahlungsmethoden verwalten
    Lassen Sie Kundinnen/Kunden in ihrer Landeswährung zahlen
    Rabatte, Upselling und optionale Artikel hinzufügen
    Zukünftige Zahlungen einrichten
    Zahlungsdaten bei der Zahlung speichern
    Zahlungen auf Ihrem Server manuell genehmigen
    Nach der Zahlung
    Elements mit Checkout Sessions API-Änderungsprotokoll (Beta)
    Vom bisherigen Bezahlvorgang migrieren
    Bezahlvorgang auf Prices umstellen
Erweiterte Integration erstellen
In-App-Integration erstellen
Zahlungsmethoden
Zahlungsmethoden hinzufügen
Zahlungsmethoden verwalten
Schnellerer Bezahlvorgang mit Link
Zahlungsschnittstellen
Payment Links
Checkout
Web Elements
In-App-Elements
Zahlungsszenarien
Umgang mit mehreren Währungen
Nutzerdefinierte Zahlungsabläufe
Flexibles Acquiring
Orchestrierung
Präsenzzahlungen
Terminal
Mehr als Zahlungen
Unternehmensgründung
Krypto
Financial Connections
Climate
StartseiteZahlungenBuild a checkout pageDynamically update checkout

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.

Dynamically update discountsPrivate Vorschau

Update discounts in response to changes customers make during checkout.

Private preview

This feature is in private preview. Request access to dynamic updates to checkout.

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

Use cases

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.

Set up SDK
Server-side

Use our official libraries to access the Stripe API from your application:

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

Update 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
# 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 Checkout Session update permissions
Server-side

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
Server-side

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.

Sicherheitshinweis

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.

When designing the endpoint, we recommend the following:

  • 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

Update 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'], });

Invoke server updates
Client-side

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

Test the integration

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

  1. Set up a sandbox environment that mirrors your production setup. Use your Stripe sandbox API keys for this environment.

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

  3. Verify server-side logic by using logging or debugging tools to confirm that your server:

    • Retrieves the 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:

    • The runServerUpdate function is called as expected.
    • 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.

War diese Seite hilfreich?
JaNein
Benötigen Sie Hilfe? Kontaktieren Sie den Kundensupport.
Nehmen Sie an unserem Programm für frühzeitigen Zugriff teil.
Schauen Sie sich unser Änderungsprotokoll an.
Fragen? Sales-Team kontaktieren.
LLM? Lesen Sie llms.txt.
Unterstützt von Markdoc