---
title: "Chấp nhận thanh toán Stripe trong flow React Native"
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 React Native, và để Adapty cấp quyền truy cập cũng như ghi nhận doanh thu cho flow."
---

> For the complete documentation index, see [llms.txt](https://adapty.io/docs/vi/llms.txt).

> **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 các gói đăng ký Stripe từ một flow mà bạn 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](https://docs.stripe.com/payments/accept-a-payment?platform=react-native) của Stripe ngay 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 thiết lập này để bán các 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 và tính năng kỹ thuật số ([quy tắc 3.1.1](https://developer.apple.com/app-store/review/guidelines/#in-app-purchase)), và Google Play yêu cầu hệ thống thanh toán của mình cho chúng ([Chính sách thanh toán](https://support.google.com/googleplay/android-developer/answer/9858738)). Thanh toán trong ứng dụng qua Stripe dành cho hàng hóa vật lý và dịch vụ mà người dùng sử dụng bên ngoài ứng dụng ([quy tắc 3.1.3(e)](https://developer.apple.com/app-store/review/guidelines/#other-purchase-methods)). Google Play không cho phép sử dụng hệ thống thanh toán của mình cho các giao dịch này, chẳng hạn như gói thành viên phòng gym hay vé sự kiện trực tiếp.
:::

## Cách 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](react-native-flow-custom-tags) và hiển thị flow.
2. Người dùng nhấn một nút trong flow. Nút đó kích hoạt một hành động tùy chỉnh, 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 một 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ờ cho đến khi hồ sơ người dùng có mức độ truy cập.

## Trước khi bắt đầu

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

1. **Stripe đã 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) ở mức **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 giá theo chu 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ụ, chẳng hạn như tư cách thành viên đang hoạt động, 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. **SDK React Native Adapty 4.0.0 trở lên**: Khởi tạo SDK bằng key của ứng dụng Adapty đã kết nối với Stripe. Adapty chỉ nhận webhook của Stripe cho ứng dụng đó. [Xác định người dùng](react-native-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 được mức độ truy cập.

   Bắt đầu từ SDK 4.4, các flow yêu cầu iOS 16 trở lên. Trên iOS 15, `createFlowView` và `AdaptyFlowView` sẽ báo lỗi với mã `platformNotSupported`. Khi ứng dụng của bạn nhận được lỗi này, hãy hiển thị nội dung riêng của bạn thay vì flow, chẳng hạn như một [paywall tùy chỉnh](react-native-implement-paywalls-manually).
5. **The Stripe React Native SDK** (`@stripe/stripe-react-native`) trong ứng dụng của bạn. Xem [Accept a payment](https://docs.stripe.com/payments/accept-a-payment?platform=react-native) trong tài liệu Stripe.
6. **Một backend có khả năng gọi Stripe API** với [secret key](https://docs.stripe.com/keys) Stripe của bạn, hoặc với một restricted key do bạn 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 này 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`, và 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 của bạn, lấy giá từ backend trước khi tải flow.
4. Truyền các mức giá vào trường `customTags` của tham số view.

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

```typescript showLineNumbers title="React Native"

export type StripeFlow = {
  flow: AdaptyFlow;
  params: CreateFlowViewParamsInput;
};

export async function loadStripeFlow(): Promise<StripeFlow> {
  // If the prices fail to load, the flow shows the tags' initial values
  const prices = await Backend.fetchPrices().catch((): Record<string, string> => ({}));

  const flow = await adapty.getFlow('YOUR_PLACEMENT_ID');
  const customTags: Record<string, string> = {};
  if (prices.monthly) customTags.stripe_monthly_price = prices.monthly;
  if (prices.annual) customTags.stripe_annual_price = prices.annual;

  return { flow, params: { customTags } };
}
```

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

## Thêm 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 hành động tùy chỉnh. Ứng dụng của bạn nhận ID hành động 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 hành động **Custom Action** cho mỗi nút, và nhập ID hành động, 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 ID hành động tới một gói. Flow không gửi bất kỳ dữ liệu nào kèm theo hành động, vì vậy ID hành động phải xác định gói đó.

### Thêm Stripe làm 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 ([guideline 3.1.3(e)](https://developer.apple.com/app-store/review/guidelines/#other-purchase-methods)), chẳng hạn như thành viên của các sự kiện trực tiếp. Đối với nội dung kỹ thuật số hoặ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](react-native-web-paywall).

Thiết lập này chỉ dành cho iOS. Google Play không cho phép sử dụng hệ thống thanh toán của mình để bán hàng hóa và dịch vụ vật lý ([Chính sách thanh toán](https://support.google.com/googleplay/android-developer/answer/9858738)), vì vậy trên Android, hãy bán các gói này thông qua Stripe.

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 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 như `pay_with_stripe`.
2. Với mỗi sản phẩm App Store trong flow, hãy tạo một Stripe price tương ứng 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 trữ sản phẩm mà người dùng chọn. Flow sẽ báo cáo từng lựa chọn đến handler `onProductSelected`. Flow được tạo 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 trữ sản phẩm mặc định cho mỗi biến thể.
5. Khi ứng dụng nhận được `pay_with_stripe`, hãy gọi phương thức `pay` của `StripeCheckout` 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á đó qua custom tag](#show-stripe-prices-in-the-flow) và hiển thị trong card của từng gói, ví dụ "or $29.00/month by card". Giá trị custom tag không thay đổi khi flow đang mở, vì vậy một liên kết 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 của nó và A/B test tương ứng.

:::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 sẽ bị trừ tiền nhưng 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, để đảm bảo người dùng khô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à [`stripe` library](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 gói đăng ký 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ết hạn gói đăng ký sau khoảng 23 giờ và Adapty sẽ không ghi lại giao dịch đó. Để biết toàn bộ các bước thiết lập Stripe, xem [Build a subscriptions integration](https://docs.stripe.com/billing/subscriptions/build-subscriptions?platform=react-native) trong tài liệu Stripe.

Mã đọc client secret từ `latest_invoice.confirmation_secret`, yêu cầu Stripe API version `2025-03-31.basil` trở lên. Thư viện `stripe` sử dụng version này từ phiên bản 18. Nếu bạn gọi Stripe API trực tiếp mà không dùng thư viện, hãy đặt header `Stripe-Version`. Với API version 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 trên. 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:

```typescript showLineNumbers title="React Native"
const BASE_URL = 'https://YOUR_BACKEND';

export type Subscription = {
  subscriptionId: string;
  clientSecret: string;
  publishableKey: string;
};

async function send<T>(path: string, init?: RequestInit): Promise<T> {
  const response = await fetch(`${BASE_URL}/${path}`, init);
  if (response.status !== 200) {
    // Use the backend's message when the response has one
    const body = await response.json().catch(() => null);
    throw new Error(body?.error ?? `The server returned HTTP ${response.status}.`);
  }
  return response.json();
}

export const Backend = {
  fetchPrices: () => send<Record<string, string>>('prices'),

  createSubscription: (plan: string, variationId: string) =>
    send<Subscription>('subscriptions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // add your authentication header
      },
      body: JSON.stringify({ plan, variationId }),
    }),
};
```

## 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 custom action, 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, link, 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 chỉ tạo 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 `variationId` của flow.
3. Hiển thị PaymentSheet phía trên flow, và xử lý kết quả trả về:
   - **Completed**: Đóng flow. Sau khi đóng, [chờ mức độ truy cập được cấp](#unlock-access-after-the-payment).
   - **Canceled**: Không làm gì. Người dùng vẫn ở trên flow và có thể chọn gói khác.
   - **Failed**: Hiển thị lỗi. Người dùng vẫn ở trên flow và có thể thử lại.
4. Xử lý nút đóng của flow, các link, và lỗi. Handler mà bạn thiết lập sẽ thay thế handler mặc định của SDK cho sự kiện đó. Các handler mặc định sẽ mở link và, khi hiển thị dạng modal, đóng flow khi nhấn nút đóng hoặc khi có lỗi.
5. Đừng chờ thanh toán trong handler của hành động tùy chỉnh, và trả về `false` từ nó. Khi hiển thị dạng modal, một handler trả về `true` sẽ đóng flow, và handler `async` cũng vậy, vì nó trả về một promise.

Các bước 2 và 3 giống nhau cho cả React component và modal presentation, vì vậy hướng dẫn này gộp chúng vào một lớp:

```typescript showLineNumbers title="React Native"
  initPaymentSheet,
  initStripe,
  PaymentSheetError,
  presentPaymentSheet,
} from '@stripe/stripe-react-native';

/** What the checkout needs from the screen that shows the flow */
export type CheckoutHost = {
  isFlowOpen: () => boolean;
  showError: (message: string) => void;
};

export class StripeCheckout {
  // Custom action IDs from the flow, mapped to your backend's plan keys
  static readonly plans: Record<string, string> = {
    buy_stripe_monthly: 'monthly',
    buy_stripe_annual: 'annual',
  };

  private paying = false;

  get isPaying(): boolean {
    return this.paying;
  }

  /** Opens PaymentSheet for a plan over the flow. Resolves to `true` when the user paid. */
  async pay(plan: string, variationId: string, host: CheckoutHost): Promise<boolean> {
    if (this.paying) return false;
    this.paying = true;

    try {
      const subscription = await Backend.createSubscription(plan, variationId);
      // The flow may have closed while the backend responded
      if (!host.isFlowOpen()) return false;

      await initStripe({ publishableKey: subscription.publishableKey });
      const { error: initError } = await initPaymentSheet({
        paymentIntentClientSecret: subscription.clientSecret,
        merchantDisplayName: 'YOUR_BUSINESS_NAME',
        // iOS: for payment methods that redirect to another app, such as bank apps
        returnURL: 'your-app://stripe-redirect',
      });
      if (initError) {
        host.showError(initError.message);
        return false;
      }

      const { error } = await presentPaymentSheet();
      if (!error) {
        return true;
      }
      if (error.code !== PaymentSheetError.Canceled) {
        host.showError(error.message);
      }
      return false; // the user stays on the flow
    } catch (error) {
      host.showError(error instanceof Error ? error.message : String(error));
      return false;
    } finally {
      this.paying = false;
    }
  }
}
```

Trên iOS, 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. Hãy đăng ký URL scheme trong ứng dụng của bạn theo hướng dẫn tại [Set up a return URL](https://docs.stripe.com/payments/accept-a-payment?platform=react-native#react-native-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ở URL này. Android không cần return URL.

```typescript showLineNumbers title="React Native"

// Call this hook in your root component
export function useStripeReturnURL() {
  useEffect(() => {
    const forward = (url: string | null) => {
      if (url) void handleURLCallback(url);
    };
    void Linking.getInitialURL().then(forward);
    const subscription = Linking.addEventListener('url', ({ url }) => forward(url));
    return () => subscription.remove();
  }, []);
}
```

Trình bày flow, và truyền các action của nó vào `StripeCheckout`:

<Tabs groupId="presentation-method" queryString>
<TabItem value="platform" label="React component" default>

Render flow bằng [component `AdaptyFlowView`](react-native-present-paywalls#react-component), và truyền các handler của nó dưới dạng props. Component sẽ bỏ qua các giá trị mà handler trả về, vì vậy để đóng flow, hãy dừng render component đó:

```typescript showLineNumbers title="React Native (TSX)"

export function MembershipScreen() {
  const [stripeFlow, setStripeFlow] = useState<StripeFlow | null>(null);
  const [checkout] = useState(() => new StripeCheckout());
  const isLoadingFlow = useRef(false);
  const isFlowOpen = useRef(false);

  // The screen can close while the backend responds, for example on Android back navigation
  useEffect(() => () => {
    isFlowOpen.current = false;
  }, []);

  const host: CheckoutHost = {
    isFlowOpen: () => isFlowOpen.current,
    showError: (message) => Alert.alert("The payment didn't go through", message),
  };

  function closeFlow() {
    isFlowOpen.current = false;
    setStripeFlow(null);
  }

  async function showStripeFlow() {
    if (isLoadingFlow.current) return;
    isLoadingFlow.current = true;

    try {
      const loadedFlow = await loadStripeFlow();
      isFlowOpen.current = true;
      setStripeFlow(loadedFlow);
    } catch (error) {
      // handle the error
    } finally {
      isLoadingFlow.current = false;
    }
  }

  async function payAndClose(plan: string, variationId: string) {
    if (!(await checkout.pay(plan, variationId, host))) return;
    closeFlow();
    await unlockAfterPayment();
  }

  if (!stripeFlow) {
    return <Button title="Become a member" onPress={() => void showStripeFlow()} />;
  }

  return (
    <AdaptyFlowView
      flow={stripeFlow.flow}
      params={stripeFlow.params}
      style={{ flex: 1 }}
      onCloseButtonPress={() => {
        if (!checkout.isPaying) closeFlow();
      }}
      onUrlPress={(url, openIn) => {
        if (checkout.isPaying) return;
        adapty.openWebUrl(url, openIn).catch(() => {
          // handle the error
        });
      }}
      onError={() => {
        // Keep the flow, and PaymentSheet over it, while the user pays.
        // Otherwise stop rendering the flow, and show your own content.
        if (!checkout.isPaying) closeFlow();
      }}
      onCustomAction={(actionId) => {
        const plan = StripeCheckout.plans[actionId];
        if (!plan) return;
        payAndClose(plan, stripeFlow.flow.variationId).catch(() => {
          // handle the error
        });
      }}
    />
  );
}

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

</TabItem>
<TabItem value="standalone" label="Modal presentation">

Tạo view bằng [`createFlowView`](react-native-present-paywalls#modal-presentation), thiết lập các trình xử lý sự kiện và hiển thị nó. Hiển thị lỗi bằng phương thức [`showDialog`](react-native-present-paywalls#show-dialog) của view, phương thức này mở hộp thoại ngay trên flow ở iOS và Android. Trên Android, với các phiên bản SDK cũ hơn 4.3.0, một React Native alert sẽ mở phía sau flow.

```typescript showLineNumbers title="React Native"

const checkout = new StripeCheckout();
let isLoadingFlow = false;

export async function showStripeFlow() {
  if (isLoadingFlow) return;
  isLoadingFlow = true;

  try {
    const { flow, params } = await loadStripeFlow();
    const view = await createFlowView(flow, params);

    const host: CheckoutHost = {
      // The handlers below don't close the flow while the user pays
      isFlowOpen: () => true,
      showError: (message) => {
        view
          .showDialog({
            title: "The payment didn't go through",
            content: message,
            primaryActionTitle: 'OK',
          })
          .catch(() => {
            // handle the error
          });
      },
    };

    async function payAndClose(plan: string) {
      if (!(await checkout.pay(plan, flow.variationId, host))) return;
      try {
        await view.dismiss();
      } finally {
        // The user paid, so unlock even if the flow fails to close
        await unlockAfterPayment();
      }
    }

    view.setEventHandlers({
      onCloseButtonPress: () => !checkout.isPaying,
      onUrlPress(url, openIn) {
        if (!checkout.isPaying) {
          adapty.openWebUrl(url, openIn).catch(() => {
            // handle the error
          });
        }
        return false;
      },
      // Keep the flow, and PaymentSheet over it, while the user pays
      onError: () => !checkout.isPaying,
      onCustomAction(actionId) {
        const plan = StripeCheckout.plans[actionId];
        if (plan) {
          payAndClose(plan).catch(() => {
            // handle the error
          });
        }
        return false;
      },
    });

    await view.present();
  } catch (error) {
    // handle the error
  } finally {
    isLoadingFlow = false;
  }
}

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

</TabItem>
</Tabs>

Nếu flow của bạn cũng bán các sản phẩm trên App Store, hãy xử lý các giao dịch mua trong các purchase handler như được mô tả trong [Xử lý sự kiện flow](react-native-handling-events-1).

## 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 gọi lấy hồ sơ người dùng cho đến khi mức độ truy cập được kích hoạt:

```typescript showLineNumbers title="React Native"

export async function waitForAccess(): Promise<boolean> {
  for (let attempt = 1; attempt <= 20; attempt++) {
    try {
      const profile = await adapty.getProfile();
      if (profile.accessLevels?.['YOUR_ACCESS_LEVEL']?.isActive) {
        return true;
      }
    } catch {
      // try again
    }
    await new Promise<void>((resolve) => setTimeout(resolve, 3000));
  }
  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 lịch sử giao nhận của Adapty webhook endpoint trong [cài đặt webhook của Stripe](https://dashboard.stripe.com/webhooks).

Để hiển thị màn hình 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 placement riêng của nó, và hiển thị 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 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ý App Store của người dùng trong Cài đặt iOS, hay trong danh sách gói đăng ký Google Play của họ. Để 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, Stripe thông báo cho Adapty, và Adapty 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 đă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 trên iOS và Android với Adapty SDK key của ứng dụng mà bạn đã kết nối với Stripe.
2. Mở flow. Các nút sẽ hiển thị 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 của một Stripe plan. Trong PaymentSheet, thanh toán bằng [test card](https://docs.stripe.com/testing) của Stripe `4242 4242 4242 4242`, nhập ngày hết hạn 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 trong 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 hiển thị trong analytics hay trong các chỉ số của flow — vì những mục này chỉ tính các giao dịch mua trong 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, có sản phẩm Adapty tương ứng với giá Stripe không, và metadata của gói đăng ký có chứa `customer_user_id` không. Bạn cũng có thể xem thêm tại [Khắc phục sự cố](stripe#troubleshooting) trong hướng dẫn tích hợp Stripe.

## Giới hạn \{#limitations\}

- **Flow không nhận được 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. App 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**: Flow hiển thị giá trị của custom tag đúng như app 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ị đó dưới dạng một tag riêng.
- **Giá trị custom tag cố định trong khi flow đang mở**: Để hiển thị giá mới, hãy tải lại flow.