Save SEPA Direct Debit details for future payments
Learn how to save payment method details for future SEPA Direct Debit payments.
You can use the Setup Intents API to collect payment method details in advance, and determine the final amount or payment date later. Use it to:
- Save payment methods to a wallet to streamline future purchases
- Collect surcharges after fulfilling a service
- Start a free trial for a subscription
Configurar StripeLado del servidorLado del cliente
Lado del servidor
Esta integración necesita puntos de conexión en tu servidor que se comuniquen con la API de Stripe. Usa nuestras bibliotecas oficiales para acceder a la API de Stripe desde tu servidor:
Lado del cliente
El SDK para React Native es de código abierto y está plenamente documentado. Internamente, utiliza SDK para iOS nativo y Android. Para instalar el SDK para React Native de Stripe, ejecuta uno de los siguientes comandos en el directorio del proyecto (según el administrador de paquetes que utilices):
A continuación, instala otras dependencias necesarias:
- Para iOS, vaya al directorio ios y ejecute
pod installpara asegurarse de que también instala las dependencias nativas necesarias. - Para Android, no hay más dependencias para instalar.
Nota
Recomendamos seguir la guía oficial de TypeScript para agregar soporte para 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 usando 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 el desarrollo, y tus claves para modo activo cuando publiques tu aplicación.
Crear o recuperar un objeto CustomerLado del servidor
Para reutilizar una cuenta de débito directo SEPA para pagos futuros, la cuenta debe estar asociada a un Customer.
You should create a Customer object when your customer creates an account with your business. Associating the ID of the Customer object with your own internal representation of a customer will enable you to retrieve and use the stored payment method details later. If your customer hasn’t created an account, you can still create a Customer object now and associate it with your internal representation of the customer’s account later.
Create a new Customer or retrieve an existing Customer to associate with these payment details. Include the following code on your server to create a new Customer.
Crear un SetupIntentLado del servidor
A SetupIntent is an object that represents your intent and tracks the steps to set up your customer’s payment method for future payments. For SEPA Direct Debit, this includes collecting a mandate from the customer and checking the validity of the IBAN.
Create a SetupIntent on your server with payment_method_types set to sepa_ and specify the Customer’s id.:
Recopilar los datos del método de pago y la confirmación del mandatoLado del cliente
Collect the customer’s IBAN in your payment form and display the following standard authorization text for your customer to implicitly sign the mandate.
Muestra el siguiente texto estándar de autorización al cliente para que implícitamente firme el mandato.
Reemplaza Rocket Rides con el nombre de tu empresa.
La configuración de un método de pago equivale a la aceptación del mandato. Puesto que el cliente ha firmado el mandato implícitamente al aceptar estas condiciones, debes comunicar estas últimas en tu formulario o por correo electrónico.
export default function SepaSetupFuturePaymentScreen() { const [email, setEmail] = useState(''); const [iban, setIban] = useState(''); return ( <Screen> <TextInput placeholder="E-mail" keyboardType="email-address" onChange={(value) => setEmail(value.nativeEvent.text)} style={styles.input} /> <TextInput placeholder="Iban" onChange={(value) => setIban(value.nativeEvent.text.toLowerCase())} style={styles.input} /> <Button variant="primary" onPress={handlePayPress} title="Save IBAN" loading={loading} /> </Screen> ); }
Enviar los datos del método de pago a StripeLado del cliente
Retrieve the client secret from the SetupIntent you created and call confirmSetupIntent.
The client secret should be handled carefully because it can complete the setup. Don’t log it, embed it in URLs, or expose it to anyone but the customer.
Nota
addressCountry and addressLine1 must be provided in the billingDetails for IBANs with the following country codes: AD, PF, TF, GI, GB, GG, VA, IM, JE, MC, NC, BL, PM, SM, CH, WF. See the React Native SDK reference for a list of address fields.
export default function SepaSetupFuturePaymentScreen() { const [iban, setIban] = useState(''); const {confirmSetupIntent, loading} = useConfirmSetupIntent(); const handlePayPress = async () => { const clientSecret = await createSetupIntentOnBackend(email); const billingDetails: PaymentMethodCreateParams.BillingDetails = { name: 'Jenny Rosen', email: 'jenny.rosen@example.com', }; const {error, setupIntent} = await confirmSetupIntent(clientSecret, { paymentMethodType: 'SepaDebit', paymentMethodData: { billingDetails, iban, } }); if (error) { Alert.alert(`Error code: ${error.code}`, error.message); console.log('Setup intent confirmation error', error.message); } else if (setupIntent) { Alert.alert( `Success: Setup intent created. Intent status: ${setupIntent.status}`, ); } }; return <Screen>{/* ... */}</Screen>; }
Probar la integración
You can test your form using the IBANs below with your confirmSepaDebitSetup request. The payment method details are successfully collected for each IBAN but exhibit different behavior when charged.
Prueba los IBAN
OpcionalCustomize mandate references with a prefix
You can customize SEPA Direct Debit mandate references to simplify mandate identification. To do this, provide the optional payment_ value. We add the reference_ to the beginning of a unique sequence to ensure the entire reference remains unique.
The reference_ must meet these requirements:
- Maximum length: 12 characters
- Must begin with a number or an uppercase letter
- Allowed characters:
- Uppercase letters
- Numbers
- Spaces
- Special characters:
.,/,&,-,_
- Can’t begin with
STRIPE
Include any desired delimiter in the prefix, as we don’t add one by default. We trim trailing spaces to a maximum of one space. With a valid prefix, the resulting reference is always 24 characters long.
The generated reference looks like EX4MPL3-19CNCI920C2M02O3.
| Error Code | Message |
|---|---|
invalid_ | The reference_ must be at most 12 characters long and can only contain uppercase letters, numbers, spaces, or the special characters /, _, -, &, and .. It can’t begin with STRIPE. |