在 Android 流程中接受 Stripe 支付

您可以在 Flow & Paywall Builder 中创建流程,并通过该流程销售 Stripe 订阅。流程会展示您的 Stripe 价格,其中的按钮会在流程上方打开 Stripe 的 PaymentSheet。支付完成后,Stripe 会通知 Adapty。Adapty 会向用户授予访问等级,并将收入归因到对应的流程、版位及 A/B 测试实验变体。此方案适用于销售用户在应用外使用的服务订阅,例如线下活动会员资格、课程通票或定期配送服务。

Important

Google Play 对数字商品和服务要求使用其自有的结算系统,但不允许通过其结算系统购买实体商品和实体服务(付款政策)。通过 Stripe 进行的应用内支付适用于实体商品,以及用户在应用外消费的服务。

工作原理

  1. 您的应用从后端获取 Stripe 价格,然后将其作为自定义标签传入流程并展示该流程。
  2. 用户点击流程中的按钮,该按钮触发自定义操作,您的应用接收到操作 ID。
  3. 您的应用请求后端创建 Stripe 订阅,后端将用户 ID 和流程的 variation ID 添加到订阅的元数据中。
  4. 您的应用在流程上方打开 PaymentSheet,用户支付订阅的首张账单。
  5. Stripe 向 Adapty 发送 webhook,Adapty 将访问等级授予对应用户 ID 的用户画像,并将购买归因到相应的流程实验变体。
  6. 您的应用关闭流程并等待用户画像获得该访问等级。

开始之前

确保您已完成以下准备工作:

  1. 将 Stripe 连接到您的 Adapty 应用:分别为测试模式和正式模式按照将 Stripe 连接到 Adapty 操作。将 Profile creation behavior 保持为 Use customer_user_id from metadata (default)。
  2. 为每个套餐创建 Stripe 产品和价格:在 Stripe 上创建产品,并设置周期性价格,例如月付或年付。
  3. 为每个 Stripe 价格创建 Adapty 产品:将 Stripe 产品 ID 和价格 ID 添加到 Adapty 产品,并分配该套餐对应的访问等级。访问等级代表服务权限(例如有效会员资格),而非应用内的数字功能。若未创建 Adapty 产品,Adapty 将不会记录该购买。
  4. Adapty Android SDK 4.0.0 或更高版本,并包含 android-ui 模块:使用已连接 Stripe 的 Adapty 应用密钥激活 SDK。Adapty 仅接收该应用的 Stripe Webhook。请通过 customer user ID 识别用户,并仅向已登录且已识别的用户展示此流程。Adapty 使用此 ID 查找将获得访问等级的用户画像。
  5. Stripe Android SDK 20.46.0 或更高版本(com.stripe:stripe-android):请参阅 Stripe 文档中的接受付款。
  6. 能够调用 Stripe API 的后端:使用您的 Stripe 密钥,或使用您自己创建的、具有 Customers 和 Subscriptions 写权限的受限密钥。请勿复用为 Adapty 生成的受限密钥——那是 Adapty 专用的密钥,不具备您后端所需的写权限。请务必将密钥保存在服务器端。

在流程中显示 Stripe 价格

流程通过自定义标签显示 Stripe 价格。自定义标签是应用在展示流程时传入的文本值。Adapty 不会对自定义标签的值进行任何格式化处理,因此请按照用户实际看到的格式传入每个价格,例如”$29.00”。

  1. 在 Flow & Paywall Builder 中,为每个价格创建一个 String 变量,例如 stripe_monthly_price 和 stripe_annual_price,并选择 Value comes from outside the app。将每个变量的 Initial value 设置为当前价格。如果应用无法加载价格,用户将看到初始值,因此请确保初始值与 Stripe 价格保持一致。
  2. 将每个标签插入文本元素,例如方案按钮的标签。
  3. 在应用中,在加载流程之前先从后端获取价格。
  4. 将价格通过 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。

  1. 在 Flow & Paywall Builder 中,为每个 Stripe 方案添加一个按钮。
  2. 为每个按钮分配 Custom Action 操作,并输入操作 ID,例如 buy_stripe_monthly 和 buy_stripe_annual。
  3. 发布流程,并将其添加到版位。

您的应用将每个操作 ID 映射到一个方案。流程不会随操作向您的应用发送任何数据,因此操作 ID 必须能够标识该方案。

在后端创建订阅

PaymentSheet 会为后端创建的 Stripe 对象付款。在本指南中,后端创建一个 Stripe 订阅,PaymentSheet 负责支付该订阅的首张发票。后端需要在订阅的元数据中设置两个键:

  • customer_user_id:用户在 Adapty 中的 customer user ID。Adapty 将访问等级授予具有此 ID 的用户画像。
  • variation_id:流程的实验变体 ID,由你的应用发送至后端。Adapty 将收入归因到该流程实验变体、其版位及对应的 A/B 测试。
Warning

对于你单独创建的 PaymentIntent(不关联任何订阅或发票),Adapty 不会记录付款。用户完成支付后,不会获得访问等级。

创建两个端点。第一个返回自定义标签的格式化价格。第二个创建订阅并返回 PaymentSheet 所需的值。在创建订阅之前,第二个端点会验证用户是否已有活跃订阅,以防止用户为同一套餐重复付费。

本示例使用 Node.js 的 ES 模块(package.json 中设置 "type": "module")、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。

在你的应用中,调用这两个端点。根据后端要求,每个请求都需携带用户的身份验证信息:


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,并在支付成功后关闭该流程:

  1. 将自定义操作 ID 映射到套餐。在应用等待后端响应或显示 PaymentSheet 期间,忽略用户点击以及流程关闭按钮。这样每次点击只会创建一个订阅。
  2. 向后端请求订阅,并传入套餐和流程的 variationId。
  3. 在流程上方展示 PaymentSheet,并处理其结果:
    • Completed:关闭流程。关闭后,等待访问等级生效。
    • Canceled:不执行任何操作。用户留在流程中,可以选择其他套餐。
    • Failed:显示错误信息。用户留在流程中,可以重试。
  4. 处理流程的关闭操作。你的操作处理器会替换 SDK 的默认处理器(负责关闭流程)。对于打开 URL 的操作,请调用默认处理器来打开该 URL。
  5. 在 Activity 的 onCreate 中,或在 Composable 的每次重组时创建 PaymentSheet。Stripe 会将 PaymentSheet 注册为 Activity Result,而 Activity 启动后便无法再注册。

步骤 1 至 3 在 Views 和 Jetpack Compose 中完全相同,因此本指南将它们统一放在一个 ViewModel 中。ViewModel 还会在 Android 重建 Activity 时(例如用户在 PaymentSheet 打开时旋转屏幕)保留已加载的流程和支付状态:


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,并在屏幕上方的容器中展示流程。为流程视图指定一个稳定的 ID,以便在 Android 重新创建 Activity 时保留流程的状态:


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 每分钟刷新一次用户画像,因此请持续请求用户画像,直到访问等级生效:


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 的 Webhook 设置中验证 Adapty Webhook 端点的投递情况。

如需在支付完成后显示确认页面(例如欢迎界面),请在访问等级激活时从应用中展示。你也可以将该页面构建为第二个流程,添加到独立的版位,并在第一个流程关闭后展示。响应购买结果介绍了如何为此设置第二个流程。

让用户管理订阅

Stripe 订阅不会出现在 Google Play 商店应用的用户订阅列表中。为了让用户能够取消订阅或更改支付方式,请在应用中添加一个按钮(例如在账户页面),用于打开 Stripe 客户门户。您的后端需要为该用户的 Stripe 客户创建一个门户会话,并返回其 URL。

当用户取消订阅时,Stripe 会通知 Adapty,Adapty 随即更新访问等级。有关 Adapty 如何处理即时取消和到期取消的详细说明,请参阅取消。

测试集成

使用 Stripe 的测试模式,连接到你的 Adapty 应用:

  1. 使用已连接到 Stripe 的 Adapty 应用的 SDK 密钥运行你的应用。
  2. 打开流程。按钮应显示你的应用传入的价格,而不是自定义标签的初始值。
  3. 点击 Stripe 方案按钮。在 PaymentSheet 中,使用 Stripe 测试卡 4242 4242 4242 4242、任意未来到期日期和任意 CVC 完成支付。
  4. 验证流程已关闭,且用户画像的访问等级在几秒内变为激活状态。
  5. 在 Adapty 看板中,打开 Event Feed。购买事件应包含 store: stripe、你的流程的 flow_id 和 flow_name、等于你的应用发送的 variationId 的 flow_variation_id,以及 developer_id 中的版位 ID。对于 Stripe 购买,variation_id 与 flow_variation_id 的值相同。

测试模式下的购买环境为 Sandbox。这些购买记录会出现在 Event Feed 和用户画像中,但不会计入数据分析或流程的数据图表,因为两者仅统计正式购买。

如果购买记录未出现在 Adapty 中,请确认以下几点:您的应用使用的 SDK 密钥是否对应已连接 Stripe 的 Adapty 应用、是否已为 Stripe 价格创建相应的 Adapty 产品,以及订阅的 metadata 中是否包含 customer_user_id。另请参阅 Stripe 集成指南中的故障排查章节。

限制

  • 流程无法接收 Stripe 结果:流程在 Stripe 支付成功、取消或失败后无法跳转到其他页面。需由您的应用关闭流程并决定后续展示内容。
  • 自定义标签中的价格为纯文本:流程按应用传入的自定义标签值原样展示,不会自动计算其他数值(例如每周价格或折扣)。请将每个数值单独作为一个标签传入。
  • 流程打开期间自定义标签值保持不变:如需展示新价格,请重新加载流程。