# Migrate from Payment Intents to Checkout Sessions

Move an in-app Payment Intents integration to Mobile Checkout Elements.

### Want access to Mobile Checkout Elements?

Mobile Checkout Elements is in private preview. Share your email address to request access.

```bash
curl https://docs.stripe.com/preview/register \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Referer: https://docs.stripe.com/payments/mobile/checkout-sessions/migrate-from-payment-intents" \
  -d '{"email": "EMAIL", "preview": "elements_beta_preview"}'
```

# iOS


Mobile Checkout Elements manages your entire checkout flow, including line items, [tax](https://docs.stripe.com/payments/mobile/checkout-sessions/collect-taxes.md), shipping, and [Adaptive Pricing](https://docs.stripe.com/payments/mobile/checkout-sessions/adaptive-pricing.md).

## Compare Checkout Sessions and Payment Intents 

| Capability             | Mobile Checkout Elements                                                                         | Payment Intents with the Mobile Payment Element                                    |
| ---------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |
| State model            | The full checkout, including the order and payment                                               | A single payment or payment method setup                                           |
| Amounts and line items | Stripe models line items and provides a totals summary                                           | Your integration calculates and stores the amount and order details                |
| Automatic tax          | Built-in Stripe Tax calculation                                                                  | Requires a separate Tax API integration and transaction recording                  |
| Adaptive Pricing       | Built in for eligible Sessions                                                                   | Not supported                                                                      |
| Shipping               | Collects shipping addresses and automatically updates tax                                        | Your integration models shipping and updates the PaymentIntent amount              |
| Checkout updates       | Elements and your app update one shared session                                                  | Your app collects shipping, determines taxes, and updates the PaymentIntent amount |
| Purchase types         | One-time payments. Setting up future payments and subscriptions not supported in private preview | One-time payments and setting up future payments                                   |

## Enable payment methods

> This integration path doesn’t support pre-authorized debits that use the Automated Clearing Settlement System (ACSS). Also, if you create the deferred intent from the client-side, you can’t use `customer_balance` with dynamic payment methods because the PaymentIntent requires a customer-configured [Account](https://docs.stripe.com/api/v2/core/accounts/object.md#v2_account_object-configuration-customer) or [Customer](https://docs.stripe.com/api/customers/object.md) object, which the client-side flow doesn’t support. To use `customer_balance`, create the `PaymentIntent` server-side with an `Account` or `Customer` and return its `client_secret` to the client.

View your [payment methods settings](https://dashboard.stripe.com/settings/payment_methods) and enable the payment methods you want to support. You need at least one payment method enabled to create a *Checkout Session* (A Checkout Session represents your customer's session as they pay for one-time purchases or subscriptions through Checkout. After a successful payment, the Checkout Session contains a reference to the Customer, and either the successful PaymentIntent or an active Subscription).

By default, Stripe enables cards and other common 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](https://docs.stripe.com/payments/payment-methods/payment-method-support.md) for product and payment method support, and our [pricing page](https://stripe.com/pricing/local-payment-methods) for fees.

## Migrate your PaymentIntent creation call [Server-side]

Upgrade your SDK to use the latest API version.

#### Ruby

```bash
# Available as a gem
sudo gem install stripe
```

```ruby
# If you use bundler, you can add this line to your Gemfile
gem 'stripe'
```

Update your PaymentIntent creation call to [create a Checkout Session](https://docs.stripe.com/api/checkout/sessions/create.md) instead. In the Checkout Session, pass:

- [items](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-items): Represents what’s in the order.
- [ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode): Set to `mobile_elements` to indicate that you’re using Mobile Checkout Elements.
- [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email): Provides an email you already have on file. If you need to collect or edit an email, follow [Provide the customer email](https://docs.stripe.com/payments/mobile/checkout-sessions/migrate-from-payment-intents.md#collect-email) instead.
- `shipping_address_collection.allowed_countries`: Limits the countries available for shipping addresses. Set this when your app collects a shipping address.

Return the Checkout Session’s [client_secret](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-client_secret) to your app to initialize Mobile Checkout Elements.

Each Checkout Session generates a `PaymentIntent` upon confirmation. To retain supported payment-level parameters from your current integration, pass them in [payment_intent_data](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data). To use `payment_intent_data`, you must set `mode` to `payment` and pass [line_items](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items) instead of `items`.

### Before

```javascript
const paymentIntent = await stripe.paymentIntents.create({
  amount: 1099,
  currency: 'usd',
  payment_method_types: ['card'],
});

res.json({clientSecret: paymentIntent.client_secret});
```

### After

```javascript
const session = await stripe.checkout.sessions.create({
  ui_mode: 'mobile_elements',
  customer_email: 'jenny.rosen@example.com',
  shipping_address_collection: {
    allowed_countries: ['US', 'CA'],
  },
  items: [
    {
      type: 'one_time_price',
      one_time_price: {
        items: [
          {
            price_data: {
              currency: 'usd',
              unit_amount: 1099,
              product_data: {
                name: 'T-shirt',
              },
            },
            quantity: 1,
          },
        ],
      },
    },
  ],
});

res.json({clientSecret: session.client_secret});
```

Don’t set `mode` when you use `items`. Keep the existing Payment Intents flow for options that the private preview doesn’t support.

## Optional: Additional Checkout Session options [Server-side]

[Checkout Sessions](https://docs.stripe.com/api/checkout/sessions.md) accept additional options that influence payment collection.

| Property                                                                                                                                   | Type                                  | Description                                                                                                                                                                                                                                                             | Required                                                                                                                                                                 |
| ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [items](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-items)                                             | `array of objects`                    | A list of items the customer is purchasing. The private preview supports `one_time_price` only.                                                                                                                                                                         | Yes                                                                                                                                                                      |
| [ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode)                                         | `mobile_elements`                     | Indicates that the Session uses Mobile Checkout Elements.                                                                                                                                                                                                               | Yes                                                                                                                                                                      |
| [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email)                           | `string`                              | Provides an email you already have on file. You can instead pass a `Customer` with an email or collect an email in your app. See [Provide the customer email](https://docs.stripe.com/payments/mobile/checkout-sessions/migrate-from-payment-intents.md#collect-email). | No, if you use another approach in [Provide the customer email](https://docs.stripe.com/payments/mobile/checkout-sessions/migrate-from-payment-intents.md#collect-email) |
| [automatic_tax](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-automatic_tax)                             | `{enabled: boolean}`                  | Enables Stripe Tax to calculate tax and collect the billing address information required for the calculation.                                                                                                                                                           | No                                                                                                                                                                       |
| [allow_promotion_codes](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-allow_promotion_codes)             | `boolean`                             | Enables customer-redeemable promotion codes.                                                                                                                                                                                                                            | No                                                                                                                                                                       |
| [billing_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-billing_address_collection)   | `auto`, `required`                    | Controls whether Checkout collects the customer’s billing address. The default is `auto`.                                                                                                                                                                               | No                                                                                                                                                                       |
| [payment_method_types](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_method_types)               | `array of enums`                      | Limits the payment methods this Checkout Session can accept. This isn’t required when you use [dynamic payment methods](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md).                                                                   | No                                                                                                                                                                       |
| [shipping_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection) | `{allowed_countries: array of enums}` | Configures Checkout to collect a shipping address from the customer.                                                                                                                                                                                                    | No                                                                                                                                                                       |

Render the controller’s Session values in your app. Don’t calculate separate discounts, tax, shipping, or totals for the same order.

## Replace client initialization [Client-side]

Replace PaymentSheet, FlowController, or Embedded Payment Element initialization with `CheckoutElementsController`. The controller provides Mobile Checkout Elements and is the single interface for reading and writing Checkout Session data from your app.

Replace your standard PaymentSheet import with the Checkout Session private-preview import:

```swift
@_spi(CheckoutSessionPreview) import StripePaymentSheet
```

#### UIKit

### Before

```swift
var configuration = PaymentSheet.Configuration()
configuration.returnURL = "my-app://stripe-redirect"

let paymentSheet = PaymentSheet(
    paymentIntentClientSecret: paymentIntentClientSecret,
    configuration: configuration
)
```

### After

```swift
@MainActor
final class CheckoutViewController: UIViewController {
    let checkout: CheckoutElementsController

    static func create(
        clientSecret: String
    ) async throws -> CheckoutViewController {
        var configuration = CheckoutElementsController.Configuration(
            clientSecret: clientSecret,
            returnURL: "my-app://stripe-redirect"
        )
        configuration.paymentElement = PaymentElement.Configuration()

        let checkout = try await CheckoutElementsController(configuration: configuration)
        return CheckoutViewController(checkout: checkout)
    }
}
```

When calling `create`, catch errors and display `error.localizedDescription` using the [controller initialization pattern](https://docs.stripe.com/payments/mobile/checkout-sessions/build-a-checkout-page.md?platform=ios#configure-checkout).

#### SwiftUI

### Before

```swift
let paymentSheet = PaymentSheet(
    paymentIntentClientSecret: paymentIntentClientSecret,
    configuration: configuration
)
```

### After

```swift
struct CheckoutContainer: View {
    let clientSecret: String

    @State private var checkout: CheckoutElementsController?
    @State private var loadError: Error?

    var body: some View {
        Group {
            if let checkout {
                CheckoutView(checkout: checkout)
            } else if let loadError {
                Text(loadError.localizedDescription)
            } else {
                ProgressView()
            }
        }
        .task {
            do {
                var configuration = CheckoutElementsController.Configuration(
                    clientSecret: clientSecret,
                    returnURL: "my-app://stripe-redirect"
                )
                configuration.paymentElement = PaymentElement.Configuration()
                checkout = try await CheckoutElementsController(configuration: configuration)
            } catch {
                loadError = error
            }
        }
    }
}
```

## Provide the customer email [Server-side] [Client-side]

A Checkout Session requires a valid customer email before confirmation. Stripe uses this email for fraud prevention, to recognize returning Link customers, and to send receipts if you enable them. This checkout email is separate from a payment method’s billing email.

Choose the approach that matches your app:

### If you already have an email

If you always have an email on file and don’t need customers to edit it during checkout, set [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email) when you create the Checkout Session, or pass [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) with a `Customer` that has an email. You don’t need an email field in your checkout UI.

An email provided through `customer_email` or `Customer.email` is immutable in the client SDK. Don’t set `defaults.email` or call `updateEmail` for that Session. Attempting to override a server-provided email returns an error.

### If you need to collect or edit an email

If you don’t always have an email, collect it with your own UI. Use this approach if you already have an email but want customers to be able to edit it during checkout.

Don’t set `customer_email` or pass a `Customer` that already has an email. If you have an initial email, set it in the Checkout configuration defaults before initialization:

```swift
configuration.defaults.email = customerEmail
```

Populate your email field with that value, and call `updateEmail` when the customer enters or changes their email. Handle validation errors and provide a valid email before confirming the Session. Omitting the email results in a confirmation error.

## Replace the payment UI [Client-side]

Fetch and display the Payment Element from the `CheckoutElementsController`. You can display it inline or present it as a sheet.

#### UIKit

To embed the Element, add its `uiView` to a scrollable container and respond to height changes.

```swift
func addPaymentElement() {
    let paymentElementView = checkout.getPaymentElement().uiView
    paymentElementView.delegate = self
    paymentElementView.translatesAutoresizingMaskIntoConstraints = false
    contentStackView.addArrangedSubview(paymentElementView)
}

@objc func didSelectPaymentMethod() {
    Task {
        await checkout.getPaymentElement().present(from: self)
    }
}
```

```swift
extension CheckoutViewController: PaymentElementViewDelegate {
    func paymentElementViewDidUpdateHeight(
        paymentElementView: PaymentElementUIView
    ) {
        paymentElementView.invalidateIntrinsicContentSize()
        view.layoutIfNeeded()
    }
}
```

#### SwiftUI

```swift
struct CheckoutView: View {
    @ObservedObject var checkout: CheckoutElementsController

    var body: some View {
        ScrollView {
            VStack {
                checkout.getPaymentElement().view

                Button("Select payment method") {
                    Task {
                        await checkout.getPaymentElement().present()
                    }
                }
            }
        }
    }
}
```

## Replace payment confirmation [Client-side]

Replace your PaymentSheet or PaymentIntent confirmation flow with Checkout confirmation. Keep the **Pay** button disabled while the controller is updating or if no payment option is selected. If you set [shipping_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection), keep the button disabled until `session.shippingAddress` has a non-null value.

#### UIKit

```swift
// Match whether your server sets shipping_address_collection.
private let collectsShippingAddress = true

func updatePayButton() {
    let hasRequiredShippingAddress =
        !collectsShippingAddress || checkout.session.shippingAddress != nil

    payButton.isEnabled =
        !checkout.isUpdating
        && checkout.session.paymentOption != nil
        && hasRequiredShippingAddress
}

@objc func didSelectPay() {
    payButton.isEnabled = false

    Task {
        let result = await checkout.confirm(from: self)
        handleCheckoutResult(result)
        updatePayButton()
    }
}

func handleCheckoutResult(_ result: CheckoutElementsController.ConfirmResult) {
    switch result {
    case .completed(let paymentStatus):
        showOrderConfirmation(paymentStatus: paymentStatus)
    case .canceled:
        restoreCheckout()
    case .failed(let error):
        showError(error.localizedDescription)
    }
}
```

#### SwiftUI

```swift
// Match whether your server sets shipping_address_collection.
let collectsShippingAddress = true

Button("Pay") {
    Task {
        let result = await checkout.confirm()
        handleCheckoutResult(result)
    }
}
.disabled(
    checkout.isUpdating
        || checkout.session.paymentOption == nil
        || (collectsShippingAddress && checkout.session.shippingAddress == nil)
)

func handleCheckoutResult(_ result: CheckoutElementsController.ConfirmResult) {
    switch result {
    case .completed(let paymentStatus):
        showOrderConfirmation(paymentStatus: paymentStatus)
    case .canceled:
        restoreCheckout()
    case .failed(let error):
        showError(error.localizedDescription)
    }
}
```

## Handle errors 

Display `error.localizedDescription` to the customer whenever initialization, a Session update, or payment confirmation fails. For express payments, display the error from the `.failed` result in the Express Checkout Element’s completion handler.

In the examples, `showError` represents your app’s UI for displaying the message, such as an alert or inline text.

## Handle post-payment events [Server-side]

Stripe sends a [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) event when the customer completes checkout. Use the [Dashboard webhook tool](https://dashboard.stripe.com/webhooks) or follow the [webhook guide](https://docs.stripe.com/webhooks/quickstart.md) to receive this event and perform actions such as sending an order confirmation email, recording the sale, or starting a shipping workflow.

Listen for these events instead of waiting for a callback from the client. The customer could quit the app before the callback executes, and malicious clients could manipulate the response. Listening for asynchronous events also lets you support delayed payment methods.

Handle these events when collecting payments with Mobile Checkout Elements:

| Event                                                                                                                                        | Description                                                                                                                                                  | Action                                                                                                                                                                                                                                                                                                                                                                                                  |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed)                             | Stripe sends this event when a customer completes checkout. For delayed payment methods, the Checkout Session can still have a `payment_status` of `unpaid`. | If [payment_status](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-payment_status) is `paid`, send the customer an order confirmation and *fulfill* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected) the order. Otherwise, wait for the `checkout.session.async_payment_succeeded` event. |
| [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) | Sent when a delayed payment method succeeds.                                                                                                                 | Send the customer an order confirmation and *fulfill* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected) the order.                                                                                                                                                                                                          |
| [checkout.session.async_payment_failed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_failed)       | Sent when a delayed payment method fails.                                                                                                                    | Ask the customer to try another payment method.                                                                                                                                                                                                                                                                                                                                                         |
| [checkout.session.expired](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.expired)                                 | Sent when the Checkout Session expires.                                                                                                                      | Create a Checkout Session when the customer attempts checkout again.                                                                                                                                                                                                                                                                                                                                    |

Make the handler idempotent, and use the Checkout Session ID as the order reference. Check the Checkout Session’s payment status before you deliver goods or services.

Verify webhook signatures to confirm that events came from Stripe. See [verify webhook signatures](https://docs.stripe.com/events/manage-webhook-endpoints.md#signature-errors).

