Ir a contenido
Crea una cuenta o inicia sesión
Logotipo de la documentación de Stripe
/
Pregúntale a la IA
Crear cuentaIniciar sesión
Empezar
Pagos
Ingresos
Plataformas y marketplaces
Gestión del dinero
Recursos para desarrolladores
API y SDKAyuda
ResumenAceptar un pagoActualiza tu integración
Pagos por Internet
ResumenEncuentra tu caso de uso
Utiliza Payment Links
Usa una página de proceso de compra prediseñada
Crea una integración personalizada con Elements
Desarrolla una integración en la aplicación
    Resumen
    Hoja de pago
    Payment Element
    Address Element
    Elemento de mensajería de método de pago
    Enlace para compras dentro de la aplicación
    Gestionar los métodos de pago en la configuración
    Migrar a tokens de confirmación
    Tarjetas estadounidenses y canadienses
Usa Managed Payments
Pagos recurrentes
Pagos en persona
Terminal
Métodos de pago
Añadir métodos de pago
Gestiona los métodos de pago
Proceso de compra más rápido con Link
Aspectos básicos de las operaciones de pago
Análisis
Saldos y plazos de liquidación
Cumplimiento de la normativa y seguridad
Divisas
Pagos rechazados
Disputas
Prevención de fraude
Protección antifraude de Radar
Transferencias
RecibosReembolsos y cancelaciones
Integraciones avanzadas
Flujos de pagos personalizados
Capacidad adquirente flexible
Pagos fuera de la sesión
Orquestación de varios responsables del tratamiento
Más allá de los pagos
Constituye tu empresa
Criptomonedas
Comercio agéntico
Pagos automáticos
Financial Connections
Climate
Verificar identidades
Estados Unidos
Español (España)
InicioPagosBuild an in-app integration

Manage payment methods in settings

Use the Payment Method Settings Sheet to let your customers manage their payment methods in your app settings page.

Nota

The Payment Method Settings Sheet is intended for use on an app settings page. For checkout and payments, use the In-app Payments, which also has built-in support for saving and displaying payment methods and supports more payment methods than the Payment Method Settings Sheet.

Nota

In code, this component is referenced as CustomerSheet for historical reasons. Throughout the documentation, when you see CustomerSheet in code examples, this refers to the Payment Method Settings Sheet.

The Payment Method Settings Sheet is a prebuilt UI component that lets your customers manage their saved payment methods. You can use the Payment Method Settings Sheet UI outside of a checkout flow, and the appearance and styling is customizable to match the appearance and aesthetic of your app. Customers can add and remove payment methods, which get saved to the customer object, and set their default payment method stored locally on the device. Use both the In-app Payments and the Payment Method Settings Sheet to provide customers a consistent end-to-end solution for saved payment methods.

Screenshot of Payment Method Settings Sheet presenting multiple saved payment methods in an iOS app.

Configura Stripe

Primero, necesitas una cuenta de Stripe. Regístrate ahora.

El SDK para React Native es de código abierto y está plenamente documentado. Internamente, utiliza el SDK de iOS nativo y Android. Para instalar el SDK para React Native de Stripe, ejecuta uno de los siguientes comandos en el directorio del proyecto (en función del administrador de paquetes que utilices):

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

A continuación, instala otras dependencias necesarias:

  • Para iOS, navega hasta el directorio de ios y ejecuta pod install para asegurarte de instalar también las dependencias nativas necesarias.
  • Para Android, no hay más dependencias para instalar.

Nota

Recomendamos seguir la guía oficial de TypeScript para añadir compatibilidad con TypeScript.

Inicialización de Stripe

Para inicializar Stripe en tu aplicación React Native, ajusta tu pantalla de pago con el componente StripeProvider o usa el método de inicialización initStripe. Solo se requiere la clave publicable de la API en publishableKey. El siguiente ejemplo muestra cómo inicializar Stripe mediante el componente StripeProvider.

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

Usa las claves de prueba de la API durante las pruebas y las tareas de desarrollo, y las claves del modo activo cuando publiques tu aplicación.

Habilitar los métodos de pago

Visualiza tu configuración de métodos de pago y habilita los que quieras aceptar. Se necesita al menos un método de pago habilitado para crear un SetupIntent.

De forma predeterminada, Stripe habilita tarjetas y otros métodos de pago habituales que pueden ayudarte a llegar a más clientes, pero te recomendamos activar otros métodos de pago que sean relevantes para tu empresa y tus clientes. Consulta Compatibilidad con métodos de pago para obtener información sobre productos y métodos de pago y nuestra página de tarifas para conocer las comisiones.

Nota

CustomerSheet only supports cards and US bank accounts.

Add Customer endpoints
Lado del servidor

Compara las referencias de Customers v1 y Accounts v2

Si tu plataforma Connect utiliza Cuentas configuradas por el cliente, utiliza nuestra guía para reemplazar las referencias del cliente y de los eventos en tu código por las referencias equivalentes de la API Accounts v2.

Create two endpoints on your server: one for fetching a CustomerSession client secret, and one to create a SetupIntent for saving a new payment method to the Customer.

  1. Create an endpoint to return a Customer ID and a CustomerSession client secret.
Command Line
curl
Ruby
Python
PHP
Node.js
Java
No results
# Create a Customer (skip this and get the existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u
sk_test_BQokikJOvBiI2HlWgH4olfQ2
:
\ -X "POST" curl https://api.stripe.com/v1/customer_sessions \ -u
sk_test_BQokikJOvBiI2HlWgH4olfQ2
:
\ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[customer_sheet][enabled]"=true \ -d "components[customer_sheet][features][payment_method_remove]"=enabled

Nota

Integrations with legacy customer ephemeral keys results in saved payment methods having an allow_redisplay value of unspecified. To display these payment methods in addition to payment methods saved while using Customer Sessions, set payment_method_allow_redisplay_filters to ["unspecified", "always"]. For more information, see CustomerSessions.

  1. Create an endpoint to return a SetupIntent configured with the Customer ID.
Command Line
curl
Ruby
Python
PHP
Node.js
Java
No results
# Create a Customer (skip this and get the existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u
sk_test_BQokikJOvBiI2HlWgH4olfQ2
:
\ -X "POST" curl https://api.stripe.com/v1/setup_intents \ -u
sk_test_BQokikJOvBiI2HlWgH4olfQ2
:
\ -d "customer"="{{CUSTOMER_ID}}" \

If you only plan to use the payment method for future payments when your customer is present during the checkout flow, set the usage parameter to on_session to improve authorization rates.

Initialize the sheet

Create a ClientSecretProvider object that implements two methods. CustomerSheet needs it to communicate with Stripe using CustomerSession objects and the endpoints you created earlier.

import {ClientSecretProvider, CustomerSessionClientSecret} from '@stripe/stripe-react-native'; const clientSecretProvider: ClientSecretProvider = { // Must return an object with customerId and clientSecret async provideCustomerSessionClientSecret(): Promise<CustomerSessionClientSecret> { const result = await MyBackend.createCustomerSession(); return { customerId: result.customer, clientSecret: result.customerSessionClientSecret, }; }, // Must return a string async provideSetupIntentClientSecret(): Promise<string> { const result = await MyBackend.createSetupIntent(); return result.setupIntent; } };

Next, configure the Payment Method Settings Sheet using the CustomerSheet class, by providing your desired settings to CustomerSheet.initialize.

import {CustomerSheet} from '@stripe/stripe-react-native'; const {error} = await CustomerSheet.initialize({ // You must provide intentConfiguration and clientSecretProvider intentConfiguration: { paymentMethodTypes: ['card'], }, clientSecretProvider: clientSecretProvider, headerTextForSelectionScreen: 'Manage your payment method', returnURL: 'my-return-url://', });

Present the sheet

Present the Payment Method Settings Sheet using CustomerSheet. When the customer dismisses the sheet, the promise resolves with a CustomerSheetResult.

import {CustomerSheet} from '@stripe/stripe-react-native'; const {error, paymentOption, paymentMethod} = await CustomerSheet.present(); if (error) { if (error.code === CustomerSheetError.Canceled) { // Customer dismissed the sheet without changing their payment option } else { // Show the error in your UI } } else { if (paymentOption) { // Configure your UI based on the payment option MyBackend.setDefaultPaymentMethod(paymentMethod.id); } if (paymentMethod) { console.log(JSON.stringify(paymentMethod, null, 2)); } }
  • If the customer selects a payment method, the result contains a paymentOption. The associated value is the selected PaymentOption, or nil if the user deleted the previously-selected payment method. You can find the full payment method details in the paymentMethod field.
  • If the user cancels the sheet, the result contains an error with the error.code === CustomerSheetError.Canceled. The selected payment method doesn’t change.
  • If an error occurs, the details are included in error.

Learn more about how to enable Apple Pay.

OpcionalEnable ACH payments

To enable ACH debit payments, enable US Bank Account as a payment method in the settings section of the Dashboard.

OpcionalFetch the selected payment method

To fetch the default payment method without presenting the Payment Method Settings Sheet, call CustomerSheet.retrievePaymentOptionSelection() after initializing the sheet.

// Call CustomerSheet.initialize() ... const { error, paymentOption, paymentMethod, } = await CustomerSheet.retrievePaymentOptionSelection();

OpcionalPersonaliza la hoja

Aspecto

Customize the colors, fonts, and other appearance attributes to match the look and feel of your app by using the appearance API.

Datos de facturación predeterminados

To set default values for billing details collected in the Payment Method Settings Sheet, configure the defaultBillingDetails property. The Payment Method Settings Sheet pre-populates its fields with the values that you provide.

await CustomerSheet.initialize({ // ... defaultBillingDetails: { email: 'foo@bar.com', address: { country: 'US', }, }, });

Recopilación de los datos de facturación

Use billingDetailsCollectionConfiguration to specify how you want to collect billing details in the Payment Method Settings Sheet.

Puedes recopilar el nombre, el correo electrónico, el número de teléfono y la dirección del cliente.

Si no tienes intención de recopilar los valores que requiere el método de pago, debes hacer lo siguiente:

  1. Attach the values that aren’t collected by the Payment Method Settings Sheet to the defaultBillingDetails property.
  2. Establece billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod en true.
await CustomerSheet.initialize({ // ... defaultBillingDetails: { email: 'foo@bar.com', }, billingDetailsCollectionConfiguration: { name: PaymentSheet.CollectionMode.ALWAYS, email: PaymentSheet.CollectionMode.NEVER, address: PaymentSheet.AddressCollectionMode.FULL, attachDefaultsToPaymentMethod: true }, });

Nota

Consult with your legal counsel regarding laws that apply to collecting information. Only collect a phone number if you need it for a transaction.

¿Te ha sido útil la página?
SíNo
  • ¿Necesitas ayuda? Ponte en contacto con el equipo de soporte.
  • Echa un vistazo a nuestro registro de cambios.
  • ¿Tienes alguna pregunta? Ponte en contacto con el equipo de ventas.
  • ¿LLM? Lee llms.txt.
  • Con tecnología de Markdoc