---
title: "React NativeフローでStripe決済を受け付ける"
description: "フローにStripeの価格を表示し、React NativeアプリでStripeのPaymentSheetで決済を行い、AdaptyにアクセスとフローへのRevenueアトリビューションを付与させます。"
---

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

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

Stripe のサブスクリプションは、フロー & ペイウォールビルダーで作成したフローから販売できます。フローには Stripe の価格が表示され、ボタンをタップすると Stripe の [PaymentSheet](https://docs.stripe.com/payments/accept-a-payment?platform=react-native) がフローの上に開きます。支払い完了後、Stripe が Adapty に通知します。Adapty はユーザーにアクセスレベルを付与し、収益をフロー・プレースメント・A/B テストのバリアントに紐付けます。対面イベントのメンバーシップ、クラスパス、定期配送など、アプリ外で消費するサービスのサブスクリプションを販売する際にこの設定をご活用ください。同じフロー内に App Store プロダクトと Stripe の両方を追加して、2 つの支払い方法を提供することも可能です。

:::important
App Storeはデジタルコンテンツや機能に対してアプリ内課金を義務付けており（[ガイドライン 3.1.1](https://developer.apple.com/app-store/review/guidelines/#in-app-purchase)）、Google Playも同様に独自の課金システムの使用を義務付けています（[お支払いに関するポリシー](https://support.google.com/googleplay/android-developer/answer/9858738)）。Stripeを通じたアプリ内決済は、物理的な商品や、ユーザーがアプリ外で消費するサービス向けです（[ガイドライン 3.1.3(e)](https://developer.apple.com/app-store/review/guidelines/#other-purchase-methods)）。Google Playでは、ジムの会員権やライブイベントのチケットなど、こうした購入にGoogleの課金システムを使用することは認められていません。
:::

## 仕組み \{#how-it-works\}

1. アプリはバックエンドからStripeの価格情報を取得し、[カスタムタグ](react-native-flow-custom-tags)としてフローに渡してフローを表示します。
2. ユーザーがフロー内のボタンをタップすると、そのボタンがカスタムアクションをトリガーし、アプリがアクションIDを受け取ります。
3. アプリはバックエンドにStripeサブスクリプションの作成を依頼します。バックエンドはユーザーIDとフローのバリエーションIDをサブスクリプションのメタデータに追加します。
4. アプリはフローの上にPaymentSheetを開き、ユーザーがサブスクリプションの初回請求書の支払いを行います。
5. StripeがAdaptyにWebhookを送信します。Adaptyはユーザーのプロファイルにアクセスレベルを付与し、購入をフローのバリアントに紐付けます。
6. アプリはフローを閉じ、プロファイルにアクセスレベルが付与されるまで待機します。

## 始める前に \{#before-you-start\}

以下が揃っていることを確認してください：

1. **StripeをAdaptyアプリに接続する**: テストモードと本番モードそれぞれで[StripeをAdaptyに接続する](stripe#1-connect-stripe-to-adapty)に従って設定します。[**Profile creation behavior**](stripe#profile-creation-behavior)は**Use customer_user_id from metadata (default)**のままにしてください。
2. **各プランのStripeプロダクトと価格**: 月額・年額などの定期課金価格を設定して[Stripeでプロダクトを作成する](stripe#2-create-products-on-stripe)。
3. **各Stripe価格に対応するAdaptyプロダクト**: [StripeのプロダクトIDと価格IDをAdaptyプロダクトに追加する](stripe#3-add-stripe-products-to-adapty)で、プランが解放するアクセスレベルを割り当てます。アクセスレベルはアプリ内のデジタル機能ではなく、アクティブなメンバーシップのようなサービス利用権を表します。Adaptyプロダクトがなければ、Adaptyは購入を記録しません。
4. **Adapty React Native SDK 4.0.0以降**: StripeへConnectしたAdaptyアプリのキーでSDKを有効化します。AdaptyはそのアプリのStripe Webhookのみを受信します。[ユーザーを識別する](react-native-identifying-users)にはカスタマーユーザーIDを使用し、このフローはログイン済みかつ識別済みのユーザーにのみ表示してください。AdaptyはこのIDを使って、アクセスレベルが付与されるプロファイルを特定します。

   SDK 4.4以降、フローはiOS 16以降が必要です。iOS 15では、`createFlowView`と`AdaptyFlowView`が`platformNotSupported`コードのエラーを返します。アプリがこのエラーを受け取った場合は、フローの代わりに[カスタムペイウォール](react-native-implement-paywalls-manually)などの独自コンテンツを表示してください。
5. **Stripe React Native SDK** (`@stripe/stripe-react-native`) がアプリに組み込まれていること。詳細は Stripe ドキュメントの [Accept a payment](https://docs.stripe.com/payments/accept-a-payment?platform=react-native) を参照してください。
6. **Stripe API を呼び出せるバックエンド**（Stripe の[シークレットキー](https://docs.stripe.com/keys)、または Customer と Subscription の書き込み権限を持つ制限付きキーを使用）が必要です。Adapty 用に生成した制限付きキーは再利用しないでください。そのキーは Adapty のものであり、バックエンドが必要とする書き込み権限がありません。キーはサーバー側で管理してください。

## フローにStripeの価格を表示する \{#show-stripe-prices-in-the-flow\}

フローはカスタムタグを通じてStripeの価格を表示します。カスタムタグとは、フローの読み込み時にアプリがフローへ渡すテキスト値です。Adaptyはカスタムタグの値をフォーマットしないため、「$29.00」のようにユーザーが実際に目にする形式で価格を渡してください。

1. フロー & ペイウォールビルダーで、価格ごとに（例：`stripe_monthly_price`、`stripe_annual_price`）[**String** 変数を作成](flow-custom-tags#create-a-custom-tag)し、**Value comes from outside the app** を選択します。各変数の **Initial value** には現在の価格を設定してください。アプリが価格を読み込めない場合、ユーザーにはこの初期値が表示されるため、Stripe の価格と一致させておきましょう。
2. [各タグをテキスト要素に挿入](flow-custom-tags#add-a-custom-tag-to-a-text-element)します（例：プランボタンのラベルなど）。
3. アプリ内でフローを読み込む前に、バックエンドから価格を取得します。
4. ビューパラメーターの `customTags` フィールドに価格を渡します。

次の関数はフローを読み込み、Stripe の価格を使ってビューパラメーターを構築します。また、バックエンドが Stripe サブスクリプションにフローの `variationId` を書き込むため、フロー自体も返します。フローの表示については[フローから PaymentSheet を開く](#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` は、[バックエンドでサブスクリプションを作成する](#create-the-subscription-on-your-backend) で作成したバックエンドのエンドポイント用クライアントです。

## PaymentSheetを開くボタンを追加する \{#add-buttons-that-open-paymentsheet\}

Stripeプランを販売する各ボタンは、カスタムアクションをトリガーします。アプリはアクションIDを受け取り、そのプランのPaymentSheetを開きます。

1. フロー＆ペイウォールビルダーで、各Stripeプラン用の[ボタンを追加](paywall-buttons)します。
2. 各ボタンに **Custom Action** アクションを割り当て、`buy_stripe_monthly` や `buy_stripe_annual` などのアクションIDを入力します。
3. フローを公開し、[プレースメントに追加](create-placement)します。

アプリは各アクション ID をプランに対応付けます。フローはアクションと一緒にデータをアプリに送信しないため、アクション ID でプランを識別する必要があります。

### Stripe をアプリ内課金の別の支払い方法として追加する \{#add-stripe-as-another-way-to-pay-for-app-store-products\}

このセットアップは、対面イベントの会員権など、ユーザーがアプリ外で消費する物理的な商品またはサービスのプランにのみ使用してください（[ガイドライン 3.1.3(e)](https://developer.apple.com/app-store/review/guidelines/#other-purchase-methods)）。デジタルコンテンツや機能については、[ウェブペイウォール](react-native-web-paywall)を通じて別の支払い方法を提供してください。

これはiOSのみの設定です。Google PlayはGoogle Playの課金システムを物理的な商品やサービスに使用することを許可していないため（[支払いポリシー](https://support.google.com/googleplay/android-developer/answer/9858738)）、Androidではこれらのプランの販売にはStripeのみを使用してください。

フローにはApp Storeのプロダクトが通常通り表示され、「Pay another way」などのリンクをタップするとPaymentSheetが開きます。App Storeの購入ボタンは変更なく引き続き機能します。

1. リンクに **Custom Action** アクションを割り当て、`pay_with_stripe` などのアクション ID を設定します。
2. フロー内の各 App Store プロダクトに対して、同じプランの Stripe price を作成します。
3. アプリ内で、各 App Store プロダクト ID を対応する Stripe プランにマッピングします。
4. ユーザーが選択したプロダクトを保存します。フローは各選択を `onProductSelected` ハンドラーに通知します。フロー & ペイウォールビルダーで作成したフローは、デフォルトでは選択されたプロダクトを通知しないため、ビルダーで選択済みに設定したプロダクトをデフォルトとして使用してください。A/B テストのバリアントごとに異なるプロダクトが選択される場合は、各バリアントのデフォルトプロダクトを保存します。
5. アプリが `pay_with_stripe` を受け取ったら、[フローから PaymentSheet を開く](#open-paymentsheet-from-the-flow) の `StripeCheckout` の `pay` メソッドを、保存したプロダクトの Stripe プランを引数として呼び出します。

フローにはストアフロントによって異なる App Store の価格が表示されます。PaymentSheet では Stripe の価格が請求されます。ユーザーがタップする前に Stripe の価格を表示するには、[カスタムタグとして渡し](#show-stripe-prices-in-the-flow)、各プランのカードに「または月額 $29.00（カード払い）」のように表示してください。カスタムタグの値はフローが開いている間は変わらないため、選択中のプランの価格を 1 つのリンクで表示することはできません。

## バックエンドでサブスクリプションを作成する \{#create-the-subscription-on-your-backend\}

PaymentSheet は、バックエンドが作成した Stripe オブジェクトの支払いを処理します。このガイドでは、バックエンドが Stripe の[サブスクリプション](https://docs.stripe.com/billing/subscriptions/overview)を作成し、PaymentSheet がそのサブスクリプションの最初の請求書の支払いを行います。バックエンドはサブスクリプションの[メタデータ](https://docs.stripe.com/metadata)に 2 つのキーを設定します。

- `customer_user_id`: AdaptyにおけるユーザーのカスタマーユーザーID。AdaptyはこのIDを持つプロファイルにアクセスレベルを付与します。
- `variation_id`: アプリがバックエンドに送信するフローのバリエーションID。Adaptyはこのフローバリエーション、そのプレースメント、およびA/B テストに収益を紐付けます。

:::warning
サブスクリプションや請求書なしで単独で作成したPaymentIntentの支払いは、Adaptyには記録されません。ユーザーが支払いを行っても、アクセスレベルは付与されません。
:::

カスタムタグのフォーマットされた価格を返す最初のエンドポイントと、サブスクリプションを作成して PaymentSheet が必要とする値を返す2番目のエンドポイントを作成します。2番目のエンドポイントはサブスクリプションを作成する前に、ユーザーがすでにアクティブなサブスクリプションを持っていないかを確認するため、同じプランに対して二重に支払いが発生しません。

この例では、`package.json` に `"type": "module"` を設定した Node.js の ES モジュール、Express、およびバージョン18以降の [`stripe` ライブラリ](https://github.com/stripe/stripe-node) を使用しています。`db` はご自身のデータベースに置き換えてください。

```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);
```

`payment_behavior: 'default_incomplete'` を使用すると、サブスクリプションは最初の支払いを待機します。ユーザーが PaymentSheet で支払いを完了すると、Stripe がサブスクリプションを有効化します。ユーザーが支払いをせずに PaymentSheet を閉じた場合、Stripe は約 23 時間後にサブスクリプションを失効させ、Adapty にはその記録が残りません。Stripe の設定全体については、Stripe ドキュメントの [Build a subscriptions integration](https://docs.stripe.com/billing/subscriptions/build-subscriptions?platform=react-native) を参照してください。

コードはクライアントシークレットを `latest_invoice.confirmation_secret` から読み取ります。これには Stripe API バージョン `2025-03-31.basil` 以降が必要です。`stripe` ライブラリはバージョン 18 からこのバージョンを使用します。ライブラリを使わずに Stripe API を呼び出す場合は、`Stripe-Version` ヘッダーを設定してください。それより前の API バージョンでは、`latest_invoice.payment_intent` を展開して `payment_intent.client_secret` を読み取ってください。

アプリ内で 2 つのエンドポイントを呼び出します。バックエンドの要件に従って、各リクエストにユーザーの認証情報を含めてください：

```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 }),
    }),
};
```

## フローからPaymentSheetを開く \{#open-paymentsheet-from-the-flow\}

フロー内のボタンがカスタムアクションをトリガーすると、アプリはPaymentSheetを開き、支払いが成功するとフローを閉じます：

1. カスタムアクションIDをプランにマッピングします。バックエンドの応答待ちやPaymentSheetの表示中は、タップ・リンク・フローの閉じるボタンを無視してください。これにより、1回のタップで1つのサブスクリプションが作成されます。
2. バックエンドにサブスクリプションをリクエストし、プランとフローの `variationId` を渡します。
3. フローの上にPaymentSheetを表示し、その結果を処理します:
   - **Completed**: フローを閉じます。閉じた後、[アクセスレベルの付与を待ちます](#unlock-access-after-the-payment)。
   - **Canceled**: 何もしません。ユーザーはフローに留まり、別のプランを選択できます。
   - **Failed**: エラーを表示します。ユーザーはフローに留まり、再試行できます。
4. フローの閉じるボタン・リンク・エラーを処理します。設定したハンドラーは、そのイベントに対するSDKのデフォルトハンドラーを置き換えます。デフォルトのハンドラーはリンクを開き、モーダル表示の場合は閉じるボタンとエラー発生時にフローを閉じます。
5. カスタムアクションハンドラー内でペイメントを待機せず、ハンドラーから `false` を返してください。モーダル表示の場合、`true` を返すハンドラーはフローを閉じます。`async` ハンドラーも同様に、プロミスを返すためフローを閉じます。

ステップ2とステップ3は、Reactコンポーネントとモーダル表示の両方で共通しているため、このガイドでは1つのセクションにまとめています。

```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;
    }
  }
}
```

iOSでは、PaymentSheetは別のアプリを開く決済方法での支払い後、リターンURLを通じてアプリに戻ります。[StripeドキュメントのリターンURLの設定](https://docs.stripe.com/payments/accept-a-payment?platform=react-native#react-native-set-up-return-url)の説明に従ってアプリにURLスキームを登録し、アプリがそのURLを開いたときにStripeへURLを渡してください。Androidはリターン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();
  }, []);
}
```

次にフローを表示し、そのアクションを `StripeCheckout` に渡します:

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

[`AdaptyFlowView` コンポーネント](react-native-present-paywalls#react-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">

[`createFlowView`](react-native-present-paywalls#modal-presentation) でビューを作成し、イベントハンドラーを設定して表示します。エラーは、ビューの [`showDialog`](react-native-present-paywalls#show-dialog) メソッドで表示します。このメソッドは iOS と Android でフローの上にダイアログを開きます。Android では、SDK バージョン 4.3.0 未満の場合、React Native のアラートがフローの背後で開きます。

```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>

フローが App Store のプロダクトも販売している場合は、[フローイベントの処理](react-native-handling-events-1)に記載されている購入ハンドラーでその購入を処理してください。

## 支払い後にアクセスを解除する \{#unlock-access-after-the-payment\}

支払いが完了すると、Adapty は Stripe のウェブフックを受け取り、数秒以内にアクセスレベルを付与します。SDK はプロファイルを1分に1回更新するため、アクセスレベルが有効になるまでプロファイルをリクエストし続けてください：

```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;
}
```

通常、アクセスレベルは数秒以内に有効になります。60秒経っても有効にならない場合は、[Stripeのウェブフック設定](https://dashboard.stripe.com/webhooks)でAdaptyウェブフックエンドポイントへの配信を確認してください。

支払い後にウェルカム画面などの確認画面を表示したい場合は、アクセスレベルが有効になったタイミングでアプリ内に表示してください。確認画面を2つ目のフローとして作成し、専用のプレースメントに追加して、最初のフローが閉じた後に表示することもできます。設定方法については[購入結果への対応](respond-to-purchase-outcomes)をご覧ください。

## サブスクリプションをユーザーが管理できるようにする \{#let-users-manage-the-subscription\}

Stripe のサブスクリプションは、iOS の設定画面にある App Store サブスクリプションや Google Play のサブスクリプション一覧には表示されません。ユーザーがキャンセルや支払い方法の変更を行えるようにするには、たとえばアカウント画面など、アプリ内の適切な場所にボタンを追加して、[Stripe カスタマーポータル](https://docs.stripe.com/customer-management)を開けるようにしてください。バックエンドでユーザーの Stripe カスタマー向けにポータルセッションを作成し、その URL を返します。

ユーザーがキャンセルすると、StripeはAdaptyに通知し、Adaptyはアクセスレベルを更新します。即時キャンセルと期間終了時のキャンセルをAdaptyがどのように処理するかについては、[キャンセル](stripe#cancellations)を参照してください。

## 連携のテスト \{#test-the-integration\}

Adapty アプリに接続された Stripe のテストモードを使用してください：

1. Stripeに接続したAdaptyアプリのAdapty SDKキーを使用して、iOSおよびAndroidでアプリを起動します。
2. フローを開きます。ボタンにはカスタムタグの初期値ではなく、アプリが渡した価格が表示されるはずです。
3. Stripeプランのボタンをタップします。PaymentSheetでStripeの[テストカード](https://docs.stripe.com/testing) `4242 4242 4242 4242`、将来の有効期限、任意のCVCを使って支払います。
4. フローが閉じ、数秒以内にプロファイルのアクセスレベルがアクティブになることを確認します。
5. Adapty ダッシュボードで[**Event Feed**](event-feed)を開きます。購入イベントには `store`: `stripe`、フローの `flow_id` と `flow_name`、アプリが送信した `variationId` と同じ値の `flow_variation_id`、そして `developer_id` にプレースメントIDが含まれているはずです。Stripe購入の場合、`variation_id` は `flow_variation_id` と同じ値になります。

テストモードの購入は `Sandbox` 環境として記録されます。イベントフィードやプロファイルには表示されますが、アナリティクスやフローの指標には表示されません（本番環境での購入のみがカウントされます）。

購入が Adapty に表示されない場合は、以下を確認してください。アプリが Stripe に接続された Adapty アプリの SDK キーを使用しているか、Stripe の価格に対応する Adapty プロダクトが存在するか、サブスクリプションのメタデータに `customer_user_id` が含まれているか。また、Stripe 連携ガイドの[トラブルシューティング](stripe#troubleshooting)も参照してください。

## 制限事項 \{#limitations\}

- **フローはStripeの結果を受け取りません**: フローはStripeの支払いが成功・キャンセル・失敗した後に別の画面へ遷移することができません。アプリがフローを閉じて、次に表示する内容を制御します。
- **カスタムタグの金額はテキストです**: フローはアプリが渡したカスタムタグの値をそのまま表示し、週あたりの金額や割引額などの別の値を計算しません。それぞれの値を個別のタグとして渡してください。
- **フローが開いている間はカスタムタグの値が固定されます**: 新しい金額を表示するには、フローを再度読み込んでください。