Accept Stripe payments in Android flows
You can sell Stripe subscriptions from a flow that you build in the Flow & Paywall Builder. The flow shows your Stripe prices, and its buttons open Stripe’s PaymentSheet over the flow. After the payment, Stripe notifies Adapty. Adapty grants the access level to the user and attributes the revenue to the flow, its placement, and its A/B test variation. Use this setup to sell subscriptions to services that users consume outside your app, such as memberships to in-person events, class passes, or recurring deliveries.
Google Play requires its billing system for digital goods and services. It doesn’t allow its billing system for physical goods and physical services (Payments policy). An in-app payment through Stripe is for physical goods and for services that users consume outside the app.
How it works
- Your app gets the Stripe prices from your backend. Then it passes them to the flow as custom tags, and shows the flow.
- The user taps a button in the flow. The button triggers a custom action, and your app receives the action ID.
- Your app asks your backend to create a Stripe subscription. Your backend adds the user’s ID and the flow’s variation ID to the subscription’s metadata.
- Your app opens PaymentSheet over the flow, and the user pays the subscription’s first invoice.
- Stripe sends a webhook to Adapty. Adapty grants the access level to the profile with the user’s ID, and attributes the purchase to the flow variation.
- Your app closes the flow and waits until the profile has the access level.
Before you start
Make sure that you have:
- Stripe connected to your Adapty app: Follow Connect Stripe to Adapty, for test mode and for live mode. Keep Profile creation behavior set to Use customer_user_id from metadata (default).
- A Stripe product and price for each plan: Create the products on Stripe with recurring prices, for example monthly or annual.
- An Adapty product for each Stripe price: Add the Stripe product ID and price ID to an Adapty product, and assign the access level that the plan unlocks. The access level stands for the right to the service, such as an active membership, not for digital features in your app. Without the Adapty product, Adapty doesn’t record the purchase.
- The Adapty Android SDK 4.0.0 or later, with the
android-uimodule: Activate the SDK with the key of the Adapty app that you connected to Stripe. Adapty receives Stripe’s webhooks only for that app. Identify users by a customer user ID, and show this flow only to users who are logged in and identified. Adapty uses this ID to find the profile that gets the access level. - The Stripe Android SDK 20.46.0 or later (
com.stripe:stripe-android) in your app. See Accept a payment in the Stripe docs. - A backend that can call the Stripe API with your Stripe secret key, or with a restricted key of your own that can write Customers and Subscriptions. Don’t reuse the restricted key that you generated for Adapty: it’s Adapty’s key, and it doesn’t have the write permissions that your backend needs. Keep the key on your server.
Show Stripe prices in the flow
The flow shows Stripe prices through custom tags. A custom tag is a text value that your app passes to the flow when it shows the flow. Adapty doesn’t format a custom tag value, so pass each price in the form that users see, such as “$29.00”.
- In the Flow & Paywall Builder, create a String variable for each price, for example
stripe_monthly_priceandstripe_annual_price, and select Value comes from outside the app. Set each variable’s Initial value to your current price. Users see the initial value if your app can’t load the prices, so keep the initial values equal to your Stripe prices. - Insert each tag into a text element, such as the label of a plan button.
- In your app, get the prices from your backend before you load the flow.
- Pass the prices in the
tagResolverparameter ofAdaptyFlowView.showFloworAdaptyFlowScreen.
The following function loads the flow, and creates a tag resolver with your Stripe prices. It also returns the flow’s variationId, because your backend writes this ID into the Stripe subscription. You show the flow in Open PaymentSheet from the flow.
import androidx.core.os.LocaleListCompat
import com.adapty.Adapty
import com.adapty.ui.AdaptyUI
import com.adapty.ui.listeners.AdaptyUiTagResolver
import com.adapty.utils.AdaptyResult
import com.adapty.utils.ResultCallback
import java.io.IOException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlinx.coroutines.suspendCancellableCoroutine
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 is the client for your backend’s endpoints, from Create the subscription on your backend. The Adapty SDK returns results in callbacks, so awaitAdapty turns a callback into a suspend call for the coroutines in this guide.
Add buttons that open PaymentSheet
Each button that sells a Stripe plan triggers a custom action. Your app receives the action ID and opens PaymentSheet for that plan.
- In the Flow & Paywall Builder, add a button for each Stripe plan.
- Assign the Custom Action action to each button, and enter an action ID, such as
buy_stripe_monthlyandbuy_stripe_annual. - Publish the flow, and add it to a placement.
Your app maps each action ID to a plan. The flow doesn’t send your app any data with the action, so the action ID must identify the plan.
Create the subscription on your backend
PaymentSheet pays for a Stripe object that your backend creates. In this guide, your backend creates a Stripe subscription, and PaymentSheet pays the subscription’s first invoice. Your backend sets two keys in the subscription’s metadata:
customer_user_id: The customer user ID of the user in Adapty. Adapty grants the access level to the profile with this ID.variation_id: The flow’s variation ID, which your app sends to the backend. Adapty attributes the revenue to this flow variation, its placement, and its A/B test.
Adapty doesn’t record a payment for a PaymentIntent that you create on its own, without a subscription or an invoice. The user pays, but doesn’t get the access level.
Create two endpoints. The first returns the formatted prices for the custom tags. The second creates the subscription and returns the values that PaymentSheet needs. Before it creates a subscription, the second endpoint verifies that the user has no active one, so a user can’t pay twice for the same plan.
This example uses Node.js with ES modules ("type": "module" in package.json), Express, and the stripe library version 18 or later. Replace db with your own database:
import express from 'express';
import Stripe from 'stripe';
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);With payment_behavior: 'default_incomplete', the subscription waits for the first payment. Stripe activates it when the user pays in PaymentSheet. If the user closes PaymentSheet without paying, Stripe expires the subscription after about 23 hours, and Adapty doesn’t record it. For the full Stripe setup, see Build a subscriptions integration in the Stripe docs.
The code reads the client secret from latest_invoice.confirmation_secret, which needs Stripe API version 2025-03-31.basil or later. The stripe library uses this version from version 18. If you call the Stripe API without the library, set the Stripe-Version header. On an earlier API version, expand latest_invoice.payment_intent and read payment_intent.client_secret instead.
In your app, call the two endpoints. Send your user’s authentication with each request, as your backend requires:
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONException
import org.json.JSONObject
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.") }
}Open PaymentSheet from the flow
Your app opens PaymentSheet when a button in the flow triggers a custom action, and closes the flow when the payment succeeds:
- Map the custom action ID to a plan. Ignore taps, and the flow’s close button, while your app waits for the backend or shows PaymentSheet. Then one tap creates one subscription.
- Ask your backend for a subscription, and pass the plan and the flow’s
variationId. - Present PaymentSheet over the flow, and handle its result:
- Completed: Close the flow. After it closes, wait for the access level.
- Canceled: Do nothing. The user stays on the flow and can choose another plan.
- Failed: Show the error. The user stays on the flow and can try again.
- Handle the flow’s close action. Your action handler replaces the SDK’s default one, which closes the flow. For the open-URL action, call the default handler, which opens the URL.
- Create PaymentSheet in your activity’s
onCreate, or in your composable on every composition. Stripe registers PaymentSheet for an activity result, and an activity can’t register after it starts.
Steps 1–3 are the same in Views and Jetpack Compose, so this guide puts them in one ViewModel. The ViewModel also keeps the loaded flow and the payment state when Android recreates the activity, for example when the user rotates the screen while PaymentSheet is open:
import android.app.AlertDialog
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.adapty.errors.AdaptyError
import com.stripe.android.PaymentConfiguration
import com.stripe.android.paymentsheet.PaymentSheet
import com.stripe.android.paymentsheet.PaymentSheetResult
import java.io.IOException
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
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()
}The flow’s event listener passes the flow’s actions to StripeCheckout. It extends AdaptyFlowDefaultEventListener, so the events that it doesn’t override keep their default handling:
import android.content.Context
import com.adapty.ui.AdaptyUI
import com.adapty.ui.listeners.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)
}
}
}Then show the flow, and present PaymentSheet when StripeCheckout asks for it:
Create PaymentSheet in onCreate, and show the flow in a container over your screen. Give the flow view a stable ID, so that it keeps the flow’s state when Android recreates the activity:
import android.os.Bundle
import android.widget.Button
import android.widget.FrameLayout
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.adapty.ui.AdaptyFlowView
import com.stripe.android.paymentsheet.PaymentSheet
import kotlinx.coroutines.launch
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,
)
}
}If your flow also sells Google Play products, the Adapty SDK makes the purchases. To respond to the purchase events, override the event methods in StripeFlowEventListener, as described in Handle flow events.
Unlock access after the payment
After the payment, Adapty receives Stripe’s webhook and grants the access level within a few seconds. The SDK refreshes the profile once a minute, so request the profile until the access level is active:
import com.adapty.Adapty
import com.adapty.errors.AdaptyError
import com.adapty.models.AdaptyProfile
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.delay
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
}Usually the access level is active within a few seconds. If it isn’t active after 60 seconds, verify the deliveries of the Adapty webhook endpoint in Stripe’s webhook settings.
To show a confirmation after the payment, such as a welcome screen, show it from your app when the access level is active. You can also build the screen as a second flow, add it to its own placement, and show it after the first flow closes. Respond to purchase outcomes shows how to set up a second flow for this.
Let users manage the subscription
A Stripe subscription doesn’t appear in the user’s subscriptions in the Google Play Store app. To let users cancel or change their payment method, add a button to your app, for example on the account screen, that opens the Stripe customer portal. Your backend creates a portal session for the user’s Stripe customer and returns its URL.
When a user cancels, Stripe notifies Adapty, and Adapty updates the access level. For how Adapty treats immediate and end-of-period cancellations, see Cancellations.
Test the integration
Use Stripe’s test mode, connected to your Adapty app:
- Run your app with the Adapty SDK key of the Adapty app that you connected to Stripe.
- Open the flow. The buttons should show the prices that your app passes, not the initial values of the custom tags.
- Tap a Stripe plan button. In PaymentSheet, pay with the Stripe test card
4242 4242 4242 4242, any future expiration date, and any CVC. - Verify that the flow closes and that the profile’s access level becomes active within a few seconds.
- In the Adapty Dashboard, open the Event Feed. The purchase event should have
store:stripe, theflow_idandflow_nameof your flow, aflow_variation_idequal to thevariationIdthat your app sent, and your placement ID indeveloper_id. For a Stripe purchase,variation_idhas the same value asflow_variation_id.
Test-mode purchases have the Sandbox environment. They appear in the Event Feed and on the profile, but not in analytics or in the flow’s metrics, which count only production purchases.
If the purchase doesn’t appear in Adapty, verify that your app uses the SDK key of the Adapty app connected to Stripe, that an Adapty product exists for the Stripe price, and that the subscription’s metadata has customer_user_id. Also see Troubleshooting in the Stripe integration guide.
Limitations
- The flow doesn’t receive the Stripe result: The flow can’t go to another screen after a successful, canceled, or failed Stripe payment. Your app closes the flow and shows what comes next.
- Prices in custom tags are text: The flow shows a custom tag value as your app passes it, and doesn’t calculate other values from it, such as a price per week or a discount. Pass each of these values as its own tag.
- Custom tag values are fixed while the flow is open: To show new prices, load the flow again.