Accepter des paiements dans l'application
Build a customized payments integration in your iOS, Android, or React Native app using the Payment Element.
The Payment Element is a customizable component that renders a list of payment methods that you can add into any screen in your app. When customers interact with payment methods in the list, the component opens individual bottom sheets to collect payment details.
A PaymentIntent flow allows you to create a charge in your app. In this integration, you render the Payment Element, create a PaymentIntent, and confirm a charge in your app.
Configurer StripeCôté serveurCôté client
Côté serveur
Pour cette intégration, votre serveur doit disposer de points de terminaison qui communiquent avec l’API Stripe. Utilisez nos bibliothèques officielles pour accéder à l’API Stripe à partir de votre serveur :
Côté client
La trousse SDK iOS de Stripe est à code source libre et possède une documentation complète. Il est également compatible avec les applications prenant en charge iOS 13 et les versions ultérieures.
Remarque
Pour plus de détails sur la version la plus récente de la trousse SDK et ses versions antérieures, consultez la page des versions sur GitHub. Pour recevoir des notifications lors de la publication d’une nouvelle version, suivez les versions du référentiel.
You also need to set your publishable key so that the SDK can make API calls to Stripe. To get started, you can hardcode the publishable key on the client while you’re integrating, but fetch the publishable key from your server in production.
// Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys STPAPIClient.shared.publishableKey ="pk_test_TYooMQauvdEDq54NiTphI7jx"
Activer les moyens de paiement
Accédez aux paramètres des moyens de paiement et activez les moyens de paiement que vous souhaitez prendre en charge. Vous devez activer au moins un moyen de paiement pour créer un PaymentIntent.
Par défaut, Stripe active les cartes et les autres modes de paiement courants qui peuvent vous permettre d’atteindre davantage de clients. Nous vous recommandons toutefois d’activer d’autres modes de paiement pertinents pour votre entreprise et vos clients. Consultez la page Prise en charge des modes de paiement pour en savoir plus sur la prise en charge des produits et des modes de paiement, et notre page de tarification pour prendre connaissance des frais que nous appliquons.
Collecter les informations de paiementCôté client
The Embedded Mobile Payment Element is designed to be placed on the checkout page of your native mobile app. The element displays a list of payment methods and you can customize it to match your app’s look and feel.
When the customer taps the Card row, it opens a sheet where they can enter their payment method details. The button in the sheet says Continue by default and dismisses the sheet when tapped, which lets your customer finish payment in your checkout.
You can also configure the button to immediately complete payment instead of continuing. To do so, complete this step after following the guide.
FacultatifClear the selected payment option
If you have payment options external to EmbeddedPaymentElement, you might need to clear the selected payment option. To do this, use the clearPaymentOption API to deselect the selected payment option.
FacultatifDisplay the mandate yourself
By default, the Embedded Mobile Payment Element displays mandates and legal disclaimers to ensure regulatory compliance. This text must be located close to your buy button. If necessary, disable its display in the view and display it yourself instead.
Avertissement
Your integration must display the mandate text to be compliant. Make sure URLs in the text can be opened by using a UITextView or something similar.
FacultatifLet the customer pay immediately in the sheet
To configure the button in the form sheet to immediately confirm payment, set formSheetAction on your EmbeddedPaymentElement. object.
The completion block executes with the result of the payment after the sheet dismisses. The embedded UI isn’t usable after payment completes, so we recommend that your implementation directs the user to a different screen, such as a receipt screen.
var configuration = EmbeddedPaymentElement.Configuration() configuration.formSheetAction = .confirm(completion: { result in switch result { case .completed: // Payment completed. You can for example, show a confirmation screen. print("Completed") case .failed(let error): // Encountered an unrecoverable error. You can display the error to the user, log it, etc. print(error) case .canceled: // Customer canceled - you should probably do nothing. break } })
Créer un PaymentIntentCôté serveur
On your server, create a PaymentIntent with an amount and currency. You can manage payment methods from the Dashboard. Stripe handles the return of eligible payment methods based on factors such as the transaction’s amount, currency, and payment flow. To prevent malicious customers from choosing their own prices, always decide how much to charge on the server-side (a trusted environment) and not the client.
If the call succeeds, return the PaymentIntent client secret. If the call fails, handle the error and return an error message with a brief explanation for your customer.
Remarque
Verify that all IntentConfiguration properties match your PaymentIntent (for example, setup_, amount, and currency).
Configurer une URL de renvoiCôté client
The customer might navigate away from your app to authenticate (for example, in Safari or their banking app). To allow them to automatically return to your app after authenticating, configure a custom URL scheme and set up your app delegate to forward the URL to the SDK. Stripe doesn’t support universal links.
Additionally, set the returnURL on your EmbeddedPaymentElement.Configuration object to the URL for your app.
var configuration = EmbeddedPaymentElement.Configuration() configuration.returnURL = "your-app://stripe-redirect"
Gérer les événements post-paiementCôté serveur
Stripe envoie un événement payment_intent.succeeded à l’issue du paiement. Utilisez l’outil de webhook du Dashboard ou suivez le guide sur les webhooks pour recevoir ces événements et exécuter des actions, comme envoyer une confirmation de commande par courriel à votre client, enregistrer la vente dans une base de données ou lancer un flux de livraison.
Écoutez ces événements plutôt que d’attendre un rappel de votre client. Du côté client, il arrive en effet que l’utilisateur ferme la fenêtre de son navigateur ou quitte l’application avant même l’exécution du rappel, et des clients malveillants pourraient manipuler la réponse. En configurant votre intégration de manière à ce qu’elle écoute les événements asynchrones, vous pourrez accepter plusieurs types de moyens de paiement avec une seule intégration.
En plus de gérer l’événement payment_, nous vous recommandons de gérer les autres événements suivants lorsque vous encaissez des paiements à l’aide du Payment Element :
| Événement | Description | Action |
|---|---|---|
| payment_intent.succeeded | Envoyé lorsqu’un client a effectué un paiement. | Envoyez au client une confirmation de commande et traitez sa commande. |
| payment_intent.processing | Envoyé lorsqu’un client a entrepris un paiement, mais qu’il ne l’a pas encore finalisé. Dans la plupart des cas, cet événement est envoyé lorsque le client entreprend un prélèvement bancaire. Il est suivi par un événement payment_ ou payment_. | Envoyez au client une confirmation de commande qui indique que son paiement est en attente. Pour des marchandises dématérialisées, nous vous recommandons de traiter la commande sans attendre que le paiement soit effectué. |
| payment_intent.payment_failed | Envoyé lorsqu’un client tente d’effectuer un paiement, mais que le paiement échoue. | Si un paiement passe de l’état processing à l’état payment_, proposez au client de retenter le paiement. |
Tester l'intégration
Consultez la section Test pour obtenir des informations supplémentaires sur la manière de tester votre intégration.
FacultatifEnable saved cardsCôté serveurCôté client
EmbeddedPaymentElement can display a Save this card for future use checkbox that saves the customer’s card, and display the customer’s saved cards. To enable this checkbox, create a Customer object on your server and an associated CustomerSession, with payment_ set to enabled.
Comparer les références Customers v1 et Accounts v2
Si votre plateforme Connect utilise des comptes configurés par le client, utilisez notre guide pour remplacer le Client et des références d’événements dans votre code avec les références équivalentes de l’API Accounts v2.
const stripe = require('stripe')('sk_test_your_secret_key'); app.post('/mobile-payment-element', async (req, res) => { // Use an existing Customer ID if this is a returning customer. const customer = await stripe.customers.create(); const customerSession = await stripe.customerSessions.create({ customer: customer.id, components: { mobile_payment_element: { enabled: true, features: { payment_method_save: 'enabled', payment_method_redisplay: 'enabled', payment_method_remove: 'enabled' } }, }, }); res.json({ customerSessionClientSecret: customerSession.client_secret, customer: customer.id, }); });
Next, configure EmbeddedPaymentElement with the Customer’s ID and the CustomerSession client secret.
FacultatifAllow delayed payment methodsCôté client
Delayed payment methods don’t guarantee that you’ll receive funds from your customer at the end of the checkout either because they take time to settle (for example, US Bank Accounts, SEPA Debit, iDEAL, and Bancontact) or because they require customer action to complete (for example, OXXO, Konbini, and Boleto).
By default, EmbeddedPaymentElement doesn’t display delayed payment methods. To opt in, set allowsDelayedPaymentMethods to true in your EmbeddedPaymentElement.. This step alone doesn’t activate any specific payment methods; rather, it indicates that your app is able to handle them. For example, although OXXO is currently not supported by EmbeddedPaymentElement, if it becomes supported and you’ve updated to the latest SDK version, your app will be able to display OXXO as a payment option without additional integration changes.
If the customer successfully uses one of these delayed payment methods in EmbeddedPaymentElement, the payment result returned is ..
FacultatifActiver Apple Pay
Remarque
If your checkout screen has a dedicated Apple Pay button, follow the Apple Pay guide and use ApplePayContext to collect payment from your Apple Pay button. You can use EmbeddedPaymentElement to handle other payment method types.
Demander un ID de marchand Apple
Pour obtenir un ID de marchand Apple, demandez un nouvel identifiant sur le site Web Apple Developer.
Renseignez le formulaire en indiquant une description et un identifiant. La description n’est destinée qu’à votre propre information et vous pourrez la modifier ultérieurement au besoin. En ce qui concerne l’identifiant, Stripe vous recommande d’utiliser le nom de votre application (par exemple, merchant.).
Créer un nouveau certificat Apple Pay
Créez un certificat permettant à votre application de chiffrer les données de paiement.
Accédez aux paramètres des certificats iOS dans le Dashboard, cliquez sur Ajouter une nouvelle application et suivez le guide.
Téléchargez un fichier de demande de signature de certificat (CSR) pour obtenir un certificat sécurisé auprès d’Apple qui vous permet d’utiliser Apple Pay.
Un fichier CSR doit être utilisé pour émettre exactement un certificat. Si vous changez votre identifiant Apple Merchant ID, vous devez accéder aux paramètres de certificat iOS du Dashboard pour obtenir un nouveau CSR et un nouveau certificat.
Réaliser une intégration avec Xcode
Ajoutez la fonctionnalité Apple Pay à votre application. Dans Xcode, ouvrez les paramètres de votre projet, cliquez sur l’onglet Signing & Capabilities (Signature et fonctionnalités), et ajoutez la fonctionnalité Apple Pay. On pourrait alors vous demander de vous connecter à votre compte de développeur. Sélectionnez l’ID du marchand que vous venez de créer, et votre application peut maintenant accepter Apple Pay.

Activer la fonctionnalité Apple Pay dans Xcode
Ajouter Apple Pay
Suivi des commandes
To add order tracking information in iOS 16 or later, configure an authorizationResultHandler in your PaymentSheet.. Stripe calls your implementation after the payment is complete, but before iOS dismisses the Apple Pay sheet.
In your authorizationResultHandler implementation, fetch the order details from your server for the completed order. Add the details to the provided PKPaymentAuthorizationResult and return the modified result.
Pour en savoir plus sur le suivi des commandes, consultez la documentation sur les commandes du portefeuille numérique Apple.
let customHandlers = PaymentSheet.ApplePayConfiguration.Handlers( authorizationResultHandler: { result in do { // Fetch the order details from your service let myOrderDetails = try await MyAPIClient.shared.fetchOrderDetails(orderID: orderID) result.orderDetails = PKPaymentOrderDetails( orderTypeIdentifier: myOrderDetails.orderTypeIdentifier, // "com.myapp.order" orderIdentifier: myOrderDetails.orderIdentifier, // "ABC123-AAAA-1111" webServiceURL: myOrderDetails.webServiceURL, // "https://my-backend.example.com/apple-order-tracking-backend" authenticationToken: myOrderDetails.authenticationToken) // "abc123" // Return your modified PKPaymentAuthorizationResult return result } catch { return PKPaymentAuthorizationResult(status: .failure, errors: [error]) } } ) var configuration = EmbeddedPaymentElement.Configuration() configuration.applePay = .init(merchantId: "merchant.com.your_app_name", merchantCountryCode: "US", customHandlers: customHandlers)
FacultatifCustomize the element
All customization is configured through the EmbeddedPaymentElement.Configuration object.
Aspect
Customize colors, fonts, and so on to match the look and feel of your app by using the appearance API.
Collecter les adresses des utilisateurs
Collect local and international shipping or billing addresses from your customers using the Address Element.
Nom d’affichage du marchand
Specify a customer-facing business name by setting merchantDisplayName. By default, this is your app’s name.
var configuration = EmbeddedPaymentElement.Configuration() configuration.merchantDisplayName = "My app, Inc."
Dark mode
EmbeddedPaymentElement automatically adapts to the user’s system-wide appearance settings (light and dark mode). If your app doesn’t support dark mode, you can set style to alwaysLight or alwaysDark mode.
var configuration = EmbeddedPaymentElement.Configuration() configuration.style = .alwaysLight
FacultatifEnable CVC recollection on confirmation
Pour collecter à nouveau le CVC d’une carte enregistrée lors de la confirmation de la PaymentIntent, votre intégration doit collecter les informations sur le paiement avant de créer une PaymentIntent.
Mettre à jour la configuration de l’Intent
PaymentSheet. accepte un paramètre facultatif qui contrôle le moment de collecter à nouveau le CVC pour une carte enregistrée.
let intentConfig = PaymentSheet.IntentConfiguration( mode: .payment(amount: 1099, currency: "USD"), confirmHandler: { confirmationToken in // Handle ConfirmationToken... }, requireCVCRecollection: true)
Mettre à jour les paramètres de création de l’Intent
Pour collecter à nouveau le CVC lors de la confirmation du paiement, ajoutez les paramètres customerId et require_ lors de la création du PaymentIntent.