---
title: "Chấp nhận thanh toán Stripe trong các flow iOS"
description: "Hiển thị giá Stripe trong một flow, thực hiện thanh toán với PaymentSheet của Stripe trong ứng dụng iOS của bạn, và để Adapty cấp quyền truy cập cũng như gán doanh thu cho flow."
---

> **AI agents**: to search Adapty docs faster and with fewer tokens, install the Adapty skills: `npx adapty skills install --yes`

Bạn có thể bán gói đăng ký Stripe từ một flow được xây dựng trong Flow & Paywall Builder. Flow sẽ hiển thị các mức giá Stripe của bạn, và các nút trong flow sẽ mở PaymentSheet của Stripe lên trên flow. Sau khi thanh toán, Stripe sẽ thông báo cho Adapty. Adapty cấp mức độ truy cập cho người dùng và gán doanh thu cho flow, placement và biến thể A/B test tương ứng. Hãy dùng cách thiết lập này để bán gói đăng ký cho các dịch vụ mà người dùng sử dụng bên ngoài ứng dụng, chẳng hạn như thành viên sự kiện trực tiếp, thẻ tham gia lớp học, hoặc dịch vụ giao hàng định kỳ. Nếu bạn cũng bán một gói dịch vụ thực tế dưới dạng sản phẩm App Store, bạn có thể thêm Stripe vào cùng flow đó như một phương thức thanh toán khác.

:::important
App Store yêu cầu in-app purchase cho nội dung kỹ thuật số và các tính năng ([hướng dẫn 3.1.1](https://developer.apple.com/app-store/review/guidelines/#in-app-purchase)). Thanh toán trong ứng dụng qua Stripe dành cho hàng hóa vật lý và các dịch vụ mà người dùng sử dụng bên ngoài ứng dụng ([hướng dẫn 3.1.3(e)](https://developer.apple.com/app-store/review/guidelines/#other-purchase-methods)). Để chuyển người dùng đến trang thanh toán web cho nội dung kỹ thuật số, hãy sử dụng [web paywall](ios-web-paywall).
:::

## Cách thức hoạt động \{#how-it-works\}

1. Ứng dụng của bạn lấy giá Stripe từ backend, sau đó truyền chúng vào flow dưới dạng [custom tags](ios-flow-custom-tags) và hiển thị flow.
2. Người dùng nhấn vào một nút trong flow. Nút đó kích hoạt một custom action, và ứng dụng của bạn nhận được action ID.
3. Ứng dụng của bạn yêu cầu backend tạo một gói đăng ký Stripe. Backend thêm ID người dùng và variation ID của flow vào metadata của gói đăng ký.
4. Ứng dụng của bạn mở PaymentSheet lên trên flow, và người dùng thanh toán hóa đơn đầu tiên của gói đăng ký.
5. Stripe gửi webhook đến Adapty. Adapty cấp mức độ truy cập cho hồ sơ người dùng có ID tương ứng và gán lượt mua cho biến thể flow.
6. Ứng dụng của bạn đóng flow và chờ đến khi hồ sơ người dùng có mức độ truy cập.

## Trước khi bắt đầu \{#before-you-start\}

Hãy đảm bảo rằng bạn đã:

1. **Stripe được kết nối với ứng dụng Adapty của bạn**: Làm theo hướng dẫn [Kết nối Stripe với Adapty](stripe#1-connect-stripe-to-adapty), cho cả chế độ test và chế độ live. Giữ nguyên [**Profile creation behavior**](stripe#profile-creation-behavior) ở chế độ **Use customer_user_id from metadata (default)**.
2. **Một sản phẩm và giá Stripe cho mỗi gói**: [Tạo sản phẩm trên Stripe](stripe#2-create-products-on-stripe) với các mức giá định kỳ, ví dụ hàng tháng hoặc hàng năm.
3. **Một sản phẩm Adapty cho mỗi mức giá Stripe**: [Thêm ID sản phẩm và ID giá Stripe vào sản phẩm Adapty](stripe#3-add-stripe-products-to-adapty), và gán mức độ truy cập mà gói đó mở khóa. Mức độ truy cập đại diện cho quyền sử dụng dịch vụ, ví dụ như tư cách thành viên đang hoạt động, chứ không phải các tính năng kỹ thuật số trong ứng dụng. Nếu không có sản phẩm Adapty, Adapty sẽ không ghi nhận giao dịch mua.
4. **Adapty iOS SDK 4.0.0 trở lên**: Khởi tạo SDK bằng key của ứng dụng Adapty mà bạn đã kết nối với Stripe. Adapty chỉ nhận webhook từ Stripe cho ứng dụng đó. [Xác định người dùng](identifying-users) bằng customer user ID, và chỉ hiển thị flow này cho những người dùng đã đăng nhập và được xác định. Adapty sử dụng ID này để tìm hồ sơ người dùng nhận mức độ truy cập.
5. **Stripe iOS SDK** với module `StripePaymentSheet` trong ứng dụng của bạn. Xem [Accept a payment](https://docs.stripe.com/payments/accept-a-payment?platform=ios) trong tài liệu Stripe.
6. **Một backend có thể gọi Stripe API** bằng [secret key](https://docs.stripe.com/keys) Stripe của bạn, hoặc bằng một restricted key tự tạo có quyền ghi Customers và Subscriptions. Đừng tái sử dụng restricted key mà bạn đã tạo cho Adapty: đó là key của Adapty, và nó không có quyền ghi mà backend của bạn cần. Hãy giữ key đó trên server của bạn.

## Hiển thị giá Stripe trong flow \{#show-stripe-prices-in-the-flow\}

Flow hiển thị giá Stripe thông qua các thẻ tùy chỉnh. Thẻ tùy chỉnh là một giá trị văn bản mà ứng dụng của bạn truyền vào flow khi tải flow đó. Adapty không định dạng giá trị thẻ tùy chỉnh, vì vậy hãy truyền mỗi mức giá theo đúng dạng người dùng sẽ thấy, chẳng hạn như "$29.00".

1. Trong Flow & Paywall Builder, [tạo một biến **String**](flow-custom-tags#create-a-custom-tag) cho mỗi mức giá, ví dụ `stripe_monthly_price` và `stripe_annual_price`, rồi chọn **Value comes from outside the app**. Đặt **Initial value** của mỗi biến bằng mức giá hiện tại của bạn. Người dùng sẽ thấy giá trị ban đầu này nếu ứng dụng không tải được giá, vì vậy hãy đặt giá trị ban đầu trùng với giá Stripe của bạn.
2. [Chèn từng tag vào một phần tử văn bản](flow-custom-tags#add-a-custom-tag-to-a-text-element), chẳng hạn như nhãn của nút chọn gói.
3. Trong ứng dụng, lấy giá từ backend của bạn trước khi tải flow.
4. Truyền giá vào tham số `tagResolver` của `getFlowConfiguration`.

Hàm sau đây tải flow với các mức giá Stripe của bạn. Hàm này cũng trả về `variationId` của flow, vì backend của bạn sẽ ghi ID này vào gói đăng ký Stripe. Bạn hiển thị flow trong [Mở PaymentSheet từ flow](#open-paymentsheet-from-the-flow).

```swift showLineNumbers title="Swift"
struct StripeFlow {
    let configuration: AdaptyUI.FlowConfiguration
    let variationId: String
}

@MainActor
func loadStripeFlow() async throws -> StripeFlow {
    // If the prices fail to load, the flow shows the tags' initial values
    let prices = (try? await Backend.fetchPrices()) ?? [:]

    let flow = try await Adapty.getFlow(placementId: "YOUR_PLACEMENT_ID")
    let configuration = try await AdaptyUI.getFlowConfiguration(
        forFlow: flow,
        tagResolver: [
            "stripe_monthly_price": prices["monthly"],
            "stripe_annual_price": prices["annual"],
        ].compactMapValues { $0 }
    )
    return StripeFlow(configuration: configuration, variationId: flow.variationId)
}
```

`Backend` là client dành cho các endpoint của backend bạn, từ phần [Tạo gói đăng ký trên backend của bạn](#create-the-subscription-on-your-backend).

Các kiểu presentation của Adapty yêu cầu iOS 16. Nếu ứng dụng của bạn hỗ trợ các phiên bản cũ hơn, hãy thêm `@available(iOS 16.0, *)` vào đoạn code trong hướng dẫn này có sử dụng chúng.

## Thêm các nút để mở PaymentSheet \{#add-buttons-that-open-paymentsheet\}

Mỗi nút bán một gói Stripe sẽ kích hoạt một custom action. Ứng dụng của bạn nhận ID action và mở PaymentSheet cho gói đó.

1. Trong Flow & Paywall Builder, [thêm một nút](paywall-buttons) cho mỗi gói Stripe.
2. Gán action **Custom Action** cho mỗi nút và nhập ID action, chẳng hạn như `buy_stripe_monthly` và `buy_stripe_annual`.
3. Xuất bản flow và [thêm nó vào một placement](create-placement).

Ứng dụng của bạn ánh xạ mỗi action ID tới một gói. Flow không gửi dữ liệu nào kèm theo hành động, vì vậy action ID phải xác định gói đó.

### Thêm Stripe như một phương thức thanh toán khác cho sản phẩm App Store \{#add-stripe-as-another-way-to-pay-for-app-store-products\}

Chỉ sử dụng thiết lập này cho các gói liên quan đến hàng hóa vật lý hoặc dịch vụ mà người dùng sử dụng bên ngoài ứng dụng ([hướng dẫn 3.1.3(e)](https://developer.apple.com/app-store/review/guidelines/#other-purchase-methods)), chẳng hạn như thẻ thành viên cho các sự kiện trực tiếp. Đối với nội dung kỹ thuật số hoặc các tính năng trong ứng dụng, hãy cung cấp phương thức thanh toán khác thông qua [web paywall](ios-web-paywall).

Flow hiển thị các sản phẩm App Store của bạn như bình thường, và một liên kết như "Pay another way" sẽ mở PaymentSheet. Các nút mua hàng qua App Store vẫn hoạt động bình thường mà không cần thay đổi gì.

1. Gán hành động **Custom Action** cho liên kết, với action ID ví dụ như `pay_with_stripe`.
2. Với mỗi sản phẩm App Store trong flow, tạo một Stripe price cho cùng gói đó.
3. Trong ứng dụng của bạn, ánh xạ từng App Store product ID sang Stripe plan tương ứng.
4. Lưu lại sản phẩm mà người dùng chọn. Flow sẽ báo cáo mỗi lần chọn tới `flowController(_:didSelectProduct:)` trong UIKit, hoặc tới closure `didSelectProduct` của modifier `.flow` trong SwiftUI. Một flow được xây dựng trong Flow & Paywall Builder mặc định không báo cáo sản phẩm được chọn, vì vậy hãy bắt đầu với sản phẩm mà bạn đã đặt là được chọn trong builder. Nếu các biến thể của một A/B test chọn các sản phẩm khác nhau, hãy lưu sản phẩm mặc định cho mỗi biến thể.
5. Khi ứng dụng nhận được `pay_with_stripe`, gọi `StripeCheckout.pay(plan:variationId:over:)` từ [Mở PaymentSheet từ flow](#open-paymentsheet-from-the-flow) với Stripe plan của sản phẩm đã lưu.

Flow hiển thị giá App Store của các sản phẩm này, và giá có thể khác nhau tùy theo storefront. PaymentSheet tính phí theo giá Stripe. Để hiển thị giá Stripe cho người dùng trước khi họ nhấn, hãy [truyền giá đó dưới dạng custom tag](#show-stripe-prices-in-the-flow) và hiển thị trong card của từng gói, ví dụ "hoặc $29.00/tháng qua thẻ". Giá trị custom tag không thay đổi trong khi flow đang mở, vì vậy một link không thể hiển thị giá của gói đang được chọn.

## Tạo gói đăng ký trên backend của bạn \{#create-the-subscription-on-your-backend\}

PaymentSheet thanh toán cho một đối tượng Stripe mà backend của bạn tạo ra. Trong hướng dẫn này, backend của bạn tạo một [gói đăng ký](https://docs.stripe.com/billing/subscriptions/overview) Stripe, và PaymentSheet thanh toán hóa đơn đầu tiên của gói đăng ký đó. Backend của bạn đặt hai khóa trong [metadata](https://docs.stripe.com/metadata) của gói đăng ký:

- `customer_user_id`: ID người dùng trong Adapty. Adapty cấp mức độ truy cập cho hồ sơ người dùng có ID này.
- `variation_id`: ID biến thể của flow, được app gửi lên backend. Adapty gán doanh thu cho biến thể flow này, placement và A/B test của nó.

:::warning
Adapty không ghi nhận thanh toán cho PaymentIntent mà bạn tạo độc lập, không gắn với gói đăng ký hay hóa đơn nào. Người dùng đã thanh toán nhưng sẽ không nhận được mức độ truy cập.
:::

Tạo hai endpoint. Endpoint đầu tiên trả về giá đã được định dạng cho các custom tag. Endpoint thứ hai tạo gói đăng ký và trả về các giá trị mà PaymentSheet cần. Trước khi tạo gói đăng ký, endpoint thứ hai kiểm tra xem người dùng có gói đăng ký đang hoạt động hay không, để tránh trường hợp người dùng thanh toán hai lần cho cùng một gói.

Ví dụ này sử dụng Node.js với ES modules (`"type": "module"` trong `package.json`), Express, và thư viện [`stripe`](https://github.com/stripe/stripe-node) phiên bản 18 trở lên. Thay `db` bằng cơ sở dữ liệu của bạn:

```javascript showLineNumbers title="Node.js"

const app = express();
app.use(express.json());

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

const prices = {
  monthly: 'price_...', // your Stripe price IDs
  annual: 'price_...',
};

// Prices for the custom tags, such as { "monthly": "$29.00", "annual": "$249.00" }.
// You can cache the response.
app.get('/prices', async (req, res) => {
  try {
    const result = {};
    for (const [plan, priceId] of Object.entries(prices)) {
      const price = await stripe.prices.retrieve(priceId);
      // Assumes a currency with two decimal places. Format for your users' locale.
      result[plan] = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: price.currency.toUpperCase(),
      }).format(price.unit_amount / 100);
    }
    res.json(result);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Could not load prices' });
  }
});

app.post('/subscriptions', async (req, res) => {
  // req.user comes from your authentication middleware. Its ID is the same
  // customer user ID that your app passes to Adapty.identify().
  const customerUserId = req.user.id;
  // variationId affects only attribution, so the backend doesn't need to trust it
  const { plan, variationId } = req.body;
  if (!prices[plan]) {
    return res.status(400).json({ error: 'Unknown plan' });
  }

  try {
    // One Stripe customer per user, stored in your database
    let customerId = await db.getStripeCustomerId(customerUserId);
    if (!customerId) {
      const customer = await stripe.customers.create({ metadata: { customer_user_id: customerUserId } });
      customerId = customer.id;
      await db.saveStripeCustomerId(customerUserId, customerId);
    }

    // Don't sell a second subscription to a user who already has one
    for (const status of ['active', 'trialing', 'past_due']) {
      const existing = await stripe.subscriptions.list({ customer: customerId, status, limit: 1 });
      if (existing.data.length > 0) {
        return res.status(409).json({ error: 'You already have a subscription' });
      }
    }

    const subscription = await stripe.subscriptions.create({
      customer: customerId,
      items: [{ price: prices[plan] }],
      payment_behavior: 'default_incomplete',
      payment_settings: { save_default_payment_method: 'on_subscription' },
      metadata: {
        customer_user_id: customerUserId,
        variation_id: variationId,
      },
      expand: ['latest_invoice.confirmation_secret'],
    });

    res.json({
      subscriptionId: subscription.id,
      clientSecret: subscription.latest_invoice.confirmation_secret.client_secret,
      publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Could not create the subscription' });
  }
});

app.listen(process.env.PORT ?? 3000);
```

Với `payment_behavior: 'default_incomplete'`, gói đăng ký sẽ chờ thanh toán lần đầu. Stripe kích hoạt nó khi người dùng thanh toán trong PaymentSheet. Nếu người dùng đóng PaymentSheet mà chưa thanh toán, Stripe sẽ hủy gói đăng ký sau khoảng 23 giờ và Adapty sẽ không ghi lại giao dịch đó. Để biết cách thiết lập Stripe đầy đủ, xem [Build a subscriptions integration](https://docs.stripe.com/billing/subscriptions/build-subscriptions?platform=ios) trong tài liệu Stripe.

Đoạn code đọc client secret từ `latest_invoice.confirmation_secret`, yêu cầu Stripe API phiên bản `2025-03-31.basil` trở lên. Thư viện `stripe` sử dụng phiên bản này từ version 18. Nếu bạn gọi Stripe API mà không dùng thư viện, hãy đặt header `Stripe-Version`. Với phiên bản API cũ hơn, hãy expand `latest_invoice.payment_intent` và đọc `payment_intent.client_secret` thay thế.

Trong ứng dụng của bạn, hãy gọi hai endpoint này. Gửi thông tin xác thực của người dùng kèm theo mỗi request, theo yêu cầu của backend:

```swift showLineNumbers title="Swift"
enum Backend {
    static let baseURL = URL(string: "https://YOUR_BACKEND")!

    struct Subscription: Decodable {
        let subscriptionId: String
        let clientSecret: String
        let publishableKey: String
    }

    struct BackendError: LocalizedError, Decodable {
        let error: String
        var errorDescription: String? { error }
    }

    struct HTTPError: LocalizedError {
        let statusCode: Int
        var errorDescription: String? { "The server returned HTTP \(statusCode)." }
    }

    static func fetchPrices() async throws -> [String: String] {
        let request = URLRequest(url: baseURL.appendingPathComponent("prices"))
        return try await send(request)
    }

    static func createSubscription(plan: String, variationId: String) async throws -> Subscription {
        var request = URLRequest(url: baseURL.appendingPathComponent("subscriptions"))
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        // add your authentication header
        request.httpBody = try JSONEncoder().encode([
            "plan": plan,
            "variationId": variationId,
        ])
        return try await send(request)
    }

    private static func send<T: Decodable>(_ request: URLRequest) async throws -> T {
        let (data, response) = try await URLSession.shared.data(for: request)
        let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0
        guard statusCode == 200 else {
            // Use the backend's message when the response has one
            throw (try? JSONDecoder().decode(BackendError.self, from: data)) ?? HTTPError(statusCode: statusCode)
        }
        return try JSONDecoder().decode(T.self, from: data)
    }
}
```

## Mở PaymentSheet từ flow \{#open-paymentsheet-from-the-flow\}

Ứng dụng của bạn mở PaymentSheet khi một nút trong flow kích hoạt một hành động tùy chỉnh, và đóng flow khi thanh toán thành công:

1. Ánh xạ ID hành động tùy chỉnh vào một gói. Bỏ qua các lần chạm và nút đóng của flow trong khi ứng dụng chờ backend hoặc hiển thị PaymentSheet. Như vậy, một lần chạm sẽ chỉ tạo ra một gói đăng ký.
2. Yêu cầu backend tạo gói đăng ký và truyền vào gói cùng với `variationId` của flow.
3. Hiển thị PaymentSheet phủ lên flow và xử lý kết quả:
   - **Completed**: Đóng flow. Sau khi flow đóng, [chờ mức độ truy cập được kích hoạt](#unlock-access-after-the-payment).
   - **Canceled**: Không làm gì. Người dùng ở lại flow và có thể chọn gói khác.
   - **Failed**: Hiển thị lỗi. Người dùng ở lại flow và có thể thử lại.
4. Xử lý các hành động đóng flow và mở URL. Handler hành động của bạn thay thế handler mặc định của SDK, vốn đóng flow và mở URL.
5. Triển khai các handler mua hàng và khôi phục, và trong SwiftUI là handler lỗi. SDK yêu cầu chúng ngay cả khi flow không có sản phẩm App Store nào.

Các bước 2 và 3 giống nhau trong UIKit và SwiftUI, vì vậy hướng dẫn này gộp chúng vào một lớp:

```swift showLineNumbers title="Swift"

@MainActor
final class StripeCheckout {
    // Custom action IDs from the flow, mapped to your backend's plan keys
    static let plans = [
        "buy_stripe_monthly": "monthly",
        "buy_stripe_annual": "annual",
    ]

    private(set) var isPaying = false

    /// Opens PaymentSheet for a plan over the flow. Returns `true` when the user paid.
    func pay(plan: String, variationId: String, over presenter: UIViewController) async -> Bool {
        guard !isPaying else { return false }
        isPaying = true
        defer { isPaying = false }

        do {
            let subscription = try await Backend.createSubscription(
                plan: plan,
                variationId: variationId
            )
            // The flow may have closed, or opened a link, while the backend responded
            guard presenter.viewIfLoaded?.window != nil, presenter.presentedViewController == nil else {
                return false
            }

            STPAPIClient.shared.publishableKey = subscription.publishableKey
            var configuration = PaymentSheet.Configuration()
            configuration.merchantDisplayName = "YOUR_BUSINESS_NAME"
            // For payment methods that redirect to another app, such as bank apps
            configuration.returnURL = "your-app://stripe-redirect"

            let paymentSheet = PaymentSheet(
                paymentIntentClientSecret: subscription.clientSecret,
                configuration: configuration
            )
            let result = await withCheckedContinuation { continuation in
                paymentSheet.present(from: presenter) { continuation.resume(returning: $0) }
            }

            switch result {
            case .completed:
                return true
            case .canceled:
                return false // the user stays on the flow
            case let .failed(error):
                showError(error, over: presenter)
                return false
            }
        } catch {
            showError(error, over: presenter)
            return false
        }
    }

    /// Opens a URL from the flow in the browser that the flow's button specifies.
    func open(_ url: URL, presentation: AdaptyWebPresentation, over presenter: UIViewController) {
        let isWebURL = url.scheme == "https" || url.scheme == "http"
        if presentation == .inAppBrowser, isWebURL {
            presenter.present(SFSafariViewController(url: url), animated: true)
        } else {
            UIApplication.shared.open(url)
        }
    }

    private func showError(_ error: Error, over presenter: UIViewController) {
        let alert = UIAlertController(
            title: "The payment didn't go through",
            message: error.localizedDescription,
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        presenter.present(alert, animated: true)
    }
}
```

PaymentSheet trả về ứng dụng của bạn thông qua return URL sau khi các phương thức thanh toán mở một ứng dụng khác. Đăng ký URL scheme trong ứng dụng của bạn, như được mô tả trong [Set up a return URL](https://docs.stripe.com/payments/accept-a-payment?platform=ios#ios-set-up-return-url) trong tài liệu Stripe, và truyền URL cho Stripe khi ứng dụng của bạn mở nó:

<Tabs groupId="ios-ui-framework">
<TabItem value="uikit" label="UIKit" default>

```swift showLineNumbers title="Swift"

// In your scene delegate
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let url = URLContexts.first?.url else { return }
    _ = StripeAPI.handleURLCallback(with: url)
}
```

</TabItem>
<TabItem value="swiftui" label="SwiftUI">

```swift showLineNumbers title="Swift"

// On your root view
.onOpenURL { url in
    _ = StripeAPI.handleURLCallback(with: url)
}
```

</TabItem>
</Tabs>

Sau đó trình bày flow và truyền các hành động của nó vào `StripeCheckout`:

<Tabs groupId="ios-ui-framework">
<TabItem value="uikit" label="UIKit" default>

Triển khai `AdaptyFlowControllerDelegate` của flow. Trình bày PaymentSheet từ flow controller, để sheet mở ra phía trên flow:

```swift showLineNumbers title="Swift"

final class StripeFlowDelegate: NSObject, AdaptyFlowControllerDelegate {
    private let variationId: String
    private let onPaid: () -> Void
    private let checkout = StripeCheckout()

    init(variationId: String, onPaid: @escaping () -> Void) {
        self.variationId = variationId
        self.onPaid = onPaid
    }

    func flowController(_ controller: AdaptyFlowController, didPerform action: AdaptyUI.Action) {
        switch action {
        case .close:
            guard !checkout.isPaying else { return }
            controller.dismiss(animated: true)
        case let .openURL(url, presentation):
            checkout.open(url, presentation: presentation, over: controller)
        // Adapty SDK 4.0–4.3: case let .custom(id):
        case let .custom(id, _):
            guard let plan = StripeCheckout.plans[id] else { return }
            Task {
                guard await checkout.pay(plan: plan, variationId: variationId, over: controller) else { return }
                controller.dismiss(animated: true) { [onPaid] in onPaid() }
            }
        }
    }

    // The SDK requires these methods. This flow sells only through Stripe.
    func flowController(
        _ controller: AdaptyFlowController,
        didFinishPurchase product: AdaptyPaywallProduct,
        purchaseResult: AdaptyPurchaseResult
    ) {}

    func flowController(
        _ controller: AdaptyFlowController,
        didFailPurchase product: AdaptyPaywallProduct,
        error: AdaptyError
    ) {}

    func flowController(_ controller: AdaptyFlowController, didFinishRestoreWith profile: AdaptyProfile) {}

    func flowController(_ controller: AdaptyFlowController, didFailRestoreWith error: AdaptyError) {}
}
```

Trong view controller của bạn, hãy tải flow và hiển thị nó. Giữ delegate trong một thuộc tính: flow controller giữ delegate của nó một cách yếu (weakly).

```swift showLineNumbers title="Swift"
final class MembershipViewController: UIViewController {
    private var flowDelegate: StripeFlowDelegate?
    private var isLoadingFlow = false

    func showStripeFlow() async {
        guard !isLoadingFlow else { return }
        isLoadingFlow = true
        defer { isLoadingFlow = false }

        do {
            let stripeFlow = try await loadStripeFlow()
            let flowDelegate = StripeFlowDelegate(variationId: stripeFlow.variationId) { [weak self] in
                Task { await self?.unlockAfterPayment() }
            }
            let flowController = try AdaptyUI.flowController(
                with: stripeFlow.configuration,
                delegate: flowDelegate
            )
            self.flowDelegate = flowDelegate
            present(flowController, animated: true)
        } catch {
            // handle the error
        }
    }

    func unlockAfterPayment() async {
        if await waitForAccess() {
            // unlock the service
        } else {
            // tell the user that the payment is processing, and how to reach your support
        }
    }
}
```

</TabItem>
<TabItem value="swiftui" label="SwiftUI">

Hiển thị flow bằng [modifier `.flow`](ios-present-paywalls#present-flows-and-paywalls-in-swiftui), và xử lý các hành động của nó trong closure `didPerformAction`. Modifier này hiển thị flow phủ lên view của bạn, vì vậy hãy hiển thị PaymentSheet từ view controller được present ở trên cùng, tức là flow:

```swift showLineNumbers title="Swift"

struct MembershipView: View {
    @State private var stripeFlow: StripeFlow?
    @State private var isFlowPresented = false
    @State private var isLoadingFlow = false
    @State private var didPay = false
    @State private var checkout = StripeCheckout()

    var body: some View {
        Button("Become a member") {
            Task { await showStripeFlow() }
        }
        .flow(
            isPresented: $isFlowPresented,
            flowConfiguration: stripeFlow?.configuration,
            didDisappear: {
                // Unlock after the flow has closed
                guard didPay else { return }
                didPay = false
                Task { await unlockAfterPayment() }
            },
            didPerformAction: { action in
                switch action {
                case .close:
                    guard !checkout.isPaying else { return }
                    isFlowPresented = false
                case let .openURL(url, presentation):
                    guard let presenter = UIApplication.shared.topViewController else { return }
                    checkout.open(url, presentation: presentation, over: presenter)
                // Adapty SDK 4.0–4.3: case let .custom(id):
                case let .custom(id, _):
                    guard let plan = StripeCheckout.plans[id],
                          let variationId = stripeFlow?.variationId,
                          let presenter = UIApplication.shared.topViewController
                    else { return }
                    Task {
                        guard await checkout.pay(plan: plan, variationId: variationId, over: presenter) else { return }
                        didPay = true
                        isFlowPresented = false
                    }
                }
            },
            // The SDK requires these closures. This flow sells only through Stripe.
            didFinishPurchase: { _, _ in },
            didFailPurchase: { _, _ in },
            didFinishRestore: { _ in },
            didFailRestore: { _ in },
            didReceiveError: { error in
                // The flow keeps working after these errors. Log them, and keep PaymentSheet open.
                print("Flow error: \(error)")
            }
        )
    }

    func showStripeFlow() async {
        guard !isLoadingFlow else { return }
        isLoadingFlow = true
        defer { isLoadingFlow = false }

        do {
            stripeFlow = try await loadStripeFlow()
            isFlowPresented = true
        } catch {
            // handle the error
        }
    }

    func unlockAfterPayment() async {
        if await waitForAccess() {
            // unlock the service
        } else {
            // tell the user that the payment is processing, and how to reach your support
        }
    }
}

extension UIApplication {
    /// The view controller at the top of the active window's presentation stack.
    var topViewController: UIViewController? {
        let scene = connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .first { $0.activationState == .foregroundActive }
        var top = scene?.keyWindow?.rootViewController
        while let presented = top?.presentedViewController {
            top = presented
        }
        return top
    }
}
```

</TabItem>
</Tabs>

Nếu flow của bạn cũng bán các sản phẩm App Store, hãy xử lý việc mua hàng trong các purchase handler như mô tả trong [Xử lý sự kiện flow](ios-handling-events).

## Mở khóa quyền truy cập sau khi thanh toán \{#unlock-access-after-the-payment\}

Sau khi thanh toán, Adapty nhận webhook từ Stripe và cấp mức độ truy cập trong vài giây. SDK làm mới hồ sơ người dùng mỗi phút một lần, vì vậy hãy liên tục truy vấn hồ sơ người dùng cho đến khi mức độ truy cập được kích hoạt:

```swift showLineNumbers title="Swift"
@MainActor
func waitForAccess() async -> Bool {
    for _ in 1...20 {
        if let profile = try? await Adapty.getProfile(),
           profile.accessLevels["YOUR_ACCESS_LEVEL"]?.isActive == true {
            return true
        }
        try? await Task.sleep(for: .seconds(3))
    }
    return false
}
```

Thông thường, mức độ truy cập sẽ được kích hoạt trong vài giây. Nếu sau 60 giây vẫn chưa được kích hoạt, hãy kiểm tra các deliveries của Adapty webhook endpoint trong [cài đặt webhook của Stripe](https://dashboard.stripe.com/webhooks).

Để hiển thị xác nhận sau khi thanh toán, chẳng hạn như màn hình chào mừng, hãy hiển thị nó từ ứng dụng của bạn khi mức độ truy cập đã được kích hoạt. Bạn cũng có thể xây dựng màn hình đó dưới dạng một flow thứ hai, thêm vào một placement riêng và hiển thị nó sau khi flow đầu tiên đóng lại. [Phản hồi kết quả mua hàng](respond-to-purchase-outcomes) hướng dẫn cách thiết lập một flow thứ hai cho trường hợp này.

## Để người dùng quản lý gói đăng ký \{#let-users-manage-the-subscription\}

Gói đăng ký Stripe không xuất hiện trong danh sách gói đăng ký của người dùng trên iOS Settings. Để người dùng có thể hủy hoặc thay đổi phương thức thanh toán, hãy thêm một nút vào ứng dụng (ví dụ: trên màn hình tài khoản) để mở [Stripe customer portal](https://docs.stripe.com/customer-management). Backend của bạn sẽ tạo một phiên portal cho Stripe customer của người dùng và trả về URL của phiên đó.

Khi người dùng hủy gói đăng ký, Stripe sẽ thông báo cho Adapty, và Adapty sẽ cập nhật mức độ truy cập. Để hiểu cách Adapty xử lý việc hủy ngay lập tức và hủy vào cuối kỳ, xem [Hủy gói đăng ký](stripe#cancellations).

## Kiểm tra tích hợp \{#test-the-integration\}

Sử dụng chế độ thử nghiệm của Stripe, được kết nối với ứng dụng Adapty của bạn:

1. Chạy ứng dụng của bạn với Adapty SDK key của ứng dụng Adapty mà bạn đã kết nối với Stripe.
2. Mở flow. Các nút sẽ hiển thị mức giá mà ứng dụng của bạn truyền vào, không phải giá trị ban đầu của các custom tag.
3. Nhấn vào nút Stripe plan. Trong PaymentSheet, thanh toán bằng [thẻ test](https://docs.stripe.com/testing) Stripe `4242 4242 4242 4242`, ngày hết hạn bất kỳ trong tương lai và CVC bất kỳ.
4. Xác nhận rằng flow đóng lại và mức độ truy cập của hồ sơ người dùng trở thành active trong vài giây.
5. Trong Adapty Dashboard, mở [**Event Feed**](event-feed). Sự kiện mua hàng sẽ có `store`: `stripe`, `flow_id` và `flow_name` của flow, `flow_variation_id` bằng với `variationId` mà ứng dụng của bạn đã gửi, và placement ID của bạn trong `developer_id`. Đối với giao dịch mua qua Stripe, `variation_id` có cùng giá trị với `flow_variation_id`.

Các giao dịch mua ở chế độ test có môi trường `Sandbox`. Chúng xuất hiện trong Event Feed và trên hồ sơ người dùng, nhưng không xuất hiện trong analytics hay trong các chỉ số của flow — những nơi chỉ tính các giao dịch mua trên môi trường production.

Nếu giao dịch mua không xuất hiện trong Adapty, hãy kiểm tra xem ứng dụng của bạn có đang dùng SDK key của ứng dụng Adapty được kết nối với Stripe không, rằng có sản phẩm Adapty tương ứng với giá Stripe đó, và metadata của gói đăng ký có chứa `customer_user_id` hay không. Ngoài ra, xem thêm [Troubleshooting](stripe#troubleshooting) trong hướng dẫn tích hợp Stripe.

## Hạn chế \{#limitations\}

- **Flow không nhận kết quả từ Stripe**: Flow không thể chuyển sang màn hình khác sau khi thanh toán Stripe thành công, bị hủy, hoặc thất bại. Ứng dụng của bạn sẽ đóng flow và hiển thị nội dung tiếp theo.
- **Giá trong custom tag là văn bản thuần túy**: Flow hiển thị giá trị custom tag đúng như ứng dụng truyền vào, và không tự tính toán các giá trị khác từ đó, chẳng hạn như giá mỗi tuần hay mức giảm giá. Hãy truyền từng giá trị như vậy dưới dạng tag riêng biệt.
- **Giá trị custom tag cố định trong suốt thời gian flow mở**: Để hiển thị giá mới, hãy tải lại flow.