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
Billing
OverviewAbout the Billing APIs
Subscriptions
    Overview
    How subscriptions work
    Get started
    Quickstart
    Plan an integration
    Build an integration
    Use cases
    About subscriptions
    Enable billing mode
    Configure subscription events
    Entitlements
    Subscription invoices
    Subscription schedules
    Recurring pricing models
    Strong Customer Authentication (SCA)
    Set up subscriptions
    Configure collection methods
    Embed a pricing table
    Set billing cycles
    Manage subscriptions
    Migrate subscriptions to Stripe
    Set product or subscription quantities
    Mixed interval subscriptions
    Backdate subscriptions
    Set trial periods
    Handle subscriptions with deferred payment
    Apply coupons
    Modify subscriptions
    Manage subscription payment methods
    Analytics
    Manage subscriptions on iOS
Invoicing
Usage-based billing
Quotes
Customer management
Billing with other products
Revenue recovery
Automations
Test your integration
Tax
Overview
Use Stripe tax
Manage compliance
Reporting
Overview
Select a report
Configure reports
Reports API
Reports for multiple accounts
Revenue recognition
Data
Overview
Business and product data use cases
SchemaData freshness
Sigma
Data Pipeline
Import external data
HomeRevenueSubscriptions

Build a subscriptions integration

Create and manage subscriptions to accept recurring payments.

Fixed-price subscription page with Payment Element
Some code

Customize with the Appearance API.

Use the Payment Element to create a custom payment form that you embed in your application to collect payments.

See the Embedded components quickstart to learn how to use the Checkout API to create and manage your overall payment flow.

Use this guide to learn how to sell fixed-price subscriptions. You’ll use the Payment Element to create a custom payment form that you embed in your application.

If you don’t want to build a custom payment form, you can integrate with Checkout. For an immersive version of that end-to-end integration guide, see the Billing quickstart.

If you aren’t ready to code an integration, you can set up basic subscriptions manually in the Dashboard. You can also use Payment Links to set up subscriptions without writing any code. Learn more about designing an integration to understand the decisions you need to make and the resources you need.

What you’ll build

This guide shows you how to:

  • Build a product catalog.
  • Build a registration process that creates a customer.
  • Create subscriptions and collect payment information.
  • Test and monitor payment and subscription status.
  • Let customers change their plan or cancel the subscription.
  • Learn how to use flexible billing mode to access enhanced billing behavior and additional features.

How to build on Stripe

Subscriptions simplify your billing by automatically creating Invoices and PaymentIntents for you. To create and activate a subscription, you need to first create a Product to define what you’re selling, and a Price, which determines the amount to charge and how often. You also need a Customer to store the PaymentMethods used to make each recurring payment.

API object definitions

Resource Definition
CustomerRepresents a customer who purchases a subscription. Use the Customer object associated with a subscription to make and track recurring charges and to manage the products that they subscribe to.
EntitlementRepresents a customer’s access to a feature included in a service product that they subscribe to. When you create a subscription for a customer’s recurring purchase of a product, an active entitlement is automatically created for each feature associated with that product. When a customer accesses your services, use their active entitlements to enable the features included in their subscription.
FeatureRepresents a function or ability that your customers can access when they subscribe to a service product. You can include features in a product by creating ProductFeatures.
InvoiceA statement of amounts a customer owes that tracks payment statuses from draft through paid or otherwise finalized. Subscriptions automatically generate invoices.
PaymentIntentA way to build dynamic payment flows. A PaymentIntent tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods. Invoices automatically create PaymentIntents.
PaymentMethodA customer’s payment methods that they use to pay for your products. For example, you can store a credit card on a Customer object and use it to make recurring payments for that customer. Typically used with the Payment Intents or Setup Intents APIs.
PriceDefines the unit price, currency, and billing cycle for a product.
ProductA good or service that your business sells. A service product can include one or more features.
ProductFeatureRepresents a single feature’s inclusion in a single product. Each product is associated with a ProductFeature for each feature that it includes, and each feature is associated with a ProductFeature for each product that includes it.
SubscriptionRepresents a customer’s scheduled recurring purchase of a product. Use a subscription to collect payments and provide repeated delivery of or continuous access to a product.

Here’s an example of how products, features, and entitlements work together. Imagine that you want to set up a recurring service that offers two tiers: a standard product with basic functionality, and an advanced product that adds extended functionality.

  1. You create two features: basic_features and extended_features.
  2. You create two products: standard_product and advanced_product.
  3. For the standard product, you create one ProductFeature that associates basic_features with standard_product.
  4. For the advanced product, you create two ProductFeatures: one that associates basic_features with advanced_product and one that associates extended_features with advanced_product.

A customer, first_customer, subscribes to the standard product. When you create the subscription, Stripe automatically creates an Entitlement that associates first_customer with basic_features.

Another customer, second_customer, subscribes to the advanced product. When you create the Subscription, Stripe automatically creates two Entitlements: one that associates second_customer with basic_features, and one that associates second_customer with extended_features.

You can determine which features to provision for a customer by retrieving their active entitlements or listening to the Active Entitlement Summary event. You don’t have to retrieve their subscriptions, products, and features.

Set up Stripe

Install the Stripe client of your choice:

build.gradle
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
/* For Gradle, add the following dependency to your build.gradle and replace with the version number you want to use from: - https://mvnrepository.com/artifact/com.stripe/stripe-java or - https://github.com/stripe/stripe-java/releases/latest */ implementation "com.stripe:stripe-java:30.0.0"
pom.xml
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
<!-- For Maven, add the following dependency to your POM and replace with the version number you want to use from: - https://mvnrepository.com/artifact/com.stripe/stripe-java or - https://github.com/stripe/stripe-java/releases/latest --> <dependency> <groupId>com.stripe</groupId> <artifactId>stripe-java</artifactId> <version>30.0.0</version> </dependency>
Other environments
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
# For other environments, manually install the following JARs: # - The Stripe JAR from https://github.com/stripe/stripe-java/releases/latest # - Google Gson from https://github.com/google/gson

Next, install the Stripe CLI. The CLI provides webhook testing, and you can run it to make API calls to Stripe. This guide shows how to use the CLI to set up a pricing model in a later section.

Command Line
homebrew
Install from source
No results
# Install Homebrew to run this command: https://brew.sh/ brew install stripe/stripe-cli/stripe # Connect the CLI to your dashboard stripe login

For additional install options, see Get started with the Stripe CLI.

Create the pricing model
Stripe CLI or Dashboard

Create your products and their prices in the Dashboard or with the Stripe CLI.

This example uses a fixed-price service with two different service-level options: Basic and Premium. For each service-level option, you need to create a product and a recurring price. (If you want to add a one-time charge for something like a setup fee, create a third product with a one-time price. To keep things simple, this example doesn’t include a one-time charge.)

In this example, each product bills at monthly intervals. The price for the Basic product is 5 USD. The price for the Premium product is 15 USD.

Go to the Add a product page and create two products. Add one price for each product, each with a monthly recurring billing period:

  • Premium product: Premium service with extra features

    • Price: Flat rate | 15 USD
  • Basic product: Basic service with minimum features

    • Price: Flat rate | 5 USD

After you create the prices, record the price IDs so you can use them in other steps. Price IDs look like this: price_G0FvDp6vZvdwRZ.

When you’re ready, use the Copy to live mode button at the top right of the page to clone your product from a sandbox to live mode.

Create the Customer
Client and Server

Stripe needs a Customer for each subscription. In your application front end, collect any necessary information from your users and pass it to the back end.

If you need to collect address details, the Address Element enables you to collect a shipping or billing address for your customers. For more information on the Address Element, see the Address Element page.

register.html
<form id="signup-form"> <label> Email <input id="email" type="email" placeholder="Email address" value="test@example.com" required /> </label> <button type="submit"> Register </button> </form>
register.js
const emailInput = document.querySelector('#email'); fetch('/create-customer', { method: 'post', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email: emailInput.value, }), }).then(r => r.json());

On the server, create the Stripe Customer object.

Note

Make sure you store the Customer ID to use in the Checkout Session

Server.java
cURL
Stripe CLI
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
Global configUses single global configuration
StripeClientUses a per-client configuration
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.apiKey =
"sk_test_BQokikJOvBiI2HlWgH4olfQ2"
; CustomerCreateParams params = CustomerCreateParams.builder() .setEmail("{{CUSTOMER_EMAIL}}") .setName("{{CUSTOMER_NAME}}") .setShipping( CustomerCreateParams.Shipping.builder() .setAddress( CustomerCreateParams.Shipping.Address.builder() .setCity("Brothers") .setCountry("US") .setLine1("27 Fredrick Ave") .setPostalCode("97712") .setState("CA") .build() ) .setName("{{CUSTOMER_NAME}}") .build() ) .setAddress( CustomerCreateParams.Address.builder() .setCity("Brothers") .setCountry("US") .setLine1("27 Fredrick Ave") .setPostalCode("97712") .setState("CA") .build() ) .build(); Customer customer = Customer.create(params);

Create the Subscription
Client and Server

Note

If you want to render the Payment Element without first creating a subscription, see Collect payment details before creating an Intent.

Allow your customer to choose a plan, and then create the subscription. In the example in this guide, the customer chooses between a Basic plan or Premium plan.

On the front end, pass the selected price ID and the customer record ID to the back end.

prices.js
fetch('/create-subscription', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ priceId: priceId, customerId: customerId, }), })

On the back end, create the subscription with an incomplete status using payment_behavior=default_incomplete. Then, return the client_secret from the subscription’s first PaymentIntent to the front end to complete payment. To do so, expand the confirmation_secret on the latest invoice of the subscription.

To enable improved subscription behavior, set billing_mode[type] to flexible. You must use the Stripe API version 2025-06-30.basil or later.

Set save_default_payment_method to on_subscription to save the payment method as the default for a subscription when a payment succeeds. Saving a default payment method increases the success rate of future subscription payments.

Server.java
Ruby
Python
PHP
Java
Node.js
Go
.NET
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.apiKey =
"sk_test_BQokikJOvBiI2HlWgH4olfQ2"
; post( "/create-subscription", (request, response) -> { response.type("application/json"); String customerId = request.cookie("customer"); CreateSubscriptionRequest postBody = gson.fromJson( request.body(), CreateSubscriptionRequest.class ); String priceId = postBody.getPriceId(); // Automatically save the payment method to the subscription // when the first payment is successful. SubscriptionCreateParams.PaymentSettings paymentSettings = SubscriptionCreateParams.PaymentSettings .builder() .setSaveDefaultPaymentMethod(SaveDefaultPaymentMethod.ON_SUBSCRIPTION) .build(); // Create the subscription. Note we're expanding the Subscription's // latest invoice and that invoice's confirmation_secret // so we can pass it to the front end to confirm the payment SubscriptionCreateParams subCreateParams = SubscriptionCreateParams .builder() .setCustomer(customerId) .addItem( SubscriptionCreateParams .Item.builder() .setPrice(priceId) .build() ) .setPaymentSettings(paymentSettings) .setPaymentBehavior(SubscriptionCreateParams.PaymentBehavior.DEFAULT_INCOMPLETE) .setBillingMode(SubscriptionCreateParams.BillingMode.FLEXIBLE) .addAllExpand(Arrays.asList("latest_invoice.confirmation_secret")) .build(); Subscription subscription = Subscription.create(subCreateParams); Map<String, Object> responseData = new HashMap<>(); responseData.put("subscriptionId", subscription.getId()); responseData.put("clientSecret", subscription.getLatestInvoiceObject().getConfirmationSecret().getClientSecret()); return StripeObject.PRETTY_PRINT_GSON.toJson(responseData); } );

Note

If you’re using a multi-currency price, use the currency parameter to tell the subscription which of the supported currencies to use. If you omit the currency parameter, the subscription uses the default currency.

The Subscription is now inactive and awaiting payment. The example response below highlights the minimum fields to store, but you can store the fields that your application frequently accesses.

{ "id": "sub_JgRjFjhKbtD2qz", "object": "subscription", "application_fee_percent": null, "automatic_tax": { "disabled_reason": null, "enabled": false, "liability": "null" }, "billing_cycle_anchor": 1623873347,

Collect payment information
Client

Use Stripe Elements to collect payment details and activate the subscription. You can customize Elements to match the look and feel of your application.

The Payment Element supports Link, credit cards, SEPA Direct Debit, and BECS Direct Debit for subscriptions. You can display the enabled payment methods and securely collect payment details based on your customer’s selection.

Set up Stripe Elements

The Payment Element is automatically available as a feature of Stripe.js. Include the Stripe.js script on your payment page by adding it to the head of your HTML file. Always load Stripe.js directly from js.stripe.com to remain PCI compliant. Don’t include the script in a bundle or host a copy of it yourself.

subscribe.html
<head> <title>Checkout</title> <script src="https://js.stripe.com/clover/stripe.js"></script> </head> <body> <!-- content here --> </body>

Create an instance of Stripe with the following JavaScript on your payment page:

subscribe.js
// Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe(
'pk_test_TYooMQauvdEDq54NiTphI7jx'
);

Add the Payment Element to your page

The Payment Element needs a place to live on your payment page. Create an empty DOM node (container) with a unique ID in your payment form.

subscribe.html
<form id="payment-form"> <div id="payment-element"> <!-- Elements will create form elements here --> </div> <button id="submit">Subscribe</button> <div id="error-message"> <!-- Display error message to your customers here --> </div> </form>

After the form loads, create an instance of the Payment Element and mount it to the container DOM node. When you created the subscription, you passed the client_secret value to the front end. Pass this value as an option when you create an instance of Elements.

subscribe.js
const options = { clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in the payment form, passing the client secret obtained in step 5 const elements = stripe.elements(options); const paymentElementOptions = { layout: "tabs", }; // Create and mount the Payment Element const paymentElement = elements.create('payment', paymentElementOptions); paymentElement.mount('#payment-element');

The Payment Element renders a dynamic form that allows your customer to select a payment method. The form automatically collects all necessary payments details for the payment method that they select.

Optional Payment Element configurations

You can optionally do the following:

  • Customize the Payment Element to match the design of your site by passing the appearance object into options when creating an instance of Elements.
  • Configure the Apple Pay interface to return a merchant token to support recurring, automatic reload, and deferred payments.

Complete payment

Use stripe.confirmPayment to complete the payment using details from the Payment Element and activate the subscription. This creates a PaymentMethod, confirms the incomplete subscription’s first PaymentIntent, and makes a charge. If Strong Customer Authentication (SCA) is required for the payment, the Payment Element handles the authentication process before confirming the PaymentIntent.

Provide a return_url to indicate where Stripe redirects the user after they complete the payment. Your user might redirect to an intermediate site first, such as a bank authorization page, before redirecting to the return_url. Card payments immediately redirect to the return_url when a payment is successful.

subscribe.js
const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: "https://example.com/order/123/complete", } }); if (error) { // This point is reached only if there's an immediate error when // confirming the payment. Show an error to your customer (for example, payment // details incomplete) const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; } else { // Your customer redirects to your `return_url`. For some payment // methods, such as iDEAL, your customer redirects to an intermediate // site first to authorize the payment, and then redirects to the `return_url`. } });

When your customer submits a payment, Stripe redirects them to the return_url and includes the following URL query parameters. The return page can use them to get the status of the PaymentIntent so it can display the payment status to the customer.

When you specify the return_url, you can also append your own query parameters for use on the return page.

ParameterDescription
payment_intentThe unique identifier for the PaymentIntent.
payment_intent_client_secretThe client secret of the PaymentIntent object. For subscription integrations, this client_secret is also exposed on the Invoice object through confirmation_secret

When the customer is redirected back to your site, you can use the payment_intent_client_secret to query for the PaymentIntent and display the transaction status to your customer.

Caution

If you have tooling that tracks the customer’s browser session, you might need to add the stripe.com domain to the referrer exclude list. Redirects cause some tools to create new sessions, which prevents you from tracking the complete session.

Use one of the query parameters to retrieve the PaymentIntent. Inspect the status of the PaymentIntent to decide what to show your customers. You can also append your own query parameters when providing the return_url, which persist through the redirect process.

status.js
// Initialize Stripe.js using your publishable key const stripe = Stripe(
'pk_test_TYooMQauvdEDq54NiTphI7jx'
); // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe.retrievePaymentIntent(clientSecret).then(({paymentIntent}) => { const message = document.querySelector('#message') // Inspect the PaymentIntent `status` to indicate the status of the payment // to your customer. // // Some payment methods [immediately succeed or fail][0] upon // confirmation, while others first enter a `processing` status. // // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification switch (paymentIntent.status) { case 'succeeded': message.innerText = 'Success! Payment received.'; break; case 'processing': message.innerText = "Payment processing. We'll update you when payment is received."; break; case 'requires_payment_method': message.innerText = 'Payment failed. Please try another payment method.'; // Redirect your user back to your payment page to attempt collecting // payment again break; default: message.innerText = 'Something went wrong.'; break; } });

Listen for webhooks
Server

To complete the integration, you need to process webhooks sent by Stripe. These events trigger whenever the status in Stripe changes, such as subscriptions creating new invoices. In your application, set up an HTTP handler to accept a POST request containing the webhook event, and verify the signature of the event:

Server.java
Ruby
Python
PHP
Java
Node.js
Go
.NET
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.apiKey =
"sk_test_BQokikJOvBiI2HlWgH4olfQ2"
; post( "/webhook", (request, response) -> { String payload = request.body(); String sigHeader = request.headers("Stripe-Signature"); String endpointSecret = dotenv.get("STRIPE_WEBHOOK_SECRET");

During development, use the Stripe CLI to observe webhooks and forward them to your application. Run the following in a new terminal while your development app is running:

Command Line
stripe listen --forward-to localhost:4242/webhook

For production, set up a webhook endpoint in Workbench, or use the Webhook Endpoints API.

Listen to a few events to complete the remaining steps in this guide. See Subscription events for more details about subscription-specific webhooks.

Provision access to your service
Client and Server

Now that the subscription is active, give your user access to your service. To do this, listen to the customer.subscription.created, customer.subscription.updated, and customer.subscription.deleted events. These events pass a Subscription object that contains a status field indicating whether the subscription is active, past due, or canceled. See the subscription lifecycle for a complete list of statuses.

In your webhook handler:

  1. Verify the subscription status. If it’s active, your user has paid for your product.
  2. Check the product your customer subscribed to and grant access to your service. Checking the product instead of the price gives you more flexibility if you need to change the pricing or billing period.
  3. Store the product.id, subscription.id and subscription.status in your database along with the customer.id you already saved. Check this record when determining which features to enable for the user in your application.

The subscription status might change at any point during its lifetime, even if your application doesn’t directly make any calls to Stripe. For example, a renewal might fail because of an expired credit card, which puts the subscription into a past due status. Or, if you implement the customer portal, a user might cancel their subscription without directly visiting your application. Implementing your handler correctly keeps your application status in sync with Stripe.

Cancel the subscription
Client and Server

You can allow customers to cancel their subscriptions. The example below adds a cancellation option to the account settings page.

Sample subscription cancellation interface

Account settings with the ability to cancel the subscription

script.js
function cancelSubscription(subscriptionId) { return fetch('/cancel-subscription', { method: 'post', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ subscriptionId: subscriptionId, }), }) .then(response => { return response.json(); }) .then(cancelSubscriptionResponse => { // Display to the user that the subscription has been canceled. }); }

On the back end, define the endpoint for your front end to call.

Server.java
Ruby
Python
PHP
Java
Node.js
Go
.NET
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.apiKey =
"sk_test_BQokikJOvBiI2HlWgH4olfQ2"
; post( "/cancel-subscription", (request, response) -> { response.type("application/json"); // Set the default payment method on the customer CancelPostBody postBody = gson.fromJson( request.body(), CancelPostBody.class ); Subscription subscription = Subscription.retrieve( postBody.getSubscriptionId() ); Subscription deletedSubscription = subscription.cancel(); return deletedSubscription.toJson(); } );

Your application receives a customer.subscription.deleted event.

After the subscription is canceled, update your database to remove the Stripe subscription ID you previously stored, and limit access to your service.

When a subscription is canceled, it can’t be reactivated. Instead, collect updated billing information from your customer, update their default payment method, and create a new subscription with their existing customer record.

Test your integration

Test payment methods

Use the following table to test different payment methods and scenarios.

Payment methodScenarioHow to test
BECS Direct DebitYour customer successfully pays with BECS Direct Debit.Fill out the form using the account number 900123456 and BSB 000000. The confirmed PaymentIntent initially transitions to processing, then transitions to the succeeded status three minutes later.
BECS Direct DebitYour customer’s payment fails with an account_closed error code.Fill out the form using the account number 111111113 and BSB 000000.
Credit cardThe card payment succeeds and doesn’t require authentication.Fill out the credit card form using the credit card number 4242 4242 4242 4242 with any expiration, CVC, and postal code.
Credit cardThe card payment requires authentication.Fill out the credit card form using the credit card number 4000 0025 0000 3155 with any expiration, CVC, and postal code.
Credit cardThe card is declined with a decline code like insufficient_funds.Fill out the credit card form using the credit card number 4000 0000 0000 9995 with any expiration, CVC, and postal code.
SEPA Direct DebitYour customer successfully pays with SEPA Direct Debit.Fill out the form using the account number AT321904300235473204. The confirmed PaymentIntent initially transitions to processing, then transitions to the succeeded status three minutes later.
SEPA Direct DebitYour customer’s PaymentIntent status transitions from processing to requires_payment_method.Fill out the form using the account number AT861904300235473202.

Monitor events

Set up webhooks to listen to subscription change events, such as upgrades and cancellations. Learn more about subscription webhooks. You can view events in the Dashboard or with the Stripe CLI.

For more details, see testing your Billing integration.

OptionalLet customers change their plans
Client and Server

To let your customers change their subscription, collect the price ID of the option they want to change to. Then, send the new price ID from the front end to a back end endpoint. The example below also passes the subscription ID, but you can retrieve it from your database for your logged in user.

script.js
function updateSubscription(priceId, subscriptionId) { return fetch('/update-subscription', { method: 'post', headers: { 'Content-type': 'application/json', }, body: JSON.stringify({ subscriptionId: subscriptionId, newPriceId: priceId, }), }) .then(response => { return response.json(); }) .then(response => { return response; }); }

On the back end, define the endpoint for your front end to call, passing the subscription ID and the new price ID. The subscription is now Premium at 15 USD per month, instead of Basic at 5 USD per month.

Server.java
Ruby
Python
PHP
Java
Node.js
Go
.NET
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.apiKey =
"sk_test_BQokikJOvBiI2HlWgH4olfQ2"
; post( "/update-subscription", (request, response) -> { response.type("application/json"); // Set the default payment method on the customer UpdatePostBody postBody = gson.fromJson( request.body(), UpdatePostBody.class ); Subscription subscription = Subscription.retrieve( postBody.getSubscriptionId() ); SubscriptionUpdateParams params = SubscriptionUpdateParams .builder() .addItem( SubscriptionUpdateParams .Item.builder() .setId(subscription.getItems().getData().get(0).getId()) .setPrice("price_H1NlVtpo6ubk0m") .build() ) .setCancelAtPeriodEnd(false) .build(); subscription.update(params); return subscription.toJson(); } );

Your application receives a customer.subscription.updated event.

OptionalPreview a price change
Client and Server

When your customer changes their subscription, there’s often an adjustment to the amount they owe, known as a proration. You can use the create preview invoice endpoint to display the adjusted amount to your customers.

On the front end, pass the create preview invoice details to a back-end endpoint.

script.js
function createPreviewInvoice( customerId, subscriptionId, newPriceId, trialEndDate ) { return fetch('/create-preview-invoice', { method: 'post', headers: { 'Content-type': 'application/json', }, body: JSON.stringify({ customerId: customerId, subscriptionId: subscriptionId, newPriceId: newPriceId, }), }) .then(response => { return response.json(); }) .then((invoice) => { return invoice; }); }

On the back end, define the endpoint for your front end to call.

Server.java
Ruby
Python
PHP
Java
Node.js
Go
.NET
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.apiKey =
"sk_test_BQokikJOvBiI2HlWgH4olfQ2"
; post( "/create-preview-invoice", (request, response) -> { response.type("application/json"); PreviewInvoicePostBody postBody = gson.fromJson( request.body(), PreviewInvoicePostBody.class ); Subscription subscription = Subscription.retrieve( postBody.getSubscriptionId() ); InvoiceCreatePreviewParams invoiceParams = InvoiceCreatePreviewParams .builder() .setCustomer(postBody.getCustomerId()) .setSubscription(postBody.getSubscriptionId()) .setSubscriptionDetails( InvoiceCreatePreviewParams.SubscriptionDetails.builder() .addItem( InvoiceCreatePreviewParams.SubscriptionDetails.Item.builder() .setId(subscription.getItems().getData().get(0).getId()) .setDeleted(true) .build() ) .addItem( InvoiceCreatePreviewParams.SubscriptionDetails.Item.builder() .setPrice(dotenv.get(postBody.getNewPriceId().toUpperCase())) .build() ) .build() ) .build(); Invoice invoice = Invoice.createPreview(invoiceParams); return invoice.toJson(); } );

OptionalDisplay the customer payment method
Client and Server

Displaying the brand and last four digits of your customer’s card can help them know which card is being charged, or if they need to update their payment method.

On the front end, send the payment method ID to a back-end endpoint that retrieves the payment method details.

script.js
function retrieveCustomerPaymentMethod(paymentMethodId) { return fetch('/retrieve-customer-payment-method', { method: 'post', headers: { 'Content-type': 'application/json', }, body: JSON.stringify({ paymentMethodId: paymentMethodId, }), }) .then((response) => { return response.json(); }) .then((response) => { return response; }); }

On the back end, define the endpoint for your front end to call.

Server.java
Ruby
Python
PHP
Java
Node.js
Go
.NET
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.apiKey =
"sk_test_BQokikJOvBiI2HlWgH4olfQ2"
; post( "/retrieve-customer-payment-method", (request, response) -> { response.type("application/json"); // Set the default payment method on the customer PaymentMethodBody paymentMethodBody = gson.fromJson( request.body(), PaymentMethodBody.class ); PaymentMethod paymentMethod = PaymentMethod.retrieve( paymentMethodBody.getPaymentMethodId() ); return paymentMethod.toJson(); } );

Example response:

{ "id": "pm_1GcbHY2eZvKYlo2CoqlVxo42", "object": "payment_method", "billing_details": { "address": { "city": null, "country": null, "line1": null, "line2": null, "postal_code": null,

Note

We recommend that you save the paymentMethod.id and last4 in your database, for example, paymentMethod.id as stripeCustomerPaymentMethodId in your users collection or table. You can optionally store exp_month, exp_year, fingerprint, billing_details as needed. This limits the number of calls you make to Stripe, for performance efficiency and to avoid possible rate limiting.

Disclose Stripe to your customers

Stripe collects information on customer interactions with Elements to provide services to you, prevent fraud, and improve its services. This includes using cookies and IP addresses to identify which Elements a customer saw during a single checkout session. You’re responsible for disclosing and obtaining all rights and consents necessary for Stripe to use data in these ways. For more information, visit our privacy center.

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