---
title: "AndroidフローでStripeの支払いを受け付ける"
description: "フローにStripe価格を表示し、Androidアプリで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=android) がフロー上に開きます。支払い完了後、Stripe は Adapty に通知します。Adapty はユーザーにアクセスレベルを付与し、収益をフロー・プレースメント・A/B テストのバリアントに紐付けます。対面イベントのメンバーシップ、クラスパス、定期配送など、アプリ外で利用するサービスのサブスクリプション販売にご活用ください。

:::important
Google Playはデジタル商品やサービスに対して自社の課金システムの使用を義務付けています。物理的な商品や物理的なサービスに対しては、自社の課金システムの使用を禁じています（[決済ポリシー](https://support.google.com/googleplay/android-developer/answer/9858738)）。Stripeを通じたアプリ内支払いは、物理的な商品、またはユーザーがアプリ外で利用するサービスに対して行うものです。
:::

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

1. アプリがバックエンドからStripeの価格情報を取得し、それを[カスタムタグ](android-flow-custom-tags)としてフローに渡してフローを表示します。
2. ユーザーがフロー内のボタンをタップすると、そのボタンがカスタムアクションをトリガーし、アプリがアクションIDを受け取ります。
3. アプリがバックエンドにStripeサブスクリプションの作成を依頼します。バックエンドはサブスクリプションのメタデータにユーザーIDとフローのバリエーションIDを追加します。
4. アプリがフローの上にPaymentSheetを開き、ユーザーがサブスクリプションの初回請求を支払います。
5. StripeがAdaptyにWebhookを送信します。AdaptyはユーザーIDを持つプロファイルにアクセスレベルを付与し、購入をフローのバリアントに帰属させます。
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 Android SDK 4.0.0以降**（`android-ui`モジュール含む）: StripeとAdaptyを接続したAdaptyアプリのキーでSDKをアクティベートします。AdaptyはそのアプリのStripe Webhookのみ受信します。[ユーザーを識別する](identifying-users)際はカスタマーユーザーIDを使用し、ログイン済みで識別済みのユーザーにのみこのフローを表示してください。AdaptyはこのIDを使ってアクセスレベルが付与されるプロファイルを特定します。
5. **Stripe Android SDK 20.46.0以降**（`com.stripe:stripe-android`）をアプリに組み込む。Stripeドキュメントの[Accept a payment](https://docs.stripe.com/payments/accept-a-payment?platform=android)を参照してください。
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. Flow & ペイウォールビルダーで、各価格に対して[**String** 変数を作成し](flow-custom-tags#create-a-custom-tag)（例：`stripe_monthly_price`、`stripe_annual_price`）、**Value comes from outside the app** を選択します。各変数の **Initial value** に現在の価格を設定してください。アプリが価格を読み込めない場合、ユーザーにはこの初期値が表示されるため、初期値は Stripe の価格と同じにしておいてください。
2. [各タグをテキスト要素に挿入します](flow-custom-tags#add-a-custom-tag-to-a-text-element)（プランボタンのラベルなど）。
3. アプリ内で、フローを読み込む前にバックエンドから価格を取得します。
4. `AdaptyFlowView.showFlow` または `AdaptyFlowScreen` の `tagResolver` パラメーターに価格を渡します。

以下の関数はフローを読み込み、Stripe の価格情報を使ったタグリゾルバーを作成します。また、フローの `variationId` を返します。これは、バックエンドがこの ID を Stripe サブスクリプションに書き込むために使用します。フローの表示方法は[フローから PaymentSheet を開く](#open-paymentsheet-from-the-flow)を参照してください。

<Tabs groupId="android-sdk-version" queryString>
<TabItem value="4.5" label="SDK 4.5 or later" default>

```kotlin showLineNumbers title="Kotlin"

class StripeFlow(
    val configuration: AdaptyUI.FlowConfiguration,
    val variationId: String,
    val tagResolver: AdaptyUiTagResolver,
)

suspend fun loadStripeFlow(): StripeFlow {
    // If the prices fail to load, the flow shows the tags' initial values
    val prices = try {
        Backend.fetchPrices()
    } catch (e: IOException) {
        emptyMap()
    }
    val customTags = mapOf(
        "stripe_monthly_price" to prices["monthly"],
        "stripe_annual_price" to prices["annual"],
    )

    val flow = awaitAdapty { callback -> Adapty.getFlow("YOUR_PLACEMENT_ID", callback = callback) }
    val preferredLocales = LocaleListCompat.getAdjustedDefault().toLanguageTags().split(",")
    val configuration = awaitAdapty { callback ->
        AdaptyUI.getFlowConfiguration(flow, preferredLocales, callback = callback)
    }
    return StripeFlow(
        configuration = configuration,
        variationId = flow.variationId,
        tagResolver = AdaptyUiTagResolver { tag -> customTags[tag] },
    )
}

// Turns an Adapty SDK callback into a suspend call
suspend fun <T> awaitAdapty(call: (ResultCallback<T>) -> Unit): T =
    suspendCancellableCoroutine { continuation ->
        call { result ->
            when (result) {
                is AdaptyResult.Success -> continuation.resume(result.value)
                is AdaptyResult.Error -> continuation.resumeWithException(result.error)
            }
        }
    }
```

</TabItem>
<TabItem value="4.4" label="SDK 4.0–4.4">

```kotlin showLineNumbers title="Kotlin"

class StripeFlow(
    val configuration: AdaptyUI.FlowConfiguration,
    val variationId: String,
    val tagResolver: AdaptyUiTagResolver,
)

suspend fun loadStripeFlow(): StripeFlow {
    // If the prices fail to load, the flow shows the tags' initial values
    val prices = try {
        Backend.fetchPrices()
    } catch (e: IOException) {
        emptyMap()
    }
    val customTags = mapOf(
        "stripe_monthly_price" to prices["monthly"],
        "stripe_annual_price" to prices["annual"],
    )

    val flow = awaitAdapty { callback -> Adapty.getFlow("YOUR_PLACEMENT_ID", callback = callback) }
    val configuration = awaitAdapty { callback ->
        AdaptyUI.getFlowConfiguration(flow, callback = callback)
    }
    return StripeFlow(
        configuration = configuration,
        variationId = flow.variationId,
        tagResolver = AdaptyUiTagResolver { tag -> customTags[tag] },
    )
}

// Turns an Adapty SDK callback into a suspend call
suspend fun <T> awaitAdapty(call: (ResultCallback<T>) -> Unit): T =
    suspendCancellableCoroutine { continuation ->
        call { result ->
            when (result) {
                is AdaptyResult.Success -> continuation.resume(result.value)
                is AdaptyResult.Error -> continuation.resumeWithException(result.error)
            }
        }
    }
```

</TabItem>
</Tabs>

`Backend` はバックエンドのエンドポイント（[バックエンドでサブスクリプションを作成する](#create-the-subscription-on-your-backend)を参照）のクライアントです。Adapty SDK はコールバックで結果を返すため、`awaitAdapty` はこのガイドのコルーチン向けにコールバックをサスペンド呼び出しに変換します。

## 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 でプランを識別する必要があります。

## バックエンドでサブスクリプションを作成する \{#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=android) を参照してください。

コードはクライアントシークレットを `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つのエンドポイントを呼び出します。バックエンドの要件に従い、各リクエストにユーザーの認証情報を含めてください：

```kotlin showLineNumbers title="Kotlin"

object Backend {
    private const val BASE_URL = "https://YOUR_BACKEND"

    class Subscription(
        val subscriptionId: String,
        val clientSecret: String,
        val publishableKey: String,
    )

    class BackendException(message: String) : IOException(message)

    suspend fun fetchPrices(): Map<String, String> {
        val json = send("prices")
        return json.keys().asSequence().associateWith { json.optString(it) }
    }

    suspend fun createSubscription(plan: String, variationId: String): Subscription {
        val body = JSONObject()
            .put("plan", plan)
            .put("variationId", variationId)
        val json = send("subscriptions", body)
        return Subscription(
            subscriptionId = json.requireString("subscriptionId"),
            clientSecret = json.requireString("clientSecret"),
            publishableKey = json.requireString("publishableKey"),
        )
    }

    private suspend fun send(path: String, body: JSONObject? = null): JSONObject =
        withContext(Dispatchers.IO) {
            val connection = URL("$BASE_URL/$path").openConnection() as HttpURLConnection
            try {
                // add your authentication header
                if (body != null) {
                    connection.requestMethod = "POST"
                    connection.doOutput = true
                    connection.setRequestProperty("Content-Type", "application/json")
                    connection.outputStream.use { it.write(body.toString().toByteArray()) }
                }
                val statusCode = connection.responseCode
                val stream = if (statusCode == 200) connection.inputStream else connection.errorStream
                val text = stream?.bufferedReader()?.use { it.readText() }.orEmpty()
                val json = try {
                    JSONObject(text)
                } catch (e: JSONException) {
                    null
                }
                if (statusCode != 200) {
                    // Use the backend's message when the response has one
                    val message = json?.optString("error").orEmpty()
                    throw BackendException(message.ifEmpty { "The server returned HTTP $statusCode." })
                }
                json ?: throw BackendException("The server returned an invalid response.")
            } finally {
                connection.disconnect()
            }
        }

    private fun JSONObject.requireString(key: String): String =
        optString(key).ifEmpty { throw BackendException("The response has no $key.") }
}
```

## フローから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のデフォルトハンドラーを置き換えます（デフォルトはフローを閉じます）。URL オープンアクションの場合は、URLを開くデフォルトハンドラーを呼び出してください。
5. PaymentSheetはアクティビティの `onCreate`、またはコンポーザブルではコンポジションのたびに作成してください。StripeはアクティビティのリザルトにPaymentSheetを登録しますが、アクティビティは起動後に登録できません。

ステップ1〜3はViewsとJetpack Composeで共通なので、このガイドではそれらを1つのViewModelにまとめています。ViewModelは、ロードされたフローと支払い状態も保持します。これにより、たとえばPaymentSheetが開いている状態でユーザーが画面を回転させた場合など、Androidがアクティビティを再作成しても状態が維持されます。

```kotlin showLineNumbers title="Kotlin"

class StripeCheckout : ViewModel() {
    companion object {
        // Custom action IDs from the flow, mapped to your backend's plan keys
        val plans = mapOf(
            "buy_stripe_monthly" to "monthly",
            "buy_stripe_annual" to "annual",
        )
    }

    sealed interface Event {
        class PresentPaymentSheet(val subscription: Backend.Subscription) : Event
        class ShowError(val error: Throwable) : Event
    }

    private val _flow = MutableStateFlow<StripeFlow?>(null)
    /** The flow to show, or `null` when the flow is closed. */
    val flow: StateFlow<StripeFlow?> = _flow.asStateFlow()

    private val _events = Channel<Event>(Channel.BUFFERED)
    val events = _events.receiveAsFlow()

    private var isLoadingFlow = false
    private var isPaying = false

    fun showFlow() {
        if (isLoadingFlow || _flow.value != null) return
        isLoadingFlow = true
        viewModelScope.launch {
            try {
                _flow.value = loadStripeFlow()
            } catch (e: AdaptyError) {
                // handle the error
            } finally {
                isLoadingFlow = false
            }
        }
    }

    fun closeFlow() {
        if (isPaying) return
        _flow.value = null
    }

    /** Creates the subscription for a plan, and asks the screen to open PaymentSheet. */
    fun pay(plan: String) {
        val variationId = _flow.value?.variationId ?: return
        if (isPaying) return
        isPaying = true
        viewModelScope.launch {
            try {
                val subscription = Backend.createSubscription(plan, variationId)
                _events.send(Event.PresentPaymentSheet(subscription))
            } catch (e: IOException) {
                isPaying = false
                _events.send(Event.ShowError(e))
            }
        }
    }

    /** Pass this function to PaymentSheet as its result callback. */
    fun onPaymentSheetResult(result: PaymentSheetResult) {
        isPaying = false
        when (result) {
            is PaymentSheetResult.Completed -> {
                _flow.value = null
                unlockAfterPayment()
            }
            is PaymentSheetResult.Canceled -> Unit // the user stays on the flow
            is PaymentSheetResult.Failed -> _events.trySend(Event.ShowError(result.error))
        }
    }

    private fun unlockAfterPayment() {
        viewModelScope.launch {
            if (waitForAccess()) {
                // unlock the service
            } else {
                // tell the user that the payment is processing, and how to reach your support
            }
        }
    }
}

fun presentPaymentSheet(
    paymentSheet: PaymentSheet,
    context: Context,
    subscription: Backend.Subscription,
) {
    PaymentConfiguration.init(context, subscription.publishableKey)
    val configuration = PaymentSheet.Configuration.Builder("YOUR_BUSINESS_NAME").build()
    paymentSheet.presentWithPaymentIntent(subscription.clientSecret, configuration)
}

fun showPaymentError(context: Context, error: Throwable) {
    AlertDialog.Builder(context)
        .setTitle("The payment didn't go through")
        .setMessage(error.localizedMessage)
        .setPositiveButton("OK", null)
        .show()
}
```

フローのイベントリスナーは、フローのアクションを `StripeCheckout` に渡します。これは `AdaptyFlowDefaultEventListener` を継承しているため、オーバーライドされていないイベントはデフォルトの処理が維持されます。

```kotlin showLineNumbers title="Kotlin"

class StripeFlowEventListener(
    private val checkout: StripeCheckout,
) : AdaptyFlowDefaultEventListener() {

    override fun onActionPerformed(action: AdaptyUI.Action, context: Context) {
        when (action) {
            AdaptyUI.Action.Close -> checkout.closeFlow()
            is AdaptyUI.Action.Custom -> {
                val plan = StripeCheckout.plans[action.customId] ?: return
                checkout.pay(plan)
            }
            // The default handler opens the URL
            is AdaptyUI.Action.OpenUrl -> super.onActionPerformed(action, context)
        }
    }
}
```

`StripeCheckout` が要求したときにフローを表示し、`PaymentSheet` を表示します：

<Tabs groupId="android-ui-framework">
<TabItem value="views" label="Views" default>

`onCreate` で PaymentSheet を作成し、画面上のコンテナにフローを表示します。Android がアクティビティを再生成したときにフローの状態を保持できるよう、フロービューに安定した ID を付与してください：

```kotlin showLineNumbers title="Kotlin"

class MembershipActivity : AppCompatActivity() {
    private val checkout: StripeCheckout by viewModels()
    private val eventListener by lazy { StripeFlowEventListener(checkout) }
    private lateinit var paymentSheet: PaymentSheet
    private lateinit var flowContainer: FrameLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_membership)
        // A FrameLayout over the whole screen, empty while the flow is closed
        flowContainer = findViewById(R.id.flow_container)
        findViewById<Button>(R.id.become_member_button).setOnClickListener {
            checkout.showFlow()
        }

        // PaymentSheet registers for an activity result, so create it in onCreate
        paymentSheet = PaymentSheet.Builder(checkout::onPaymentSheetResult).build(this)

        lifecycleScope.launch {
            // Also shows the flow again after the activity is recreated
            checkout.flow.collect(::showFlow)
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                checkout.events.collect { event ->
                    when (event) {
                        is StripeCheckout.Event.PresentPaymentSheet ->
                            presentPaymentSheet(paymentSheet, this@MembershipActivity, event.subscription)
                        is StripeCheckout.Event.ShowError ->
                            showPaymentError(this@MembershipActivity, event.error)
                    }
                }
            }
        }
    }

    private fun showFlow(stripeFlow: StripeFlow?) {
        flowContainer.removeAllViews()
        if (stripeFlow == null) return

        val flowView = AdaptyFlowView(this)
        // A stable ID keeps the flow's state when the activity is recreated.
        // Declare it in res/values/ids.xml: <item name="stripe_flow_view" type="id" />
        flowView.id = R.id.stripe_flow_view
        flowContainer.addView(flowView)
        flowView.showFlow(
            stripeFlow.configuration,
            products = null,
            eventListener = eventListener,
            tagResolver = stripeFlow.tagResolver,
        )
    }
}
```

</TabItem>
<TabItem value="compose" label="Jetpack Compose">

[`AdaptyFlowScreen`](android-present-paywalls) でフローを表示し、同じコンポーザブル内で PaymentSheet を構築します。条件分岐の中ではなく、コンポジションのたびに `build()` を呼び出してください：

```kotlin showLineNumbers title="Kotlin"

@Composable
fun MembershipScreen(checkout: StripeCheckout = viewModel()) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    val stripeFlow by checkout.flow.collectAsStateWithLifecycle()
    val eventListener = remember(checkout) { StripeFlowEventListener(checkout) }

    // Call it unconditionally: PaymentSheet registers for an activity result
    val paymentSheet = remember(checkout) {
        PaymentSheet.Builder(checkout::onPaymentSheetResult)
    }.build()

    LaunchedEffect(checkout, lifecycleOwner) {
        lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
            checkout.events.collect { event ->
                when (event) {
                    is StripeCheckout.Event.PresentPaymentSheet ->
                        presentPaymentSheet(paymentSheet, context, event.subscription)
                    is StripeCheckout.Event.ShowError ->
                        showPaymentError(context, event.error)
                }
            }
        }
    }

    Box(Modifier.fillMaxSize()) {
        Button(onClick = { checkout.showFlow() }) {
            Text("Become a member")
        }
        stripeFlow?.let { flow ->
            AdaptyFlowScreen(
                flowConfiguration = flow.configuration,
                products = null,
                eventListener = eventListener,
                tagResolver = flow.tagResolver,
            )
        }
    }
}
```

</TabItem>
</Tabs>

フローがGoogle Playのプロダクトも販売している場合、Adapty SDKが購入処理を行います。購入イベントに対応するには、[フローイベントの処理](android-handling-events)で説明されているように、`StripeFlowEventListener`のイベントメソッドをオーバーライドしてください。

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

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

```kotlin showLineNumbers title="Kotlin"

suspend fun waitForAccess(): Boolean {
    repeat(20) {
        val profile = try {
            awaitAdapty<AdaptyProfile> { callback -> Adapty.getProfile(callback) }
        } catch (e: AdaptyError) {
            null
        }
        if (profile?.accessLevels?.get("YOUR_ACCESS_LEVEL")?.isActive == true) return true
        delay(3.seconds)
    }
    return false
}
```

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

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

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

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

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

## インテグレーションをテストする \{#test-the-integration\}

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

1. Stripeに接続したAdaptyアプリのAdapty SDKキーを使ってアプリを起動します。
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の決済が成功・キャンセル・失敗した後、フローは別の画面に遷移できません。アプリがフローを閉じ、次に表示するコンテンツを制御します。
- **カスタムタグの価格はテキストとして扱われる**: フローはアプリが渡したカスタムタグの値をそのまま表示するため、週ごとの価格や割引率などの値を自動計算しません。それぞれの値を個別のタグとして渡してください。
- **カスタムタグの値はフローが開いている間は固定される**: 新しい価格を表示するには、フローを再度読み込んでください。