Accept Stripe payments in Flutter 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. If you also sell a plan for a real-world service as an App Store product, you can add Stripe to the same flow as another way to pay for it.
The App Store requires in-app purchases for digital content and features (guideline 3.1.1), and Google Play requires its billing system for them (Payments policy). An in-app payment through Stripe is for physical goods and for services that users consume outside the app (guideline 3.1.3(e)). Google Play doesn’t allow its billing system for these purchases, such as gym memberships and tickets for live events.
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 Flutter SDK 4.0.0 or later: 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.
Starting from SDK 4.4, flows require iOS 16 or later. On iOS 15,
AdaptyUI().createFlowView()andAdaptyUIFlowPlatformViewreport an error withAdaptyErrorCode.platformNotSupported. When your app receives this error, show your own content instead of the flow, such as a custom paywall. -
The
flutter_stripepackage in your app, with the Android and iOS setup from its README. On Android,flutter_stripeneeds aMainActivitythat extendsFlutterFragmentActivity, with a theme that descends fromTheme.AppCompat. -
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 loads 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
customTagsparameter ofAdaptyUIFlowPlatformView.
The following function loads the flow and builds its custom tags with your Stripe prices. It also returns the flow, because your backend writes the flow’s variationId into the Stripe subscription. You show the flow in Open PaymentSheet from the flow.
import 'package:adapty_flutter/adapty_flutter.dart';
typedef StripeFlow = ({AdaptyFlow flow, Map<String, String> customTags});
Future<StripeFlow> loadStripeFlow() async {
// If the prices fail to load, the flow shows the tags' initial values
final prices = await Backend.fetchPrices().catchError((Object _) => <String, String>{});
final flow = await Adapty().getFlow(placementId: 'YOUR_PLACEMENT_ID');
return (
flow: flow,
customTags: {
'stripe_monthly_price': ?prices['monthly'],
'stripe_annual_price': ?prices['annual'],
},
);
}Backend is the client for your backend’s endpoints, from Create the subscription on your backend.
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.
Add Stripe as another way to pay for App Store products
Use this setup only for plans that are physical goods or services that users consume outside the app (guideline 3.1.3(e)), such as memberships to in-person events. For digital content or features, offer another way to pay through a web paywall.
This setup is for iOS only. Google Play doesn’t allow its billing system for physical goods and services (Payments policy), so on Android, sell these plans only through Stripe.
The flow shows your App Store products as usual, and a link such as “Pay another way” opens PaymentSheet. The App Store purchase buttons keep working without changes.
- Assign the Custom Action action to the link, with an action ID such as
pay_with_stripe. - For each App Store product in the flow, create a Stripe price for the same plan.
- In your app, map each App Store product ID to its Stripe plan.
- Store the product that the user selects. The flow reports each selection to the
onDidSelectProductcallback ofAdaptyUIFlowPlatformView. A flow built in the Flow & Paywall Builder doesn’t report the product that is selected by default, so start with the product that you set as selected in the builder. If the variations of an A/B test select different products, store the default for each variation. - When
onDidPerformActionreceivespay_with_stripe, call_payAndClosefrom Open PaymentSheet from the flow with the Stripe plan of the stored product.
The flow shows the App Store prices of these products, which differ by storefront. PaymentSheet charges the Stripe price. To show users the Stripe price before they tap, pass it as a custom tag and show it in each plan’s card, for example “or $29.00/month by card”. Custom tag values don’t change while the flow is open, so one link can’t show the price of the selected 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. This example uses the http package:
import 'dart:convert';
import 'package:http/http.dart' as http;
class Subscription {
const Subscription({
required this.subscriptionId,
required this.clientSecret,
required this.publishableKey,
});
factory Subscription.fromJson(Map<String, dynamic> json) => Subscription(
subscriptionId: json['subscriptionId'] as String,
clientSecret: json['clientSecret'] as String,
publishableKey: json['publishableKey'] as String,
);
final String subscriptionId;
final String clientSecret;
final String publishableKey;
}
class BackendException implements Exception {
const BackendException(this.message);
final String message;
@override
String toString() => message;
}
abstract final class Backend {
static const baseUrl = 'https://YOUR_BACKEND';
static Future<Map<String, String>> fetchPrices() async {
final json = await _send(http.get(Uri.parse('$baseUrl/prices')));
return (json as Map<String, dynamic>).cast<String, String>();
}
static Future<Subscription> createSubscription({
required String plan,
required String variationId,
}) async {
final json = await _send(http.post(
Uri.parse('$baseUrl/subscriptions'),
headers: {
'Content-Type': 'application/json',
// add your authentication header
},
body: jsonEncode({'plan': plan, 'variationId': variationId}),
));
return Subscription.fromJson(json as Map<String, dynamic>);
}
static Future<Object?> _send(Future<http.Response> request) async {
final response = await request;
if (response.statusCode != 200) {
// Use the backend's message when the response has one
String? message;
try {
message = (jsonDecode(response.body) as Map<String, dynamic>)['error'] as String?;
} catch (_) {}
throw BackendException(message ?? 'The server returned HTTP ${response.statusCode}.');
}
return jsonDecode(response.body);
}
}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, the flow’s close button, and its links 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 in a Flutter dialog, which opens over the embedded flow.
view.showDialogdoesn’t work for an embedded flow. The user stays on the flow and can try again.
- Handle the flow’s close and open-URL actions, and the Android system Back button. With
onDidPerformActionset, the SDK doesn’t open URLs for this flow. To close the flow, remove the widget:view.dismiss()fails for an embedded flow.
This guide puts steps 2 and 3 in one class:
import 'package:adapty_flutter/adapty_flutter.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
class StripeCheckout {
// Custom action IDs from the flow, mapped to your backend's plan keys
static const plans = {
'buy_stripe_monthly': 'monthly',
'buy_stripe_annual': 'annual',
};
bool _isPaying = false;
bool get isPaying => _isPaying;
/// Opens PaymentSheet for a plan over the flow. Returns `true` when the user paid.
Future<bool> pay(
String plan,
AdaptyUIFlowView view, {
required Future<void> Function(String message) showError,
}) async {
if (_isPaying) return false;
_isPaying = true;
try {
final subscription = await Backend.createSubscription(
plan: plan,
variationId: view.variationId,
);
Stripe.publishableKey = subscription.publishableKey;
// The URL scheme that you register in your iOS app
Stripe.urlScheme = 'your-app';
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: subscription.clientSecret,
merchantDisplayName: 'YOUR_BUSINESS_NAME',
// For payment methods that redirect to another app, such as bank apps
returnURL: 'your-app://stripe-redirect',
),
);
await Stripe.instance.presentPaymentSheet();
return true;
} on StripeException catch (e) {
if (e.error.code == FailureCode.Canceled) return false; // the user stays on the flow
await showError(e.error.localizedMessage ?? e.error.message ?? 'Unknown error');
return false;
} catch (e) {
await showError(e.toString());
return false;
} finally {
_isPaying = false;
}
}
}On iOS, PaymentSheet returns to your app through the return URL after payment methods that open another app. Register the URL scheme in your app’s ios/Runner/Info.plist, as described in Set up a return URL in the Stripe docs. Use the same scheme in Stripe.urlScheme and in returnURL. When iOS opens your app with this URL, flutter_stripe passes the URL to Stripe. If your app sets FlutterDeepLinkingEnabled to true in Info.plist, pass the URL to Stripe in your deep-link handler:
import 'package:flutter_stripe/flutter_stripe.dart';
// In your deep-link handler, for URLs with your scheme
Future<void> handleStripeRedirect(Uri uri) async {
await Stripe.instance.handleURLCallback(uri.toString());
}On Android, PaymentSheet returns to your app without a return URL.
Then show the flow, and pass its actions to StripeCheckout. Render the flow with the AdaptyUIFlowPlatformView widget in its own route, and handle its actions in onDidPerformAction. Because the flow is a widget in your Flutter route, PaymentSheet’s result reaches your app while the flow is open. To close the flow, pop the route:
import 'dart:io';
import 'package:adapty_flutter/adapty_flutter.dart';
import 'package:flutter/material.dart';
class StripeFlowPage extends StatefulWidget {
const StripeFlowPage({super.key, required this.stripeFlow});
final StripeFlow stripeFlow;
@override
State<StripeFlowPage> createState() => _StripeFlowPageState();
}
class _StripeFlowPageState extends State<StripeFlowPage> {
final _checkout = StripeCheckout();
bool _hasAppeared = false;
bool _isClosing = false; // the route closes after the payment
bool get _isBusy => _checkout.isPaying || _isClosing;
/// Pops the route. The screen receives `true` when the user paid.
void _close({bool paid = false}) {
if (_isClosing || !mounted) return;
_isClosing = true;
Navigator.of(context).pop(paid);
}
void _onAction(AdaptyUIFlowView view, AdaptyUIAction action) {
switch (action) {
case CloseAction():
case AndroidSystemBackAction():
if (_isBusy) return;
_close();
case OpenUrlAction(:final url, :final openIn):
if (_isBusy) return;
AdaptyUI().openUrl(url, openIn: openIn).ignore();
case CustomAction(:final action):
final plan = StripeCheckout.plans[action];
if (plan == null || _isBusy) return;
_payAndClose(plan, view);
}
}
Future<void> _payAndClose(String plan, AdaptyUIFlowView view) async {
if (await _checkout.pay(plan, view, showError: _showError)) _close(paid: true);
}
/// Shows the error over the flow
Future<void> _showError(String message) async {
if (!mounted) return;
await showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: const Text("The payment didn't go through"),
content: Text(message),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('OK'),
),
],
),
);
}
@override
Widget build(BuildContext context) {
// Android's Back button can pop the route instead of reaching the flow
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) {
if (!didPop && !_isBusy) _close();
},
child: Scaffold(
// Keeps the flow's close button out of the Android status bar.
// On iOS, the flow applies the safe area itself.
body: SafeArea(
top: Platform.isAndroid,
bottom: Platform.isAndroid,
child: AdaptyUIFlowPlatformView(
flow: widget.stripeFlow.flow,
customTags: widget.stripeFlow.customTags,
onDidAppear: (_) => _hasAppeared = true,
onDidPerformAction: _onAction,
onDidReceiveError: (view, error) {
debugPrint('Flow error: $error');
// The widget stays empty when it can't show the flow.
// The flow keeps working after other errors, so keep PaymentSheet open.
if (!_hasAppeared && !_isBusy) _close();
},
),
),
),
);
}
}If your app sets an observer with AdaptyUI().setFlowsEventsObserver, the observer also receives this flow’s events. Handle the Stripe actions only in onDidPerformAction.
In your screen, load the flow, and push its route:
import 'package:adapty_flutter/adapty_flutter.dart';
import 'package:flutter/material.dart';
class MembershipScreen extends StatefulWidget {
const MembershipScreen({super.key});
@override
State<MembershipScreen> createState() => _MembershipScreenState();
}
class _MembershipScreenState extends State<MembershipScreen> {
bool _isLoadingFlow = false;
Future<void> _showStripeFlow() async {
if (_isLoadingFlow) return;
_isLoadingFlow = true;
try {
final stripeFlow = await loadStripeFlow();
if (!mounted) return;
final paid = await Navigator.of(context).push<bool>(
MaterialPageRoute(builder: (_) => StripeFlowPage(stripeFlow: stripeFlow)),
);
if (paid == true) await _unlockAfterPayment();
} on AdaptyError catch (e) {
// handle the error
} catch (e) {
// handle the error
} finally {
_isLoadingFlow = false;
}
}
Future<void> _unlockAfterPayment() async {
final hasAccess = await waitForAccess();
if (!mounted) return;
if (hasAccess) {
// unlock the service
} else {
// tell the user that the payment is processing, and how to reach your support
}
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: _showStripeFlow,
child: const Text('Become a member'),
);
}
}If your flow also sells App Store or Google Play products, handle their purchases in the purchase callbacks of AdaptyUIFlowPlatformView, 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 'package:adapty_flutter/adapty_flutter.dart';
Future<bool> waitForAccess() async {
for (var attempt = 0; attempt < 20; attempt++) {
try {
final profile = await Adapty().getProfile();
if (profile.accessLevels['YOUR_ACCESS_LEVEL']?.isActive == true) return true;
} catch (_) {
// try again
}
await Future<void>.delayed(const Duration(seconds: 3));
}
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 present 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 App Store or Google Play subscriptions. 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.