AndroidフローでStripeの支払いを受け付ける
Stripe のサブスクリプションを、フロー&ペイウォールビルダーで作成したフローから販売できます。フローには Stripe の価格が表示され、ボタンをタップすると Stripe の PaymentSheet がフロー上に開きます。支払い完了後、Stripe は Adapty に通知します。Adapty はユーザーにアクセスレベルを付与し、収益をフロー・プレースメント・A/B テストのバリアントに紐付けます。対面イベントのメンバーシップ、クラスパス、定期配送など、アプリ外で利用するサービスのサブスクリプション販売にご活用ください。
Google Playはデジタル商品やサービスに対して自社の課金システムの使用を義務付けています。物理的な商品や物理的なサービスに対しては、自社の課金システムの使用を禁じています(決済ポリシー)。Stripeを通じたアプリ内支払いは、物理的な商品、またはユーザーがアプリ外で利用するサービスに対して行うものです。
仕組み
- アプリがバックエンドからStripeの価格情報を取得し、それをカスタムタグとしてフローに渡してフローを表示します。
- ユーザーがフロー内のボタンをタップすると、そのボタンがカスタムアクションをトリガーし、アプリがアクションIDを受け取ります。
- アプリがバックエンドにStripeサブスクリプションの作成を依頼します。バックエンドはサブスクリプションのメタデータにユーザーIDとフローのバリエーションIDを追加します。
- アプリがフローの上にPaymentSheetを開き、ユーザーがサブスクリプションの初回請求を支払います。
- StripeがAdaptyにWebhookを送信します。AdaptyはユーザーIDを持つプロファイルにアクセスレベルを付与し、購入をフローのバリアントに帰属させます。
- アプリがフローを閉じ、プロファイルにアクセスレベルが付与されるまで待機します。
始める前に
以下を確認してください:
- StripeをAdaptyアプリに接続する: テストモードと本番モードそれぞれでStripeをAdaptyに接続するの手順に従ってください。Profile creation behaviorは**Use customer_user_id from metadata (default)**のまま維持してください。
- 各プランのStripeプロダクトと価格: 月次・年次などの定期課金価格を設定してStripeでプロダクトを作成する。
- 各Stripe価格に対応するAdaptyプロダクト: StripeのプロダクトIDと価格IDをAdaptyプロダクトに追加し、そのプランで解除されるアクセスレベルを割り当てます。アクセスレベルはアプリ内のデジタル機能ではなく、アクティブなメンバーシップなどサービスを利用する権利を表します。Adaptyプロダクトがなければ、Adaptyは購入を記録しません。
- Adapty Android SDK 4.0.0以降(
android-uiモジュール含む): StripeとAdaptyを接続したAdaptyアプリのキーでSDKをアクティベートします。AdaptyはそのアプリのStripe Webhookのみ受信します。ユーザーを識別する際はカスタマーユーザーIDを使用し、ログイン済みで識別済みのユーザーにのみこのフローを表示してください。AdaptyはこのIDを使ってアクセスレベルが付与されるプロファイルを特定します。 - Stripe Android SDK 20.46.0以降(
com.stripe:stripe-android)をアプリに組み込む。StripeドキュメントのAccept a paymentを参照してください。 - Stripe APIを呼び出せるバックエンド: Stripeのシークレットキー、またはCustomerとSubscriptionの書き込み権限を持つ独自の制限付きキーを使用します。Adapty用に生成した制限付きキーは流用しないでください。それはAdapty専用のキーであり、バックエンドが必要とする書き込み権限がありません。キーはサーバー上で管理してください。
フローにStripeの価格を表示する
フローはカスタムタグを通じてStripeの価格を表示します。カスタムタグとは、フローを表示する際にアプリがフローに渡すテキスト値です。Adaptyはカスタムタグの値を整形しないため、「$29.00」のようにユーザーが見る形式で各価格を渡してください。
- Flow & ペイウォールビルダーで、各価格に対してString 変数を作成し(例:
stripe_monthly_price、stripe_annual_price)、Value comes from outside the app を選択します。各変数の Initial value に現在の価格を設定してください。アプリが価格を読み込めない場合、ユーザーにはこの初期値が表示されるため、初期値は Stripe の価格と同じにしておいてください。 - 各タグをテキスト要素に挿入します(プランボタンのラベルなど)。
- アプリ内で、フローを読み込む前にバックエンドから価格を取得します。
AdaptyFlowView.showFlowまたはAdaptyFlowScreenのtagResolverパラメーターに価格を渡します。
以下の関数はフローを読み込み、Stripe の価格情報を使ったタグリゾルバーを作成します。また、フローの variationId を返します。これは、バックエンドがこの ID を Stripe サブスクリプションに書き込むために使用します。フローの表示方法はフローから PaymentSheet を開くを参照してください。
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)
}
}
}Backend はバックエンドのエンドポイント(バックエンドでサブスクリプションを作成するを参照)のクライアントです。Adapty SDK はコールバックで結果を返すため、awaitAdapty はこのガイドのコルーチン向けにコールバックをサスペンド呼び出しに変換します。
PaymentSheet を開くボタンを追加する
Stripe プランを販売する各ボタンには、カスタムアクションを設定します。アプリはアクション ID を受け取り、そのプランの PaymentSheet を開きます。
- フロー&ペイウォールビルダーで、各 Stripe プランにボタンを追加します。
- 各ボタンに Custom Action アクションを割り当て、
buy_stripe_monthlyやbuy_stripe_annualなどのアクション ID を入力します。 - フローを公開し、プレースメントに追加します。
あなたのアプリは、各アクション ID をプランにマッピングします。フローはアクションと共にアプリにデータを送信しないため、アクション ID でプランを識別する必要があります。
バックエンドでサブスクリプションを作成する
PaymentSheet は、バックエンドが作成した Stripe オブジェクトに対して支払いを行います。このガイドでは、バックエンドで Stripe のサブスクリプションを作成し、PaymentSheet でそのサブスクリプションの初回請求書の支払いを行います。バックエンドはサブスクリプションのメタデータに 2 つのキーを設定します:
customer_user_id: AdaptyにおけるユーザーのカスタマーユーザーID。AdaptyはこのIDを持つプロファイルにアクセスレベルを付与します。variation_id: アプリがバックエンドに送信するフローのバリエーションID。Adaptyはこのフローバリアント、そのプレースメント、およびA/B テストに収益を紐付けます。
サブスクリプションや請求書を紐付けずに単独で作成したPaymentIntentの支払いは、Adaptyには記録されません。ユーザーが支払いを完了しても、アクセスレベルは付与されません。
カスタムタグのフォーマットされた価格を返す最初のエンドポイントと、サブスクリプションを作成して PaymentSheet が必要とする値を返す2番目のエンドポイントを作成します。2番目のエンドポイントはサブスクリプションを作成する前に、ユーザーがすでにアクティブなサブスクリプションを持っていないかを確認するため、同じプランに対して二重に支払うことはできません。
この例では、package.json に "type": "module" を設定した Node.js の ES モジュール、Express、およびバージョン 18 以降の stripe ライブラリ を使用しています。db はご自身のデータベースに置き換えてください:
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 を参照してください。
コードはクライアントシークレットを 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つのエンドポイントを呼び出します。バックエンドの要件に従い、各リクエストにユーザーの認証情報を含めてください:
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を開く
フロー内のボタンがカスタムアクションをトリガーしたときにアプリがPaymentSheetを開き、支払いが成功したらフローを閉じます。
- カスタムアクションIDをプランにマッピングします。バックエンドの応答待ちやPaymentSheetの表示中は、タップと フローのクローズボタンを無視してください。これにより、1回のタップで1つのサブスクリプションが作成されます。
- バックエンドにサブスクリプションをリクエストし、プランとフローの
variationIdを渡します。 - フローの上にPaymentSheetを表示し、その結果を処理します:
- Completed:フローを閉じます。閉じた後、アクセスレベルの付与を待機します。
- Canceled:何もしません。ユーザーはフローに留まり、別のプランを選択できます。
- Failed:エラーを表示します。ユーザーはフローに留まり、再試行できます。
- フローのクローズアクションを処理します。あなたのアクションハンドラーはSDKのデフォルトハンドラーを置き換えます(デフォルトはフローを閉じます)。URL オープンアクションの場合は、URLを開くデフォルトハンドラーを呼び出してください。
- PaymentSheetはアクティビティの
onCreate、またはコンポーザブルではコンポジションのたびに作成してください。StripeはアクティビティのリザルトにPaymentSheetを登録しますが、アクティビティは起動後に登録できません。
ステップ1〜3はViewsとJetpack Composeで共通なので、このガイドではそれらを1つのViewModelにまとめています。ViewModelは、ロードされたフローと支払い状態も保持します。これにより、たとえばPaymentSheetが開いている状態でユーザーが画面を回転させた場合など、Androidがアクティビティを再作成しても状態が維持されます。
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 を継承しているため、オーバーライドされていないイベントはデフォルトの処理が維持されます。
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 を表示します:
onCreate で PaymentSheet を作成し、画面上のコンテナにフローを表示します。Android がアクティビティを再生成したときにフローの状態を保持できるよう、フロービューに安定した ID を付与してください:
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,
)
}
}フローがGoogle Playのプロダクトも販売している場合、Adapty SDKが購入処理を行います。購入イベントに対応するには、フローイベントの処理で説明されているように、StripeFlowEventListenerのイベントメソッドをオーバーライドしてください。
支払い後にアクセスを解放する
支払いが完了すると、AdaptyはStripeのWebhookを受信し、数秒以内にアクセスレベルを付与します。SDKはプロファイルを1分に1回更新するため、アクセスレベルが有効になるまでプロファイルをリクエストし続けてください。
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のウェブフック設定でAdaptyウェブフックエンドポイントへの配信を確認してください。
支払い後にウェルカム画面などの確認画面を表示するには、アクセスレベルが有効になったタイミングでアプリ側から表示してください。また、確認画面を2つ目のフローとして作成し、専用のプレースメントに追加して、最初のフローが閉じた後に表示する方法もあります。この2つ目のフローの設定方法については、購入結果への対応をご覧ください。
ユーザーがサブスクリプションを管理できるようにする
Stripe のサブスクリプションは、Google Play ストアアプリのユーザーのサブスクリプション一覧には表示されません。ユーザーがキャンセルや支払い方法の変更を行えるようにするには、アカウント画面などにボタンを追加し、Stripe カスタマーポータルを開けるようにしてください。バックエンドでユーザーの Stripe カスタマー向けにポータルセッションを作成し、その URL を返します。
ユーザーがキャンセルすると、StripeはAdaptyに通知し、AdaptyはアクセスレベルをAdaptyは更新します。即時キャンセルと期間終了時のキャンセルをAdaptyがどのように扱うかについては、キャンセルを参照してください。
インテグレーションをテストする
Adapty アプリに接続された Stripe のテストモードを使用してください:
- Stripeに接続したAdaptyアプリのAdapty SDKキーを使ってアプリを起動します。
- フローを開きます。ボタンにはカスタムタグの初期値ではなく、アプリが渡した価格が表示されるはずです。
- Stripeプランのボタンをタップします。PaymentSheetでStripeのテストカード
4242 4242 4242 4242、未来の有効期限、任意のCVCを使って支払います。 - フローが閉じ、数秒以内にプロファイルのアクセスレベルがアクティブになることを確認します。
- Adapty ダッシュボードで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の結果を受け取らない: Stripeの決済が成功・キャンセル・失敗した後、フローは別の画面に遷移できません。アプリがフローを閉じ、次に表示するコンテンツを制御します。
- カスタムタグの価格はテキストとして扱われる: フローはアプリが渡したカスタムタグの値をそのまま表示するため、週ごとの価格や割引率などの値を自動計算しません。それぞれの値を個別のタグとして渡してください。
- カスタムタグの値はフローが開いている間は固定される: 新しい価格を表示するには、フローを再度読み込んでください。