Accéder directement au contenu
Créez un compte
ou
connecter-vous
Logo de la documentation Stripe
/
Demander à l'assistant IA
Créez un compte
Connectez-vous
Démarrer
Paiements
Revenus
Plateformes et places de marché
Gestion de fonds
Ressources pour les développeurs
Aperçu
À propos des paiements Stripe
Mettre votre intégration à niveau
Analyses des paiements
Paiements en ligne
PrésentationTrouver votre cas d'usageManaged Payments
Utiliser Payment Links
Créer une page de paiement
    Présentation
    Solutions de démarrage rapide
    Personnaliser l'apparence
    Collecter des informations supplémentaires
    Collecter des taxes
    Mise à jour dynamique lors du paiement
      Personnalisation dynamique des options d'expédition
      Mise à jour dynamique des postes de facture
      Mettre à jour la durée des essais de manière dynamique
      Dynamically update discounts
    Gérer votre catalogue de produits
    Abonnements
    Gérer les moyens de paiement
    Offrir aux clients la possibilité de payer dans leur devise locale
    Ajoutez des réductions, des ventes incitatives et des articles facultatifs
    Configurer des paiements futurs
    Enregistrer les coordonnées bancaires lors du paiement
    Approuver manuellement les paiements sur votre serveur
    Après le paiement
    Liste des modifications de la version bêta d'Elements avec l'API Checkout Sessions
    Migrer depuis l'ancienne version de Checkout
    Migrer vers Checkout pour utiliser Prices
Développer une intégration avancée
Développer une intégration dans l'application
Moyens de paiement
Ajouter des moyens de paiement
Gérer les moyens de paiement
Paiement accéléré avec Link
Interfaces de paiement
Payment Links
Checkout
Elements pour le web
Elements intégrés à l'application
Scénarios de paiement
Gérer plusieurs devises
Tunnels de paiement personnalisés
Acquisition flexible
Orchestration
Paiements par TPE
Terminal
Au-delà des paiements
Constituez votre entreprise
Cryptomonnaies
Financial Connections
Climate
AccueilPaiementsBuild a checkout pageDynamically update checkout

Remarque

Cette page n'est pas encore disponible dans cette langue. Nous faisons tout notre possible pour proposer notre documentation dans davantage de langues et nous vous fournirons la version traduite dès qu'elle sera disponible.

Dynamically update discountsVersion bêta privée

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.

Conseil en matière de sécurité

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.

Cette page vous a-t-elle été utile ?
OuiNon
Besoin d'aide ? Contactez le service Support.
Rejoignez notre programme d'accès anticipé.
Consultez notre log des modifications.
Des questions ? Contactez l'équipe commerciale.
LLM ? Lire llms.txt.
Propulsé par Markdoc