Accept in-app payments
Build a customised payments integration in your iOS Android or React Native app using the Payment Element.
The Payment Element is a customisable 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.
Accounts v2 API support
The Payment Sheet doesn’t support customer-configured Accounts. It only supports Customer objects.
iOS
Android
React Native
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.
Set up Stripe Server-side Client-side
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:
Command Line
Select a language
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
# Available as a gem
sudo gem install stripe
Gemfile
Select a language
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
# If you use bundler, you can add this line to your Gemfile
gem 'stripe'
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. the relevant part of the product as the repository URL.
- 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.
You also need to set your publishable key so that the SDK can make API calls to Stripe. To get started, you can hard-code 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_GvF3BSyx8RSXMK5yAFhqEd3H"
Enable payment methods
View your payment methods settings and enable the payment methods you want to support. You need at least one payment method enabled to create a PaymentIntent.
By default, Stripe enables cards and other prevalent payment methods that can help you reach more customers, but we recommend turning on additional payment methods that are relevant for your business and customers. See Payment method support for product and payment method support, and our pricing page for fees.
Collect payment details Client-side
Place the Embedded Mobile Payment Element on the checkout page of your native mobile app. The element displays a list of payment methods and you can customise 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.
Initialise the Payment Element
Call create to instantiate EmbeddedPaymentElement with a EmbeddedPaymentElement.Configuration and a PaymentSheet.IntentConfiguration.
The Configuration object contains general-purpose configuration options for EmbeddedPaymentElement that don’t change between payments, like returnURL. The IntentConfiguration object contains details about the specific payment like the amount and currency, as well as a confirmationTokenConfirmHandler callback. For now, leave its implementation empty. After it successfully initialises, set its presentingViewController and delegate properties.
import StripePaymentSheet
class MyCheckoutVC: UIViewController {
func createEmbeddedPaymentElement() async throws -> EmbeddedPaymentElement {
let intentConfig = PaymentSheet.IntentConfiguration(
mode: .payment(amount: 1099, currency: "USD")
) { [weak self] confirmationToken in
return await self?.handleConfirmationToken(confirmationToken)
}
var configuration = EmbeddedPaymentElement.Configuration()
configuration.returnURL = "your-app://stripe-redirect" // Use the return url you set up in the previous step
let embeddedPaymentElement = try await EmbeddedPaymentElement.create(intentConfiguration: intentConfig, configuration: configuration)
embeddedPaymentElement.presentingViewController = self
embeddedPaymentElement.delegate = self
return embeddedPaymentElement
}
func handleConfirmationToken(_ confirmationToken: STPConfirmationToken) async throws -> String {
// You'll implement this in the "Confirm the payment" section below
}
}
Add the Payment Element view
After EmbeddedPaymentElement successfully initialises, put its view in your checkout UI.
Note
The view must be contained within a scrollable view such as UIScrollView because it doesn’t have a fixed size and can change height after it initially renders.
class MyCheckoutVC: UIViewController {
// ...
private(set) var embeddedPaymentElement: EmbeddedPaymentElement?
private lazy var checkoutButton: UIButton = {
let checkoutButton = UIButton(type: .system)
checkoutButton.backgroundColor = .systemBlue
checkoutButton.layer.cornerRadius = 5.0
checkoutButton.clipsToBounds = true
checkoutButton.setTitle("Checkout", for: .normal)
checkoutButton.setTitleColor(.white, for: .normal)
checkoutButton.translatesAutoresizingMaskIntoConstraints = false
checkoutButton.isEnabled = embeddedPaymentElement?.paymentOption != nil
checkoutButton.addTarget(self, action: #selector(didTapConfirmButton), for: .touchUpInside)
return checkoutButton
}()
// ...
@objc func didTapConfirmButton() {
// You'll implement this in the "Confirm the payment" section below
}
override func viewDidLoad() {
super.viewDidLoad()
Task { @MainActor in
do {
// Create a UIScrollView
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(scrollView)
// Create the Payment Element
let embeddedPaymentElement = try await createEmbeddedPaymentElement()
embeddedPaymentElement.delegate = self
embeddedPaymentElement.presentingViewController = self
self.embeddedPaymentElement = embeddedPaymentElement
// Add its view to the scroll view
scrollView.addSubview(embeddedPaymentElement.view)
// Add your own checkout button to the scroll view
scrollView.addSubview(checkoutButton)
// Set up layout constraints
embeddedPaymentElement.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
embeddedPaymentElement.view.topAnchor.constraint(equalTo: scrollView.topAnchor),
embeddedPaymentElement.view.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
embeddedPaymentElement.view.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
checkoutButton.topAnchor.constraint(equalTo: embeddedPaymentElement.view.bottomAnchor, constant: 4.0),
checkoutButton.leadingAnchor.constraint(equalTo: scrollView.safeAreaLayoutGuide.leadingAnchor, constant: 4.0),
checkoutButton.trailingAnchor.constraint(equalTo: scrollView.safeAreaLayoutGuide.trailingAnchor, constant: -4.0),
])
} catch {
// Handle view not being added to view
}
}
}
}
At this point you can run your app and see the Embedded Mobile Payment Element.
Handle height changes
The EmbeddedPaymentElement’s view might grow or shrink in size, which can impact the layout of the view.
Handle height changes by implementing the embeddedPaymentElementDidUpdateHeight delegate method. EmbeddedPaymentElement’s view calls this method inside an animation block that updates its height. Your implementation is expected to call setNeedsLayout() and layoutIfNeeded() on the scroll view that contains the EmbeddedPaymentElement’s view to enable a smooth animation of the height change.
extension MyCheckoutVC: EmbeddedPaymentElementDelegate {
func embeddedPaymentElementDidUpdateHeight(embeddedPaymentElement: StripePaymentSheet.EmbeddedPaymentElement) {
// Handle layout appropriately
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}
}
We recommend that you test that your view properly responds to changes in height. To do this, call testHeightChange() on EmbeddedPaymentElement to simulate showing and hiding a mandate within the element. Make sure that after calling testHeightChange(), your scroll view adjusts smoothly.
class MyCheckoutVC: UIViewController {
override func viewDidLoad() {
// This is only for testing purposes:
#if DEBUG
Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in
Task { @MainActor in
self?.embeddedPaymentElement?.testHeightChange()
}
}
#endif
}
}
Optional Display the selected payment option
If you need to access details about the customer’s selected payment option like a label (for example, “····4242”), image (for example, a the related setting logo), or billing details to display in your UI, use the EmbeddedPaymentElement’s paymentOption property.
To be notified when the paymentOption changes, implement the embeddedPaymentElementDidUpdatePaymentOption delegate method.
extension MyCheckoutVC: EmbeddedPaymentElementDelegate {
func embeddedPaymentElementDidUpdatePaymentOption(embeddedPaymentElement: EmbeddedPaymentElement) {
print("The payment option changed: \(embeddedPaymentElement.paymentOption)")
checkoutButton.isEnabled = embeddedPaymentElement.paymentOption != nil
}
}
Optional Update payment details
As the customer performs actions that change the payment details (for example, applying a discount code), update the EmbeddedPaymentElement instance to reflect the new values by calling the update method. Some payment methods, like Apple Pay and Google Pay, show the amount in the UI, so make sure it’s always accurate and up to date.
When the update call completes, update your UI. The update call might change the customer’s currently selected payment option.
extension MyCheckoutVC {
func update() {
Task { @MainActor in
var updatedIntentConfig = oldIntentConfig
// Update the amount to reflect the price after applying the discount code
updatedIntentConfig.mode = PaymentSheet.IntentConfiguration.Mode.payment(amount: 999, currency: "USD")
let result = await embeddedPaymentElement?.update(intentConfiguration: updatedIntentConfig)
switch result {
case .canceled, nil:
// Do nothing; this happens when a subsequent `update` call cancels this one
break
case .failed(let error):
// Display error to user in an alert, let users retry
case .succeeded:
// Update your UI in case the payment option changed
}
}
}
}
Confirm the payment
When the customer taps the checkout button, call embeddedPaymentElement.confirm() to complete the payment. Be sure to disable user interaction during confirmation.
extension MyCheckoutVC {
@objc func didTapConfirmButton() {
Task { @MainActor in
guard let embeddedPaymentElement else { return }
self.view.isUserInteractionEnabled = false // Disable user interaction, show a spinner, and so on before calling confirm.
let result = await embeddedPaymentElement.confirm()
switch result {
case .completed:
// Payment completed - show a confirmation screen.
case .failed(let error):
self.view.isUserInteractionEnabled = true
// Encountered an unrecoverable error. You can display the error to the user, log it, and so on.
case .canceled:
self.view.isUserInteractionEnabled = true
// Customer canceled - you should probably do nothing.
break
}
}
}
}
Next, implement the confirmationTokenConfirmHandler callback you passed to PaymentSheet.IntentConfiguration earlier to send a request to your server. Your server creates a PaymentIntent and returns its client secret. For information about this process, see Create a PaymentIntent.
When the request returns, return your server response’s client secret or throw an error. The EmbeddedPaymentElement confirms the PaymentIntent using the client secret or displays the localised error message in its UI (either errorDescription or localizedDescription). After confirmation completes, EmbeddedPaymentElement isn’t usable. Instead, direct the user to a receipt screen or something similar.
extension MyCheckoutVC {
func handleConfirmationToken(_ confirmationToken: STPConfirmationToken) async throws -> String {
// Make a request to your own server. Pass `confirmationToken.stripeId` if using server-side confirmation, and return the client secret or throw an error.
let myServerClientSecret = try await fetchIntentClientSecret(...)
}
}
Optional Clear the selected payment option
Optional Display the mandate yourself
Optional Let the customer pay immediately in the sheet
Create a PaymentIntent Server-side
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.
Set the same Customer or customer-configured Account on the PaymentIntent that you set on the CustomerSession.
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.
Note
Verify that all IntentConfiguration properties match your PaymentIntent (for example, setup_future_usage, amount, and currency).
main.rb
Select a language
Ruby
Python
PHP
Node.js
Java
Go
.NET
No results
require 'stripe'
# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices.
client = Stripe::StripeClient.new('sk_test_Ou1w6LVt3zmVipDVJsvMeQsc')
post '/create-intent' do
data = JSON.parse request.body.read
params = {
amount: 1099,
currency: 'usd',
automatic_payment_methods: {enabled: true},
}
begin
intent = client.v1.payment_intents.create(params)
{client_secret: intent.client_secret}.to_json
rescue Stripe::StripeError => e
{error: e.error.message}.to_json
end
end
Set up a return URL Client-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.
SceneDelegate.swift
Swift
// 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 EmbeddedPaymentElement.Configuration object to the URL for your app.
var configuration = EmbeddedPaymentElement.Configuration()
configuration.returnURL = "your-app://stripe-redirect"
Handle post-payment events Server-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_intent.succeeded 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_intent.succeeded or payment_intent.payment_failed 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_failed, offer the customer another attempt to pay. |
Test the integration
| Card number | Scenario | How to test |
|---|---|---|
| The card payment succeeds and doesn’t require authentication. | Fill in the credit card form using the credit card number with any expiry date, CVC, and postal code. | |
| The card payment requires authentication. | Fill in the credit card form using the credit card number with any expiry date, CVC, and postal code. | |
The card is declined with a decline code like insufficient_funds. | Fill in the credit card form using the credit card number with any expiry date, CVC, and postal code. | |
| The UnionPay card has a variable length of 13-19 digits. | Fill in the credit card form using the credit card number with any expiry date, CVC, and postal code. |
See Testing for additional information to test your integration.
Enable card scanning
To enable card scanning support for iOS, set the NSCameraUsageDescription ( Privacy - Camera Usage Description) in the Info.plist of your application, and provide a reason for accessing the camera (for example, “To scan cards”).