Skip to content
Create account
or
Sign in
The Stripe Docs logo
/
Ask AI
Create account
Sign in
Get started
Payments
Revenue
Platforms and marketplaces
Money management
Developer resources
Overview
About Stripe payments
Upgrade your integration
Payments analytics
Online payments
OverviewFind your use caseManaged Payments
Use Payment Links
Build a checkout page
    Overview
    Quickstarts
    Customise look and feel
    Collect additional information
    Collect taxes
    Dynamically update checkout
      Dynamically customise shipping options
      Dynamically update line items
      Dynamically update trial durations
      Dynamically update discounts
    Manage your product catalogue
    Subscriptions
    Manage payment methods
    Let customers pay in their local currency
    Add discounts, upsells, and optional items
    Set up future payments
    Save payment details during payment
    Manually approve payments on your server
    After the payment
    Elements with Checkout Sessions API beta changelog
    Migrate from legacy Checkout
    Migrate Checkout to use Prices
Build an advanced integration
Build an in-app integration
Payment Methods
Add payment methods
Manage payment methods
Faster checkout with Link
Payment interfaces
Payment Links
Checkout
Web Elements
In-app Elements
Payment scenarios
Handle multiple currencies
Custom payment flows
Flexible acquiring
Orchestration
In-person payments
Terminal
Beyond payments
Incorporate your company
Crypto
Financial Connections
Climate
HomePaymentsBuild a checkout pageDynamically update checkout

Dynamically update discountsPrivate preview

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.

Security tip

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.

Was this page helpful?
YesNo
Need help? Contact Support.
Join our early access programme.
Check out our changelog.
Questions? Contact Sales.
LLM? Read llms.txt.
Powered by Markdoc