Save payment details during an in-app payment
Save payment details during a payment in your mobile app.
Accounts v2 API support
The Payment Sheet doesn’t support customer-configured Accounts. It only supports Customer objects.
Use the Payment Intents API to save payment details from a purchase. There are several use cases:
- Charge a customer for an e-commerce order and store the details for future purchases.
- Initiate the first payment of a series of recurring payments.
- Charge a deposit and store the details to charge the full amount later.
Card-present transactions
Card-present transactions, such as payments through Stripe Terminal, use a different process for saving the payment method. For details, see the Terminal documentation.
Compliance
You’re responsible for your compliance with all applicable laws, regulations, and network rules when saving a customer’s payment details for future use, such as displaying a customer’s payment method to them in the checkout flow for a future purchase or charging them when they’re not actively using your website or app. Before saving or charging a customer’s payment method, make sure you:
- Add terms to your website or app that state how you plan to save payment method details, such as:
- The customer’s agreement allowing you to initiate a payment or a series of payments on their behalf for specified transactions.
- The anticipated timing and frequency of payments (for example, if the charges are for scheduled installments, subscription payments, or unscheduled top-ups).
- How you determine the payment amount.
- Your cancellation policy, if the payment method is for a subscription service.
- Use a saved payment method for only the purpose stated in your terms.
- Collect explicit consent from the customer for this specific use. For example, include a "Save my payment method for future checkbox.
- Keep a record of your customer’s written agreement to your terms.
Set up StripeServer-sideClient-side
First, you need a Stripe account. Register now.
Server-side
This integration requires endpoints on your server that talk to the Stripe API. Use our official libraries for access to the Stripe API from your server:
Client-side
The Stripe iOS SDK is open source, fully documented, and compatible with apps supporting iOS 13 or above.
To install the SDK, follow these steps:
- In Xcode, select File > Add Package Dependencies… and enter
https://github.as the repository URL.com/stripe/stripe-ios-spm - Select the latest version number from our releases page.
- Add the StripePaymentSheet product to the target of your app.
Note
For details on the latest SDK release and past versions, see the Releases page on GitHub. To receive notifications when a new release is published, watch releases for the repository.
Enable payment methods
Card payments are enabled by default. View your payment methods settings to enable more payment methods you want to support.
Add an endpointServer-side
Note
To display the PaymentSheet before you create a PaymentIntent, see Collect payment details before creating an Intent.
This integration uses three Stripe API objects:
PaymentIntent: Stripe uses this to represent your intent to collect payment from a customer, tracking your charge attempts and payment state changes throughout the process.
A customer-configured Account or a Customer object: To set up a payment method for future payments, you must attach it to a customer. Create an object to represent your customer when they create an account with your business. If your customer makes a payment as a guest, you can create an
AccountorCustomerobject before payment and associate it with your own internal representation of the customer’s account later.CustomerSession: Information on the object that represents your customer is sensitive, and can’t be retrieved directly from an app. A
CustomerSessiongrants the SDK temporary scoped access to theAccountorCustomerand provides additional configuration options. See a complete list of configuration options.
For security reasons, your app can’t create these objects. Instead, add an endpoint on your server that:
- Retrieves the
AccountorCustomer, or creates a new one. - Creates a CustomerSession for the
AccountorCustomer. - Creates a
PaymentIntentwith the amount, currency, setup_future_usage, and either the customer_account or the customer. - Returns the
PaymentIntent’s client secret, theCustomerSession’sclient_, the ID of thesecret AccountorCustomer, and your publishable key to your app.
Set the same Account or Customer on the PaymentIntent that you set on the CustomerSession.
Note
The mobile Payment Element only supports setup_ with cards and US bank accounts.
The payment methods shown to customers during the checkout process are also included on the PaymentIntent. You can let Stripe pull payment methods from your Dashboard settings or you can list them manually. Regardless of the option you choose, know that the currency passed in the PaymentIntent filters the payment methods shown to the customer. For example, if you pass eur on the PaymentIntent and have OXXO enabled in the Dashboard, OXXO won’t be shown to the customer because OXXO doesn’t support eur payments.
Unless your integration requires a code-based option for offering payment methods, Stripe recommends the automated option. This is because Stripe evaluates the currency, payment method restrictions, and other parameters to determine the list of supported payment methods. Payment methods that increase conversion and that are most relevant to the currency and customer’s location are prioritized.
You can manage payment methods from the Dashboard. Stripe creates the PaymentIntent using eligible payment methods you’ve configured, based on factors such as the transaction’s amount, currency, and payment flow. If you don’t want to use the Dashboard, or if you want to specify the allowed payment methods manually, you can use the allowed_ parameter.
# Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u sk_test_BQokikJOvBiI2HlWgH4olfQ2: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u sk_test_BQokikJOvBiI2HlWgH4olfQ2: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u sk_test_BQokikJOvBiI2HlWgH4olfQ2: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ -d "setup_future_usage"="off_session" \ -d "automatic_payment_methods[enabled]"=true \
Collect payment detailsClient-side
To display the mobile Payment Element on your checkout screen:
- Display the products the customer is purchasing along with the total amount
- Use the Address Element to collect any required shipping information from the customer
- Add a checkout button to display Stripe’s UI
In your app’s checkout screen, fetch the PaymentIntent client secret, CustomerSession client secret, customer-configured Account ID, and publishable key from the endpoint you created in the previous step. Use STPAPIClient. to set your publishable key and initialize the PaymentSheet.
import UIKit @_spi(CustomerSessionBetaAccess) import StripePaymentSheet class CheckoutViewController: UIViewController { @IBOutlet weak var checkoutButton: UIButton! var paymentSheet: PaymentSheet? let backendCheckoutUrl = URL(string: "Your back-end endpoint/payment-sheet")! // Your back-end endpoint override func viewDidLoad() { super.viewDidLoad() checkoutButton.addTarget(self, action: #selector(didTapCheckoutButton), for: .touchUpInside) checkoutButton.isEnabled = false // MARK: Fetch the PaymentIntent client secret, CustomerSession client secret, customer-configured Account ID, and publishable key var request = URLRequest(url: backendCheckoutUrl) request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let customerAccountId = json["customerAccount"] as? String, let customerSessionClientSecret = json["customerSessionClientSecret"] as? String, let paymentIntentClientSecret = json["paymentIntent"] as? String, let publishableKey = json["publishableKey"] as? String, let self = self else { // Handle error return } STPAPIClient.shared.publishableKey = publishableKey // MARK: Create a PaymentSheet instance var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "Example, Inc." configuration.customerAccount = .init(id: customerAccountId, customerSessionClientSecret: customerSessionClientSecret) // Set `allowsDelayedPaymentMethods` to true if your business handles // delayed notification payment methods like US bank accounts. configuration.allowsDelayedPaymentMethods = true self.paymentSheet = PaymentSheet(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) DispatchQueue.main.async { self.checkoutButton.isEnabled = true } }) task.resume() } }
When the customer taps the Checkout button, call present to present the PaymentSheet. After the customer completes the payment, Stripe dismisses the PaymentSheet and calls the completion block with PaymentSheetResult.
@objc func didTapCheckoutButton() { // MARK: Start the checkout process paymentSheet?.present(from: self) { paymentResult in // MARK: Handle the payment result switch paymentResult { case .completed: print("Your order is confirmed") case .canceled: print("Canceled!") case .failed(let error): print("Payment failed: \(error)") } } }
If PaymentSheetResult is ., inform the customer (for example, by displaying an order confirmation screen).
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.
Set up a return URLClient-side
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.
// This method handles opening custom URL schemes (for example, "your-app://stripe-redirect") func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { guard let url = URLContexts.first?.url else { return } let stripeHandled = StripeAPI.handleURLCallback(with: url) if (!stripeHandled) { // This was not a Stripe url – handle the URL normally as you would } }
Additionally, set the returnURL on your PaymentSheet.Configuration object to the URL for your app.
var configuration = PaymentSheet.Configuration() configuration.returnURL = "your-app://stripe-redirect"
Handle post-payment eventsServer-side
Stripe sends a payment_intent.succeeded event when the payment completes. Use the Dashboard webhook tool or follow the webhook guide to receive these events and run actions, such as sending an order confirmation email to your customer, logging the sale in a database, or starting a shipping workflow.
Listen for these events rather than waiting on a callback from the client. On the client, the customer could close the browser window or quit the app before the callback executes, and malicious clients could manipulate the response. Setting up your integration to listen for asynchronous events is what enables you to accept different types of payment methods with a single integration.
In addition to handling the payment_ event, we recommend handling these other events when collecting payments with the Payment Element:
| Event | Description | Action |
|---|---|---|
| payment_intent.succeeded | Sent when a customer successfully completes a payment. | Send the customer an order confirmation and fulfill their order. |
| payment_intent.processing | Sent when a customer successfully initiates a payment, but the payment has yet to complete. This event is most commonly sent when the customer initiates a bank debit. It’s followed by either a payment_ or payment_ event in the future. | Send the customer an order confirmation that indicates their payment is pending. For digital goods, you might want to fulfill the order before waiting for payment to complete. |
| payment_intent.payment_failed | Sent when a customer attempts a payment, but the payment fails. | If a payment transitions from processing to payment_, offer the customer another attempt to pay. |
Charge the saved Payment Method laterServer-side
To find a payment method to charge, list the payment methods associated with your customer. This example lists cards, but you can list any supported type.
Use the Accounts v2 API to represent customers
The Accounts v2 API is generally available for Connect users, and in public preview for other Stripe users. If you’re part of the Accounts v2 preview, you need to specify a preview version in your code.
To join the Accounts v2 preview, go to Account previews and features in your Dashboard and enable Reusable payment methods for Global Payouts.
For most use cases, we recommend modeling your customers as customer-configured Account objects instead of using Customer objects.
When you’re ready to charge your customer off-session, use the ID of the Customer or customer-configured Account and the PaymentMethod ID to create a PaymentIntent with the amount and currency of the payment. Set a few other parameters to make the off-session payment:
- Set off_session to true to indicate that the customer isn’t in your checkout flow to respond to any authentication requests. If, during your checkout flow, a partner (such as a card issuer or bank) requests authentication, Stripe requests exemptions using customer information from a previous on-session transaction. If the conditions for exemption aren’t met, the
PaymentIntentmight throw an error. - Set confirm to true to trigger confirmation immediately when the
PaymentIntentis created. - Set payment_method to the
PaymentMethod’s ID. - Depending on how you represent customers in your integration, set either customer_account to the ID of the customer-configured
Accountor customer to the ID of theCustomer.
curl https://api.stripe.com/v1/payment_intents \ -u "sk_test_BQokikJOvBiI2HlWgH4olfQ2:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]=true" \ -d "customer_account=" \ -d payment_method={{PAYMENT_METHOD_ID}} \ --data-urlencode "return_url=https://example.com/order/123/complete" \ -d off_session=true \ -d confirm=true{{CUSTOMER_ACCOUNT_ID}}
Test the integration
| Payment method | Scenario | How to test |
|---|---|---|
| Credit card | The card setup 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 card | The card requires authentication for the initial setup, then succeeds for subsequent payments. | Fill out the credit card form using the credit card number 4000 0025 0000 3155 with any expiration, CVC, and postal code. |
| Credit card | The card requires authentication for the initial setup and also requires authentication for subsequent payments. | Fill out the credit card form using the credit card number 4000 0027 6000 3184 with any expiration, CVC, and postal code. |
| Credit card | The card is declined during setup. | Fill out the credit card form using the credit card number 4000 0000 0000 9995 with any expiration, CVC, and postal code. |
Enable card scanning
To enable card scanning support for iOS, set the NSCameraUsageDescription (Privacy - Camera Usage Description) in the Info. of your application, and provide a reason for accessing the camera (for example, “To scan cards”).