Ir a contenido
Crea una cuenta
o
Inicia sesión
Logotipo de Stripe Docs
/
Pregúntale a la IA
Crear una cuenta
Iniciar sesión
Empieza ahora
Pagos
Ingresos
Plataformas y marketplaces
Gestión del dinero
Recursos para desarrolladores
Resumen
Billing
ResumenAcerca de las API de facturación
Suscripciones
    Resumen
    Cómo funcionan las suscripciones
    Empieza ahora
    Inicio rápido
    Planificar una integración
    Crear una integración
    Casos de uso
    Acerca de las suscripciones
    Habilitar modo de facturación
    Configurar eventos de suscripción
    Derechos
    Facturas de suscripciones
    Calendarios de suscripciones
    Modelos de tarifas recurrentes
    Autenticación reforzada de clientes (SCA)
    Configurar suscripciones
    Configurar métodos de cobro
    Inserta un cuadro de tarifas
    Establecer ciclos de facturación
    Administración de suscripciones
    Migrar suscripciones a Stripe
    Establecer cantidades de productos o suscripciones
    Suscripciones a intervalos combinados
    Suscripciones con fechas pasadas
    Configura períodos de prueba
    Gestionar suscripciones con pago diferido
    Aplica cupones
    Modificar suscripciones
    Gestionar métodos de pago de suscripciones
    Análisis
    Administrar suscripciones en iOS
Invoicing
Cobro por consumo
Presupuestos
Gestión de clientes
Gestión de cobros con otros productos
Recuperación de ingresos
Automatizaciones
Prueba tu integración
Impuesto
Resumen
Usa Stripe Tax
Gestiona el cumplimiento de la normativa
Elaboración de informes
Resumen
Seleccionar un informe
Configura informes
API de informes
Informes para varias cuentas
Reconocimiento de ingresos
Datos
ResumenEsquema
Informes personalizados
Data Pipeline
Gestión de datos
InicioIngresosSubscriptions

Nota

Esta página aún no está disponible en este idioma. Estamos trabajando intensamente para que nuestra documentación esté disponible en más idiomas. Ofreceremos la traducción en cuanto esté disponible.

Build a subscriptions integration

Create and manage subscriptions to accept recurring payments.

Learn how to sell fixed-price subscriptions. You’ll use the Mobile Payment Element to create a custom payment form that you embed in your app.

Fixed-price subscription page with Stripe Checkout

Nota

If you’re selling digital products or services that are consumed within your app (for example, subscriptions, in-game currencies, game levels, access to premium content, or unlocking a full version), you must use Apple’s in-app purchase APIs. This rule has some exceptions, including one-to-one personal services and apps based in specific regions. See the App Store review guidelines for more information.

Build your subscription

This guide shows you how to:

  • Model your business by building a product catalog.
  • Create a registration process to add customers.
  • Create subscriptions and collect payment information.
  • Test and monitor the status of payments and subscriptions.
  • 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 model it 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 model what is being sold, and a Price which determines the interval and amount to charge. You also need a Customer to store 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

The React Native SDK is open source and fully documented. Internally, it uses the native iOS and Android SDKs. To install Stripe’s React Native SDK, run one of the following commands in your project’s directory (depending on which package manager you use):

Command Line
yarn add @stripe/stripe-react-native

Next, install some other necessary dependencies:

  • For iOS, go to the ios directory and run pod install to ensure that you also install the required native dependencies.
  • For Android, there are no more dependencies to install.

Nota

We recommend following the official TypeScript guide to add TypeScript support.

Stripe initialization

To initialize Stripe in your React Native app, either wrap your payment screen with the StripeProvider component, or use the initStripe initialization method. Only the API publishable key in publishableKey is required. The following example shows how to initialize Stripe using the StripeProvider component.

import { useState, useEffect } from 'react'; import { StripeProvider } from '@stripe/stripe-react-native'; function App() { const [publishableKey, setPublishableKey] = useState(''); const fetchPublishableKey = async () => { const key = await fetchKey(); // fetch key from your server here setPublishableKey(key); }; useEffect(() => { fetchPublishableKey(); }, []); return ( <StripeProvider publishableKey={publishableKey} merchantIdentifier="merchant.identifier" // required for Apple Pay urlScheme="your-url-scheme" // required for 3D Secure and bank redirects > {/* Your app code here */} </StripeProvider> ); }

Nota

Use your API test keys while you test and develop, and your live mode keys when you publish your app.

And then 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 frontend, collect any necessary information from your users and pass it to the backend.

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, visit the Address Element page.

RegisterView.js
import React from 'react'; import {View, TextInput, StyleSheet, Button, Platform} from 'react-native'; function RegisterView() { const [email, setEmail] = React.useState(''); const createCustomer = async () => { const apiEndpoint = Platform.OS === 'ios' ? 'http://localhost:4242' : 'http://10.0.2.2:4567'; const response = await fetch(`${apiEndpoint}/create-customer`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email: email, }), }); if (response.status === 200) { const customer = await response.json(); console.log(customer); } }; return ( <View> <TextInput style={styles.input} placeholder="Email" value={email} onChangeText={setEmail} /> <Button title="Register" onPress={async () => { await createCustomer(); }} /> </View> ); } const styles = StyleSheet.create({ input: { height: 40, margin: 12, borderWidth: 1, padding: 10, }, }); export default RegisterView;

On the server, create the Stripe customer object.

Command Line
cURL
Stripe CLI
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
curl https://api.stripe.com/v1/customers \ -u "
sk_test_BQokikJOvBiI2HlWgH4olfQ2
:"
\ -d email={{CUSTOMER_EMAIL}} \ -d name={{CUSTOMER_NAME}} \ -d "shipping[address][city]"=Brothers \ -d "shipping[address][country]"=US \ -d "shipping[address][line1]"="27 Fredrick Ave" \ -d "shipping[address][postal_code]"=97712 \ -d "shipping[address][state]"=CA \ -d "shipping[name]"={{CUSTOMER_NAME}} \ -d "address[city]"=Brothers \ -d "address[country]"=US \ -d "address[line1]"="27 Fredrick Ave" \ -d "address[postal_code]"=97712 \ -d "address[state]"=CA

Create the subscription
Client and Server

Nota

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

Let your new customer choose a plan and then create the subscription—in this guide, they choose between Basic and Premium.

In your app, pass the selected price ID and the ID of the customer record to the backend.

PricesView.js
const createSubscription = async (priceId, customerId) => { const apiEndpoint = Platform.OS === 'ios' ? 'http://localhost:4242' : 'http://10.0.2.2:4567'; const response = await fetch(`${apiEndpoint}/create-subscription`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ priceId: priceId, customerId: customerId, }), }); if (response.status === 200) { const subscription = await response.json(); return subscription; } };

On the backend, create the subscription with status incomplete using payment_behavior=default_incomplete. Then return the client_secret from the subscription’s first payment intent to the frontend to complete payment by expanding theconfirmation_secret on the latest invoice of the subscription.

To enable improved subscription behavior, set billing_mode[type] to flexible. You must use 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.rb
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.api_key =
'sk_test_BQokikJOvBiI2HlWgH4olfQ2'
post '/create-subscription' do content_type 'application/json' data = JSON.parse(request.body.read) customer_id = cookies[:customer] price_id = data['priceId'] # 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 subscription = Stripe::Subscription.create( customer: customer_id, items: [{ price: price_id, }], payment_behavior: 'default_incomplete', payment_settings: {save_default_payment_method: 'on_subscription'}, billing_mode: {type: 'flexible'}, expand: ['latest_invoice.confirmation_secret'] ) { subscriptionId: subscription.id, clientSecret: subscription.latest_invoice.confirmation_secret.client_secret }.to_json end

Nota

If you’re using a multi-currency Price, use the currency parameter to tell the Subscription which of the Price’s currencies to use. (If you omit the currency parameter, then the Subscription uses the Price’s default currency.)

At this point the Subscription is inactive and awaiting payment. Here’s an example response. The minimum fields to store are highlighted, but store whatever 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 the Payment Sheet to collect payment details and activate the subscription. You can customize Elements to match the look and feel of your application.

The Payment Sheet securely collects all necessary payment details for a wide variety of payments methods. Learn about the supported payment methods for Payment Sheet and Subscriptions.

Add the Payment Element to your app

Nota

This step shows one way to get started, but you can use any in-app payments integration.

Initialize and present the Mobile Payment Element using the PaymentSheet class.

SubscribeView.js
import React from 'react'; import {useStripe, PaymentSheetError} from '@stripe/stripe-react-native'; import {View, Button} from 'react-native'; function SubscribeView({clientSecret}) { const {initPaymentSheet, presentPaymentSheet} = useStripe(); React.useEffect(() => { const initializePaymentSheet = async () => { const {error} = await initPaymentSheet({ paymentIntentClientSecret: clientSecret, returnURL: 'stripe-example://payment-sheet', // Set `allowsDelayedPaymentMethods` to true if your business handles // delayed notification payment methods like US bank accounts. allowsDelayedPaymentMethods: true, }); if (error) { // Handle error } }; initializePaymentSheet(); }, [clientSecret, initPaymentSheet]); return ( <View> <Button title="Subscribe" onPress={async () => { const {error} = await presentPaymentSheet(); if (error) { if (error.code === PaymentSheetError.Failed) { // Handle failed } else if (error.code === PaymentSheetError.Canceled) { // Handle canceled } } else { // Payment succeeded } }} /> </View> ); } export default SubscribeView;

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

Setting allowsDelayedPaymentMethods to true allows delayed notification payment methods like US bank accounts. For these payment methods, the final payment status isn’t known when the PaymentSheet completes, and instead succeeds or fails later. If you support these types of payment methods, inform the customer their order is confirmed and only fulfill their order (for example, ship their product) when the payment is successful.

You can customize the Payment Element to match the design of your app by using the appearance property your PaymentSheet.Configuration object.

Confirm payment

The Mobile Payment Element creates a PaymentMethod and confirms the incomplete Subscription’s first PaymentIntent, causing a charge to be made. If Strong Customer Authentication (SCA) is required for the payment, the Payment Element handles the authentication process before confirming the PaymentIntent.

Set up a return URL (iOS only)
Client-side

When a customer exits your app (for example to authenticate in Safari or their banking app), provide a way for them to automatically return to your app. Many payment method types require a return URL. If you don’t provide one, we can’t present payment methods that require a return URL to your users, even if you’ve enabled them.

To provide a return URL:

  1. Register a custom URL. Universal links aren’t supported.
  2. Configure your custom URL.
  3. Set up your root component to forward the URL to the Stripe SDK as shown below.

Nota

If you’re using Expo, set your scheme in the app.json file.

App.tsx
import { useEffect, useCallback } from 'react'; import { Linking } from 'react-native'; import { useStripe } from '@stripe/stripe-react-native'; export default function MyApp() { const { handleURLCallback } = useStripe(); const handleDeepLink = useCallback( async (url: string | null) => { if (url) { const stripeHandled = await handleURLCallback(url); if (stripeHandled) { // This was a Stripe URL - you can return or add extra handling here as you see fit } else { // This was NOT a Stripe URL – handle as you normally would } } }, [handleURLCallback] ); useEffect(() => { const getUrlAsync = async () => { const initialUrl = await Linking.getInitialURL(); handleDeepLink(initialUrl); }; getUrlAsync(); const deepLinkListener = Linking.addEventListener( 'url', (event: { url: string }) => { handleDeepLink(event.url); } ); return () => deepLinkListener.remove(); }, [handleDeepLink]); return ( <View> <AwesomeAppComponent /> </View> ); }

Additionally, set the returnURL when you call the initPaymentSheet method:

await initPaymentSheet({ ... returnURL: 'your-app://stripe-redirect', ... });

For more information on native URL schemes, refer to the Android and iOS docs.

OpcionalEnable Apple Pay

Register for an Apple Merchant ID

Obtain an Apple Merchant ID by registering for a new identifier on the Apple Developer website.

Fill out the form with a description and identifier. Your description is for your own records and you can modify it in the future. Stripe recommends using the name of your app as the identifier (for example, merchant.com.{{YOUR_APP_NAME}}).

Create a new Apple Pay certificate

Create a certificate for your app to encrypt payment data.

Go to the iOS Certificate Settings in the Dashboard, click Add new application, and follow the guide.

Download a Certificate Signing Request (CSR) file to get a secure certificate from Apple that allows you to use Apple Pay.

One CSR file must be used to issue exactly one certificate. If you switch your Apple Merchant ID, you must go to the iOS Certificate Settings in the Dashboard to obtain a new CSR and certificate.

Integrate with Xcode

Add the Apple Pay capability to your app. In Xcode, open your project settings, click the Signing & Capabilities tab, and add the Apple Pay capability. You might be prompted to log in to your developer account at this point. Select the merchant ID you created earlier, and your app is ready to accept Apple Pay.

Enable the Apple Pay capability in Xcode

Add Apple Pay

When you call initPaymentSheet, pass in an ApplePayParams with merchantCountryCode set to the country code of your business.

In accordance with Apple’s guidelines for recurring payments, you must also set a cardItems that includes a RecurringCartSummaryItem with the amount you intend to charge (for example, “$59.95 a month”).

You can also adopt merchant tokens by setting the request with its type set to PaymentRequestType.Recurring

To learn more about how to use recurring payments with Apple Pay, see Apple’s PassKit documentation.

const initializePaymentSheet = async () => { const recurringSummaryItem = { label: 'My Subscription', amount: '59.99', paymentType: 'Recurring', intervalCount: 1, intervalUnit: 'month', // Payment starts today startDate: new Date().getTime() / 1000, // Payment ends in one year endDate: new Date().getTime() / 1000 + 60 * 60 * 24 * 365, }; const {error} = await initPaymentSheet({ // ... applePay: { merchantCountryCode: 'US', cartItems: [recurringSummaryItem], request: { type: PaymentRequestType.Recurring, description: 'Recurring', managementUrl: 'https://my-backend.example.com/customer-portal', billing: recurringSummaryItem, billingAgreement: "You'll be billed $59.99 every month for the next 12 months. To cancel at any time, go to Account and click 'Cancel Membership.'", }, }, }); };

Order tracking

To add order tracking information in iOS 16 or later, configure a setOrderTracking callback function. Stripe calls your implementation after the payment is complete, but before iOS dismisses the Apple Pay sheet.

In your implementation of setOrderTracking callback function, fetch the order details from your server for the completed order, and pass the details to the provided completion function.

To learn more about order tracking, see Apple’s Wallet Orders documentation.

await initPaymentSheet({ // ... applePay: { // ... setOrderTracking: async complete => { const apiEndpoint = Platform.OS === 'ios' ? 'http://localhost:4242' : 'http://10.0.2.2:4567'; const response = await fetch( `${apiEndpoint}/retrieve-order?orderId=${orderId}`, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }, ); if (response.status === 200) { const orderDetails = await response.json(); // orderDetails should include orderIdentifier, orderTypeIdentifier, // authenticationToken and webServiceUrl complete(orderDetails); } }, }, });

Listen for webhooks
Server

To complete the integration, you need to process webhooks sent by Stripe. These are events triggered whenever state inside of 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.rb
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.api_key =
'sk_test_BQokikJOvBiI2HlWgH4olfQ2'
post '/webhook' do # You can use webhooks to receive information about asynchronous payment events. # For more about our webhook events check out https://stripe.com/docs/webhooks. webhook_secret = ENV['STRIPE_WEBHOOK_SECRET'] payload = request.body.read if !webhook_secret.empty?

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 URL in the Dashboard, or use the Webhook Endpoints API.

You need to 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 which 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 then your user has paid for your product.
  2. Check the product the 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 interval.
  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 state of a subscription might change at any point during its lifetime, even if your application does not directly make any calls to Stripe. For example, a renewal might fail due to an expired credit card, which puts the subscription into a past due state. 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 state in sync with Stripe.

Cancel the subscription
Client and Server

It’s common to allow customers to cancel their subscriptions. This example adds a cancellation option to the account settings page.

The example collects the subscription ID on the frontend, but your application can get this information from your database for your logged in user.

Sample subscription cancelation interface.

Account settings with the ability to cancel the subscription

SubscriptionView.js
const cancelSubscription = async subscriptionId => { const apiEndpoint = Platform.OS === 'ios' ? 'http://localhost:4242' : 'http://10.0.2.2:4567'; const response = await fetch(`${apiEndpoint}/cancel-subscription`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ subscriptionId: subscriptionId, }), }); if (response.status === 200) { const subscription = await response.json(); return subscription; } };

On the backend, define the endpoint for your app to call.

server.rb
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.api_key =
'sk_test_BQokikJOvBiI2HlWgH4olfQ2'
post '/cancel-subscription' do content_type 'application/json' data = JSON.parse request.body.read deleted_subscription = Stripe::Subscription.cancel(data['subscriptionId']) deleted_subscription.to_json end

Your backend 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.

OpcionalLet 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 app to a backend endpoint. This example also passes the subscription ID, but you can retrieve it from your database for your logged in user.

UpdateSubscription.js
const updateSubscription = async (subscriptionId, priceId) => { const apiEndpoint = Platform.OS === 'ios' ? 'http://localhost:4242' : 'http://10.0.2.2:4567'; const response = await fetch(`${apiEndpoint}/update-subscription`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ subscriptionId: subscriptionId, priceId: priceId, }), }); if (response.status === 200) { const subscription = await response.json(); return subscription; } };

On the backend, define the endpoint for your frontend 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.rb
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.api_key =
'sk_test_BQokikJOvBiI2HlWgH4olfQ2'
post '/update-subscription' do content_type 'application/json' data = JSON.parse request.body.read subscription = Stripe::Subscription.retrieve(data['subscriptionId']) updated_subscription = Stripe::Subscription.update( data['subscriptionId'], cancel_at_period_end: false, items: [ { id: subscription.items.data[0].id, price: 'price_H1NlVtpo6ubk0m' } ] ) updated_subscription.to_json end

Your application receives a customer.subscription.updated event.

OpcionalPreview 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.

From the app, pass the preview invoice details to a backend endpoint.

CreatePreviewInvoice.js
const createPreviewInvoice = async (subscriptionId, priceId, newPriceId) => { const apiEndpoint = Platform.OS === 'ios' ? 'http://localhost:4242' : 'http://10.0.2.2:4567'; const response = await fetch(`${apiEndpoint}/create-preview-invoice`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ subscriptionId: subscriptionId, priceId: priceId, newPriceId: newPriceId, }), }); if (response.status === 200) { const invoice = await response.json(); return invoice; } };

On the backend, define the endpoint for your frontend to call.

server.rb
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.api_key =
'sk_test_BQokikJOvBiI2HlWgH4olfQ2'
post '/create-preview-invoice' do content_type 'application/json' data = JSON.parse request.body.read subscription = Stripe::Subscription.retrieve(data['subscriptionId']) invoice = Stripe::Invoice.create_preview( customer: data['customerId'], subscription: data['subscriptionId'], subscription_details: { items: [ { id: subscription.items.data[0].id, deleted: true }, { price: ENV[data['newPriceId']], deleted: false } ] } ) invoice.to_json end

OpcionalDisplay 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.

RetrieveCustomerPaymentMethod.js
const retrieveCustomerPaymentMethod = async paymentMethodId => { const apiEndpoint = Platform.OS === 'ios' ? 'http://localhost:4242' : 'http://10.0.2.2:4567'; const response = await fetch( `${apiEndpoint}/retrieve-customer-payment-method`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ paymentMethodId: paymentMethodId, }), }, ); if (response.status === 200) { const paymentMethod = await response.json(); return paymentMethod; } };

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

server.rb
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.api_key =
'sk_test_BQokikJOvBiI2HlWgH4olfQ2'
post '/retrieve-customer-payment-method' do content_type 'application/json' data = JSON.parse request.body.read payment_method = Stripe::PaymentMethod.retrieve(data['paymentMethodId']) payment_method.to_json end

Example response:

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

Nota

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 is to limit the number of calls you make to Stripe—for both 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.

¿Te fue útil esta página?
SíNo
  • ¿Necesitas ayuda? Ponte en contacto con soporte.
  • Únete a nuestro programa de acceso anticipado.
  • Echa un vistazo a nuestro registro de cambios.
  • ¿Tienes alguna pregunta? Contacto.
  • ¿LLM? Lee llms.txt.
  • Con tecnología de Markdoc