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.

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):
A continuación, instala otras dependencias necesarias:
- Para iOS, navega hasta el directorio de ios y ejecuta
pod installpara 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 endpointsLado del servidor
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.
- Create an endpoint to return a Customer ID and a CustomerSession client secret.
Nota
Integrations with legacy customer ephemeral keys results in saved payment methods having an allow_ value of unspecified. To display these payment methods in addition to payment methods saved while using Customer Sessions, set payment_ to ["unspecified", "always"]. For more information, see CustomerSessions.
- Create an endpoint to return a SetupIntent configured with the 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..
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://', });
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. 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:
- Attach the values that aren’t collected by the Payment Method Settings Sheet to the
defaultBillingDetailsproperty. - Establece
billingDetailsCollectionConfiguration.enattachDefaultsToPaymentMethod 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.