1. Introduction
Adding in-app purchases to a Flutter app requires configuring the Apple App Store and Google Play Store, verifying purchase tokens on a trusted backend, and granting entitlements such as consumable currency, one-time upgrades, or recurring subscription perks.
In this codelab, you collaborate with Google Antigravity to build Dash Clicker—a mobile clicker game that uses the Dash mascot as currency—and pair it with a Dart shelf backend service and Cloud Firestore to validate and track three types of in-app purchases:
- Consumable (
dash_consumable_2k): A repeatable purchase that immediately grants the player 2,000 Dashes and can be bought multiple times. - Non-consumable (
dash_upgrade_3d): A permanent one-time upgrade that transforms the classic Dash mascot into a modern 3D Dash forever. - Subscription (
dash_subscription_doubler): An auto-renewing subscription that multiplies passively generated clicks while the subscription remains active.
|
|
|
What you'll build
- A Flutter mobile app (
app/) styled withmaterial_uiandcupertino_uithat queries store products, initiates purchases, and reacts to real-time purchase streams. - A Dart
shelfbackend server (dart-backend/) that verifies purchase receipts with Google Play and the App Store, polls store billing events, and records purchase states in Cloud Firestore.
Your learning journey
This codelab guides you through building and connecting the full-stack in-app purchase flow step by step:
- Set up the development environment - Install Flutter and Google Antigravity, prompt Antigravity to scaffold the Dash Clicker starter project (
app/), and configure your iOS bundle identifier and AndroidapplicationId. - Install the plugin - Prompt Antigravity to add
in_app_purchaseandin_app_purchase_platform_interfacetoapp/. - Set up the App Store - Register your App ID, create a sandbox test account, and configure the three products in App Store Connect.
- Set up the Play Store - Create your app in Google Play Console, prompt Antigravity to configure release keystore signing in Gradle, upload an initial app bundle, add license testers, and configure the products.
- Set up Firebase - Enable Google Sign-In and Cloud Firestore in the Firebase console, run
flutterfire configure, and configure Android SHA-1 fingerprints and iOS URL schemes. - Listen to purchase updates - Prompt Antigravity to add a testable
IAPConnectionwrapper, subscribe topurchaseStream, and test the app withTestIAPConnection. - Make purchases - Prompt Antigravity to wrap
ProductDetailsinPurchasableProduct, query store products, triggerbuyConsumableandbuyNonConsumable, and complete pending purchases. - Set up the backend - Prompt Antigravity to scaffold the
dart-backend/server withIapRepositoryand configure service account credentials. - Verify purchases - Prompt Antigravity to require Firebase login on
PurchasePage, post purchase tokens to/verifypurchase, and implementGooglePlayPurchaseHandlerandAppStorePurchaseHandler. - Keep track of purchases - Prompt Antigravity to poll Google Cloud Pub/Sub and the App Store Server API on the backend and synchronize entitlements back to the Flutter client using
IAPRepo.
What you'll learn
- How to collaborate with Google Antigravity to iteratively build and customize a full-stack Flutter in-app purchase app and Dart backend.
- How to configure App Store Connect and Google Play Console with consumable, non-consumable, and subscription products.
- How to query products, initiate purchases, and handle purchase streams with the
in_app_purchaseplugin. - How to verify Google Play and App Store purchase tokens on a Dart backend and store them in Cloud Firestore.
- How to process store billing events and synchronize subscription and upgrade entitlements across devices.
Prerequisites
- Basic familiarity with Flutter widgets, Dart syntax, and
Providerstate management. - An Apple Developer account (to test App Store purchases on iOS), a Google Play Developer account (to test Play Store purchases on Android), or both.
- A Firebase account and the Firebase CLI.
2. Set up the development environment
Editor
This codelab uses Google Antigravity as your AI-first development environment. In each step, you prompt Antigravity to generate or evolve your Flutter client (app/) and Dart backend (dart-backend/), inspect the generated code, and optionally explore variations.
Install Flutter
The most up-to-date instructions on installing the Flutter SDK are always on docs.flutter.dev.
For this codelab, install the following software:
- Flutter SDK
- Google Antigravity with the official Dart and Flutter plugin enabled (available in the Plugin Marketplace under the Build with Google section).
- Compiler software for your chosen mobile target (Android Studio to target Android, or Xcode to target iOS).
Prompt Antigravity to create the starter project
- Launch Google Antigravity and open an empty workspace directory where you'd like to build both your Flutter app (
app/) and Dart server (dart-backend/). Choose a path that doesn't require elevated privileges or contain spaces, such as a folder in your home directory orC:\src\. - In the Antigravity agent chat panel, send the following prompt to scaffold the Dash Clicker starter app in
app/:
Create a new empty Flutter project in `app/` named `dashclicker` targeting Android and iOS (`flutter create app --project-name dashclicker --empty --platforms android,ios`). Add the `cloud_firestore`, `cupertino_icons`, `firebase_auth`, `firebase_core`, `google_sign_in`, `http`, `intl`, `provider`, `logging`, `material_ui`, and `cupertino_ui` packages. Download `dash_old.png` and `dash.png` from `https://raw.githubusercontent.com/flutter/codelabs/main/in_app_purchases/step_00/app/assets/dash_old.png` and `https://raw.githubusercontent.com/flutter/codelabs/main/in_app_purchases/step_00/app/assets/dash.png` into `app/assets/` and register `assets/` under `flutter: assets:` in `app/pubspec.yaml`. Set `minSdk = 23` in `app/android/app/build.gradle.kts`, and add `GIDClientID` and `CFBundleURLTypes` placeholders in `app/ios/Runner/Info.plist`. Scaffold the Dash Clicker starter files using `package:material_ui/material_ui.dart` and `package:cupertino_ui/cupertino_ui.dart`:
- `lib/constants.dart` defining `cloudRegion = 'europe-west1'`, `storeKeyConsumable = 'dash_consumable_2k'`, `storeKeyUpgrade = 'dash_upgrade_3d'`, `storeKeySubscription = 'dash_subscription_doubler'`, and `serverIp = '192.168.178.46'`
- `lib/firebase_options.dart` with a placeholder `DefaultFirebaseOptions` for Android and iOS
- `lib/model/firebase_state.dart` (`enum FirebaseState { loading, available, notAvailable }`), `lib/model/store_state.dart` (`enum StoreState { loading, available, notAvailable }`), `lib/model/purchasable_product.dart` (`enum ProductStatus { purchasable, purchased, pending }` and `PurchasableProduct(this.title, this.description, this.price)`), and `lib/model/past_purchase.dart` (`PurchaseType`, `Store`, `Status`, and `PastPurchase.fromJson`)
- `lib/logic/dash_counter.dart` (`DashCounter extends ChangeNotifier` with `count`, `countString`, `increment()`, `addAutoIncrement()`, `applyPaidMultiplier()`, `removePaidMultiplier()`, `addBoughtDashes(int amount)`, and a 10Hz `Timer.periodic`)
- `lib/logic/dash_purchases.dart` (`DashPurchases extends ChangeNotifier` with `counter`, `storeState = StoreState.available`, mock `products`, `bool get beautifiedDash => false`, and a simulated `buy(PurchasableProduct product)` method)
- `lib/logic/dash_upgrades.dart` (`DashUpgrades extends ChangeNotifier` and `Upgrade` for `'Tim Sneath'`)
- `lib/logic/firebase_notifier.dart` (`FirebaseNotifier extends ChangeNotifier` initializing `Firebase.initializeApp`, `GoogleSignIn.instance`, `FirebaseAuth`, and `FirebaseFirestore`)
- `lib/repo/iap_repo.dart` (`IAPRepo extends ChangeNotifier` listening to Firebase auth changes and the `purchases` collection in Firestore)
- `lib/pages/home_page.dart` (`HomePage`, `DashClickerWidget`, `CounterStateWidget`, and `UpgradeList`), `lib/pages/login_page.dart` (`LoginPage`), and `lib/pages/purchase_page.dart` (`PurchasePage`, `_PurchasesLoading`, `_PurchasesNotAvailable`, `_PurchaseList`, `_PurchaseWidget`, and `PastPurchasesWidget`)
- `lib/main.dart` (`MyApp` and `MyHomePage` providing `FirebaseNotifier`, `DashCounter`, `DashUpgrades`, `IAPRepo`, and `DashPurchases` using `MultiProvider` with a `BottomNavigationBar` switching between `HomePage` and `PurchasePage`)
- `test/widget_test.dart` pumping `const MyApp()` and verifying `find.text('Tim Sneath')`.
Understanding the generated starter code
Antigravity creates the app/ Flutter project and scaffolds the Dash Clicker game architecture using Provider and ChangeNotifier:
app/lib/main.dartregisters fiveChangeNotifierProviders (FirebaseNotifier,DashCounter,DashUpgrades,IAPRepo, andDashPurchases) insideMyHomePageand switches betweenHomePageandPurchasePage.app/lib/constants.dartdefines the three store product IDs that must match the IDs you configure in App Store Connect and Google Play Console:
const cloudRegion = 'europe-west1';
const storeKeyConsumable = 'dash_consumable_2k';
const storeKeyUpgrade = 'dash_upgrade_3d';
const storeKeySubscription = 'dash_subscription_doubler';
// TODO: Replace by your own server IP
const serverIp = '192.168.178.46';
Configure your app's bundle identifier and application ID
To communicate with the App Store and Play Store, your app needs a unique reverse-domain identifier (for example, dev.flutter.dashclicker). On iOS, this is called the bundle identifier; on Android, it is the application ID. Using the same identifier on both platforms keeps configuration simpler.
First, set up the bundle identifier for iOS by opening app/ios/Runner.xcworkspace in Xcode:

In Xcode's project navigator, select Runner at the top, open the Signing & Capabilities tab, select your Team, and enter your unique Bundle Identifier:

Next, update the Android applicationId in app/android/app/build.gradle.kts to match your chosen identifier (you can edit it directly or ask Antigravity to update applicationId in app/android/app/build.gradle.kts to your chosen ID):

3. Install the plugin
In this step, you prompt Antigravity to add the in_app_purchase plugin and its platform interface package (used for mocking store connections in widget tests) to app/.
Prompt Antigravity to install in_app_purchase
In the Antigravity agent chat panel, send the following prompt:
In `app/`, add `in_app_purchase` to `dependencies` and `in_app_purchase_platform_interface` to `dev_dependencies` in `pubspec.yaml`.
Understanding the generated code
Antigravity runs flutter pub add in_app_purchase dev:in_app_purchase_platform_interface inside app/, updating app/pubspec.yaml:
dependencies:
flutter:
sdk: flutter
cloud_firestore: ^7.1.0
cupertino_icons: ^2.0.0
cupertino_ui: ^1.1.6
firebase_auth: ^7.0.1
firebase_core: ^5.1.0
google_sign_in: ^7.2.0
http: ^1.6.0
in_app_purchase: ^3.3.1
intl: ^0.20.3
logging: ^1.3.0
material_ui: ^1.11.0
provider: ^6.1.5+1
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^6.0.0
in_app_purchase_platform_interface: ^1.4.1
in_app_purchaseprovides the cross-platformInAppPurchaseAPI backed by StoreKit on iOS and Google Play Billing on Android.in_app_purchase_platform_interfaceexposesInAppPurchasePlatformAddition, which lets you implement a mockInAppPurchaseclient inapp/test/widget_test.dart.
4. Set up the App Store
To test in-app purchases on iOS, you need to register your app in App Store Connect and configure purchasable products. You don't have to publish the app or submit it for review, but you do need an Apple Developer account. If you don't have one, enroll in the Apple Developer Program.
Paid Apps Agreements
To use in-app purchases, you must have an active Paid Apps agreement in App Store Connect. Go to App Store Connect, and select Agreements, Tax, and Banking (or Business).

Review the agreements for free and paid apps. View and accept the terms for Paid Apps, and enter the required tax and banking information.

When everything is configured, the status for Paid Apps changes to Active. Without an active Paid Apps agreement, StoreKit won't return your in-app products during testing.

Register an App ID
Create a new App ID in the Apple Developer Portal:
- Visit Apple Developer Identifiers and click the + icon next to the Identifiers header.

- Select App IDs and click Continue.

- Select App as the type and click Continue.

- Enter a description and set the Bundle ID (Explicit) to the exact bundle identifier you configured in Xcode. Ensure the In-App Purchase capability is enabled, then register the identifier.

For additional details, see Apple Developer Account Help.
Create a new app and sandbox user
Create a new app in App Store Connect using your registered bundle identifier:
|
|
For more guidance on creating an app and managing agreements, see App Store Connect Help.
To test in-app purchases without real charges, create a Sandbox Apple Account in App Store Connect under Users and Access > Sandbox. You must use an email address that isn't already associated with an Apple Account.

On your test iPhone or iPad, sign in with your sandbox account under Settings > Developer > Sandbox Apple Account.
|
|
Configure your in-app purchases
Next, configure the three purchasable items in App Store Connect:
dash_consumable_2k: A consumable purchase that can be bought repeatedly, granting 2,000 Dashes per purchase.dash_upgrade_3d: A non-consumable upgrade purchase that can only be bought once, unlocking the 3D Dash mascot.dash_subscription_doubler: An auto-renewing subscription that multiplies passive clicks while active.

In your app's In-App Purchases (and Subscriptions) sections, create the three products with these exact Product IDs:
- Consumable (
dash_consumable_2k):- Create a Consumable product with Reference Name
dash consumable 2kand Product IDdash_consumable_2k.
- Configure availability so the product is available in your sandbox user's country or region.

- Set the price to
\$1.99(or local currency equivalent).
- Add a localization with Display Name
Spring is in the airand Description2000 dashes fly out.
- Upload a review screenshot. The image content doesn't matter for sandbox testing, but uploading a screenshot transitions the product to the Ready to Submit state, which is required for the app to fetch the product from StoreKit.

- Create a Consumable product with Reference Name
- Non-consumable (
dash_upgrade_3d):- Create a Non-Consumable product with Reference Name
dash upgrade 3dand Product IDdash_upgrade_3d. - Set the Display Name to
3D Dash, Description toBrings your dash back to the future, and price to\$0.99. - Configure availability and upload a review screenshot just as you did for
dash_consumable_2k.
- Create a Non-Consumable product with Reference Name
- Auto-renewing subscription (
dash_subscription_doubler):- Under Subscriptions, create a Subscription Group named
subscriptions(users can subscribe to only one product within the same group at a time, and can upgrade or downgrade within the group).
- Add an App Store localization for the subscription group.

- Inside the group, create a subscription with Reference Name
dash subscription doublerand Product IDdash_subscription_doubler.
- Set the Subscription Duration to 1 Week, Display Name to
Jet Engine, Description toDoubles your clicks, and price to\$0.49. Configure availability and upload a review screenshot so its status becomes Ready to Submit.
- Under Subscriptions, create a Subscription Group named
Your products should now appear in App Store Connect with the Ready to Submit status:


5. Set up the Play Store
To test in-app purchases on Android, you need a Google Play Developer account. If you don't have one yet, register for a Google Play Developer account.
Create a new app
Create a new app in the Google Play Console:
- Open the Google Play Console.
- Select All apps > Create app.
- Choose a default language and enter an app name (you can change this later).
- Select Game as the app type and Free as the pricing model.
- Complete the Developer Program Policies and US export laws declarations, then select Create app.
After creating the app, complete the initial Set up your app tasks on the dashboard:

Sign the application
To test Google Play Billing, you must upload at least one signed release appbundle to a testing track in Google Play Console.
Create a keystore
If you don't already have an upload keystore, generate one from the terminal.
On macOS or Linux:
keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key
On Windows:
keytool -genkey -v -keystore c:\Users\USER_NAME\key.jks -storetype JKS -keyalg RSA -keysize 2048 -validity 10000 -alias key
Create app/android/key.properties
Create app/android/key.properties containing a reference to your keystore:
storePassword=<password from previous step>
keyPassword=<password from previous step>
keyAlias=key
storeFile=<location of the key store file, such as /Users/<user name>/key.jks>
Prompt Antigravity to configure release signing in Gradle
Send the following prompt in Antigravity to wire up release signing in app/android/app/build.gradle.kts:
Update `app/android/app/build.gradle.kts` to load `key.properties` into a `Properties` object if the file exists, configure a `release` signing config inside `signingConfigs` using `keyAlias`, `keyPassword`, `storeFile`, and `storePassword`, and assign `signingConfigs.getByName("release")` to the `release` build type when `key.properties` is present.
Antigravity updates app/android/app/build.gradle.kts to load key.properties and sign release builds:
val keystoreProperties = Properties()
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
}
android {
// ...
signingConfigs {
create("release") {
keyAlias = keystoreProperties["keyAlias"] as String?
keyPassword = keystoreProperties["keyPassword"] as String?
storeFile = keystoreProperties["storeFile"]?.let { file(it) }
storePassword = keystoreProperties["storePassword"] as String?
}
}
buildTypes {
release {
signingConfig = signingConfigs.getByName("release")
}
}
}
Upload your first build
Build a signed release app bundle from app/:
cd app
flutter build appbundle
The release bundle is written to app/build/app/outputs/bundle/release/app-release.aab.
In the Google Play Console, navigate to Test and release > Testing > Closed testing, create a closed testing release, upload app-release.aab, and click Save > Review release > Start rollout to Closed testing.
Set up test users
To test in-app purchases on Android, add your testers' Google Accounts in two places in the Google Play Console:
- Testing track testers: Go to Test and release > Testing > Internal testing (or Closed testing), open the Testers tab, click Create email list, add your testers' email addresses, select the list, and click Save changes.

- License testers: Return to the All apps view, select Settings > License testing, add the same tester email addresses, set License response to
RESPOND_NORMALLY, and click Save changes.
Configure your in-app purchases
Configure the same three product IDs in the Google Play Console:
dash_consumable_2k: Consumable purchase granting 2,000 Dashes.dash_upgrade_3d: Non-consumable one-time 3D Dash upgrade.dash_subscription_doubler: Auto-renewing click-multiplier subscription.
First, create the one-time products (dash_consumable_2k and dash_upgrade_3d):
- Select your app in the Google Play Console and navigate to Monetize with Play > Products > In-app products.
- Click Create product.

- Enter the exact Product ID (
dash_consumable_2k), name, description, and price, then click Save and Activate. - Repeat the process for
dash_upgrade_3d.
Next, create the subscription (dash_subscription_doubler):
- Navigate to Monetize with Play > Products > Subscriptions and click Create subscription.

- Enter the Product ID (
dash_subscription_doubler), add a base plan with a weekly billing period and price, then Save and Activate it.
6. Set up Firebase
Using a backend service with Cloud Firestore to verify and track purchases gives your app several security advantages:
- You verify transactions directly with Google Play and Apple servers.
- You can react to server-side billing events (such as renewals or cancellations).
- You store a single source of truth in Cloud Firestore associated with each authenticated user.
- Users can't unlock premium perks by tampering with their device clock.
Create a Firebase project
- Open the Firebase console and create a new Firebase project (for example, Dash Clicker).
- Navigate to Build > Authentication, click Get started, open the Sign-in method tab, and enable the Google sign-in provider.

- Navigate to Build > Firestore Database and create a database.

- Open the Rules tab in Cloud Firestore and publish the following security rules so authenticated users can read only their own purchase documents:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /purchases/{purchaseId} {
allow read: if request.auth != null && request.auth.uid == resource.data.userId
}
}
}
Set up Firebase for Flutter
Follow the FlutterFire setup guide to install the FlutterFire CLI, then run flutterfire configure inside app/:
cd app
flutterfire configure
- Select the Firebase project you created.
- Enable android and ios.
- Confirm yes when asked to override
lib/firebase_options.dart.
Set up Firebase for Android: Debug SHA-1 certificate
Google Sign-In on Android requires registering your debug keystore's SHA-1 fingerprint in the Firebase console:
- In the Firebase console, open Project Overview > Project settings > General, scroll down to Your apps, and select your Android app:

- Generate a signing report from
app/android/:cd app/android ./gradlew :app:signingReport - Locate the
SHA1fingerprint underVariant: debugandConfig: debug, add it to your Android app in the Firebase console, and re-runflutterfire configureinapp/sogoogle-services.jsonandlib/firebase_options.dartinclude the updated OAuth client configuration.
Set up Firebase for iOS: Configure URL schemes
To support Google Sign-In on iOS, app/ios/Runner/Info.plist must include the REVERSED_CLIENT_ID from app/ios/Runner/GoogleService-Info.plist inside CFBundleURLTypes (see the google_sign_in iOS integration docs).
You can prompt Antigravity to copy the REVERSED_CLIENT_ID and CLIENT_ID from app/ios/Runner/GoogleService-Info.plist into app/ios/Runner/Info.plist:
Read `CLIENT_ID` and `REVERSED_CLIENT_ID` from `app/ios/Runner/GoogleService-Info.plist` and update `GIDClientID` and `CFBundleURLTypes` (`CFBundleURLSchemes`) in `app/ios/Runner/Info.plist` with those values.
In app/ios/Runner/Info.plist, the CFBundleURLTypes entry looks like this:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>com.googleusercontent.apps.YOUR_REVERSED_CLIENT_ID</string>
</array>
</dict>
</array>
7. Listen to purchase updates
In this step, you prepare the Flutter app to listen to store purchase updates as soon as the app launches, and keep the widget tree testable by introducing an overridable IAPConnection wrapper.
Prompt Antigravity to listen to purchase updates
Send the following prompt in Antigravity:
Update `app/lib/main.dart` to define an `IAPConnection` class with a static `InAppPurchase? _instance` and a static getter and setter for `instance` (defaulting to `InAppPurchase.instance`), and set `lazy: false` on `ChangeNotifierProvider<DashPurchases>`. Update `DashPurchases` in `app/lib/logic/dash_purchases.dart` to set `storeState = StoreState.notAvailable`, hold `final iapConnection = IAPConnection.instance` and `late StreamSubscription<List<PurchaseDetails>> _subscription`, subscribe to `iapConnection.purchaseStream.listen(_onPurchaseUpdate, onDone: _updateStreamOnDone, onError: _updateStreamOnError)` in the constructor, cancel `_subscription` in `dispose()`, and add `_onPurchaseUpdate`, `_updateStreamOnDone`, and `_updateStreamOnError` methods. Finally, update `app/test/widget_test.dart` to define `TestIAPConnection implements InAppPurchase` and set `IAPConnection.instance = TestIAPConnection()` before pumping `MyApp`.
Understanding the generated code
Eager provider initialization and IAPConnection in app/lib/main.dart
By default, Provider creates its value lazily when a widget first reads it. Because pending store transactions can arrive on purchaseStream immediately at startup, ChangeNotifierProvider sets lazy: false. In addition, IAPConnection provides a static seam so widget tests can inject a fake InAppPurchase implementation:
class IAPConnection {
static InAppPurchase? _instance;
static set instance(InAppPurchase value) {
_instance = value;
}
static InAppPurchase get instance {
_instance ??= InAppPurchase.instance;
return _instance!;
}
}
ChangeNotifierProvider<DashPurchases>(
create: (context) => DashPurchases(context.read<DashCounter>()),
lazy: false,
),
Subscribing to purchaseStream in app/lib/logic/dash_purchases.dart
In DashPurchases, the constructor subscribes to iapConnection.purchaseStream and dispose() cancels _subscription:
final iapConnection = IAPConnection.instance;
DashPurchases(this.counter) {
final purchaseUpdated = iapConnection.purchaseStream;
_subscription = purchaseUpdated.listen(
_onPurchaseUpdate,
onDone: _updateStreamOnDone,
onError: _updateStreamOnError,
);
}
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
Run and test the app
Run the widget test suite in app/ to verify that TestIAPConnection mocks the store connection cleanly:
cd app
flutter test
8. Make purchases
In this step, you replace the hardcoded mock products with live store products fetched using queryProductDetails, initiate purchases when the user taps a product, and complete transactions when updates arrive on purchaseStream.
Prompt Antigravity to load and make purchases
Send the following prompt in Antigravity:
Update `PurchasableProduct` in `app/lib/model/purchasable_product.dart` to wrap a `ProductDetails productDetails` from `package:in_app_purchase/in_app_purchase.dart`, exposing `id`, `title`, `description`, and `price` getters from `productDetails` and initializing `status = ProductStatus.purchasable`. Then update `DashPurchases` in `app/lib/logic/dash_purchases.dart` to initialize `storeState = StoreState.loading`, `products = []`, and `bool _beautifiedDashUpgrade = false` (backing `beautifiedDash`), call `loadPurchases()` in the constructor to check `iapConnection.isAvailable()` and query `{storeKeyConsumable, storeKeySubscription, storeKeyUpgrade}` with `iapConnection.queryProductDetails(ids)`, implement `buy(PurchasableProduct product)` using `PurchaseParam` to call `iapConnection.buyConsumable` for `storeKeyConsumable` and `iapConnection.buyNonConsumable` for `storeKeySubscription` and `storeKeyUpgrade`, and implement `_onPurchaseUpdate` and `_handlePurchase(PurchaseDetails purchaseDetails)` to apply `PurchaseStatus.purchased` rewards (`counter.applyPaidMultiplier()`, `counter.addBoughtDashes(2000)`, `_beautifiedDashUpgrade = true`) and call `iapConnection.completePurchase(purchaseDetails)` when `purchaseDetails.pendingCompletePurchase` is true.
Understanding the generated code
Wrapping ProductDetails in app/lib/model/purchasable_product.dart
PurchasableProduct wraps the ProductDetails returned by the store while tracking local UI ProductStatus (purchasable, purchased, or pending):
class PurchasableProduct {
String get id => productDetails.id;
String get title => productDetails.title;
String get description => productDetails.description;
String get price => productDetails.price;
ProductStatus status;
ProductDetails productDetails;
PurchasableProduct(this.productDetails) : status = ProductStatus.purchasable;
}
Querying products in app/lib/logic/dash_purchases.dart
loadPurchases() first verifies that the underlying store is reachable with iapConnection.isAvailable(), then queries the three product IDs defined in app/lib/constants.dart:
Future<void> loadPurchases() async {
final available = await iapConnection.isAvailable();
if (!available) {
storeState = StoreState.notAvailable;
notifyListeners();
return;
}
const ids = <String>{
storeKeyConsumable,
storeKeySubscription,
storeKeyUpgrade,
};
final response = await iapConnection.queryProductDetails(ids);
products = response.productDetails
.map((e) => PurchasableProduct(e))
.toList();
storeState = StoreState.available;
notifyListeners();
}
Initiating and completing purchases
When a user taps a product in PurchasePage, buy() constructs a PurchaseParam and dispatches consumables to buyConsumable and one-time upgrades or subscriptions to buyNonConsumable:
Future<void> buy(PurchasableProduct product) async {
final purchaseParam = PurchaseParam(productDetails: product.productDetails);
switch (product.id) {
case storeKeyConsumable:
await iapConnection.buyConsumable(purchaseParam: purchaseParam);
case storeKeySubscription:
case storeKeyUpgrade:
await iapConnection.buyNonConsumable(purchaseParam: purchaseParam);
default:
throw ArgumentError.value(
product.productDetails,
'${product.id} is not a known product',
);
}
}
When the store emits updated PurchaseDetails objects on purchaseStream, _handlePurchase grants the corresponding reward and acknowledges completion by calling completePurchase:
Future<void> _handlePurchase(PurchaseDetails purchaseDetails) async {
if (purchaseDetails.status == PurchaseStatus.purchased) {
switch (purchaseDetails.productID) {
case storeKeySubscription:
counter.applyPaidMultiplier();
case storeKeyConsumable:
counter.addBoughtDashes(2000);
case storeKeyUpgrade:
_beautifiedDashUpgrade = true;
}
}
if (purchaseDetails.pendingCompletePurchase) {
await iapConnection.completePurchase(purchaseDetails);
}
}
Run and test the app
Run flutter test in app/ and launch the app on your configured test device. When your store products are active, the Purchase tab displays them ready for purchase:

9. Set up the backend
Before verifying and tracking purchases on a server, you'll scaffold the Dart backend service in dart-backend/ alongside app/ and configure credentials for Firebase, Google Play, and the App Store.
Prompt Antigravity to scaffold the Dart backend
In the Antigravity agent chat panel, send the following prompt to create the dart-backend/ project:
Create a Dart shelf server project in `dart-backend/` with package name `firebase_backend_dart` (`dart create -t server-shelf`). Add `googleapis: ^16.0.0`, `googleapis_auth`, `http`, and `app_store_server_sdk` to `dependencies`, and `test` to `dev_dependencies` (configuring `deprecated_member_use: ignore` in `dart-backend/analysis_options.yaml`). Create:
- `dart-backend/lib/constants.dart` defining `androidPackageId`, `appStoreIssuerId`, `appStoreKeyId`, `appStoreSharedSecret`, `bundleId`, `googleCloudProjectId`, and `googlePlayPubsubBillingTopic = 'play_billing'`
- `dart-backend/lib/helpers.dart` with `serveHandler(Handler handler)`, `listenPort()`, and `terminateRequestFuture()` listening to `SIGINT` and `SIGTERM`
- `dart-backend/lib/products.dart` defining `ProductData(this.productId, this.type)`, `enum ProductType { subscription, nonSubscription }`, and `productDataMap` for `'dash_consumable_2k'`, `'dash_upgrade_3d'`, and `'dash_subscription_doubler'`
- `dart-backend/lib/iap_repository.dart` defining `enum IAPSource { googleplay, appstore }`, `abstract class Purchase`, `NonSubscriptionPurchase`, `SubscriptionPurchase`, and `IapRepository(this.api, this.projectId)` using `package:googleapis/firestore/v1.dart` (`createOrUpdatePurchase`, `updatePurchase`, and `getPurchases`)
- `dart-backend/bin/server.dart` starting an empty `Router()` with `await serveHandler(router.call)`.
Understanding the generated code
dart-backend/bin/server.dartinitializes ashelf_routerRouterand serves HTTP requests on port8080usingserveHandlerindart-backend/lib/helpers.dart.dart-backend/lib/products.dartmaps each product ID (dash_consumable_2k,dash_upgrade_3d, anddash_subscription_doubler) to itsProductType(nonSubscriptionorsubscription).dart-backend/lib/iap_repository.dartencapsulates reading and writingNonSubscriptionPurchaseandSubscriptionPurchasedocuments in thepurchasescollection of Cloud Firestore usingFirestoreApi.
You can test that the server starts locally by running:
cd dart-backend
dart run ./bin/server.dart
Set up Firebase access
To let dart-backend/ write verified purchases to Cloud Firestore, generate a service account key:
- In the Firebase console, open Project settings > Service accounts and click Generate new private key.

- Save the downloaded JSON file as
dart-backend/assets/service-account-firebase.json.
Set up Google Play access
To let dart-backend/ verify Android purchases with the Google Play Android Developer API:
- Open the Google Play Android Developer API page in the Google Cloud Console and enable the API.

- Go to the Google Cloud Service accounts page and click + Create service account.

- Enter a service account name and click Create and continue.

- Grant the Pub/Sub Subscriber role and click Done.

- Open the newly created service account's actions menu and select Manage keys.

- Select Add key > Create new key, choose JSON, and download the key:


- Save the downloaded file as
dart-backend/assets/service-account-google-play.json. - Open Users and permissions in the Google Play Console, click Invite new users, and enter the service account's email address:


- Grant View financial data and Manage orders and subscriptions permissions for your app, then click Invite user.

Set up Apple App Store access
To verify App Store receipts on the backend, generate an App-Specific Shared Secret:
- Open App Store Connect, select Apps, and choose your app.
- In the sidebar, navigate to General > App Information.
- Under App-Specific Shared Secret, click Manage, generate a new shared secret, and copy it:


Update dart-backend/lib/constants.dart
Ensure the following constants are set in dart-backend/lib/constants.dart:
androidPackageId: Your AndroidapplicationId(such ascom.example.dashclicker).appStoreSharedSecret: Your App Store Connect shared secret.bundleId: Your iOS bundle identifier (such ascom.example.dashclicker).
10. Verify purchases
When a user completes a purchase on iOS or Android, the store issues a verification token (PurchaseDetails.verificationData.serverVerificationData). Instead of trusting the client device directly, the Flutter app sends this token to dart-backend/, which verifies the token with Google Play or the App Store and records the purchase in Cloud Firestore.

Prompt Antigravity to verify purchases on the client and backend
Send the following prompt in Antigravity to connect the Flutter app and Dart backend verification flow:
1. In `app/`:
- Update `PurchasePage` in `app/lib/pages/purchase_page.dart` to watch `FirebaseNotifier` and return `_PurchasesLoading()` when `state == FirebaseState.loading`, `_PurchasesNotAvailable()` when `state == FirebaseState.notAvailable`, and `const LoginPage()` when `!firebaseNotifier.loggedIn`.
- Add `User? get user => FirebaseAuth.instance.currentUser;` to `FirebaseNotifier` in `app/lib/logic/firebase_notifier.dart`.
- Update `DashPurchases` in `app/lib/logic/dash_purchases.dart` (and its provider in `app/lib/main.dart`) to accept `this.firebaseNotifier`, implement `_verifyPurchase(PurchaseDetails purchaseDetails)` that sends an HTTP `POST` request to `Uri.http('$serverIp:8080', '/verifypurchase')` with JSON body `{'source': purchaseDetails.verificationData.source, 'productId': purchaseDetails.productID, 'verificationData': purchaseDetails.verificationData.serverVerificationData, 'userId': firebaseNotifier.user?.uid}`, and update `_handlePurchase` so purchase rewards are only applied when `await _verifyPurchase(purchaseDetails)` returns `true`.
2. In `dart-backend/`:
- Create `dart-backend/lib/purchase_handler.dart` with `abstract class PurchaseHandler` defining `handleNonSubscription`, `handleSubscription`, and `verifyPurchase` switching on `productData.type`.
- Create `dart-backend/lib/google_play_purchase_handler.dart` with `GooglePlayPurchaseHandler extends PurchaseHandler` that verifies one-time purchases using `androidPublisher.purchases.products.get` and subscriptions using `androidPublisher.purchases.subscriptions.get`, parses order IDs with `extractOrderId(String orderId)` (stripping `..` renewal suffixes), maps statuses with `_nonSubscriptionStatusFrom` and `_subscriptionStatusFrom`, and saves purchases to `iapRepository`.
- Create `dart-backend/lib/app_store_purchase_handler.dart` with `AppStorePurchaseHandler extends PurchaseHandler` that validates receipts with `ITunesApi(ITunesHttpClient(ITunesEnvironment.sandbox(), loggingEnabled: true)).verifyReceipt` and saves `NonSubscriptionPurchase` and `SubscriptionPurchase` records to `iapRepository`.
- Update `dart-backend/bin/server.dart` to initialize `AndroidPublisherApi` and `FirestoreApi` from the service account JSON files in `_createPurchaseHandlers()`, register a `POST /verifypurchase` route, and extract request fields in `getPurchaseData(dynamic payload)` using Dart 3 map pattern matching.
Understanding the generated code
Gating purchases behind authentication and calling /verifypurchase
In app/lib/pages/purchase_page.dart, PurchasePage checks FirebaseNotifier and displays LoginPage until the user signs in:
var firebaseNotifier = context.watch<FirebaseNotifier>();
if (firebaseNotifier.state == FirebaseState.loading) {
return _PurchasesLoading();
} else if (firebaseNotifier.state == FirebaseState.notAvailable) {
return _PurchasesNotAvailable();
}
if (!firebaseNotifier.loggedIn) {
return const LoginPage();
}
In app/lib/logic/dash_purchases.dart, _verifyPurchase posts the store source (google_play or app_store), productID, serverVerificationData, and the signed-in userId to the Dart backend before _handlePurchase grants the in-app reward:
Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async {
final url = Uri.http('$serverIp:8080', '/verifypurchase');
const headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
final response = await http.post(
url,
body: jsonEncode({
'source': purchaseDetails.verificationData.source,
'productId': purchaseDetails.productID,
'verificationData':
purchaseDetails.verificationData.serverVerificationData,
'userId': firebaseNotifier.user?.uid,
}),
headers: headers,
);
if (response.statusCode == 200) {
return true;
} else {
return false;
}
}
Routing and Dart 3 pattern matching in dart-backend/bin/server.dart
On the server, POST /verifypurchase decodes the JSON request body with getPurchaseData using a Dart 3 map pattern and record return type, then delegates verification to the matching store handler:
router.post('/verifypurchase', (Request request) async {
final dynamic payload = json.decode(await request.readAsString());
final (:userId, :source, :productData, :token) = getPurchaseData(payload);
final result = await purchaseHandlers[source]!.verifyPurchase(
userId: userId,
productData: productData,
token: token,
);
if (result) {
return Response.ok('all good!');
} else {
return Response.internalServerError();
}
});
({String userId, String source, ProductData productData, String token})
getPurchaseData(dynamic payload) {
if (payload case {
'userId': String userId,
'source': String source,
'productId': String productId,
'verificationData': String token,
}) {
return (
userId: userId,
source: source,
productData: productDataMap[productId]!,
token: token,
);
} else {
throw const FormatException('Unexpected JSON');
}
}
Verifying Google Play and App Store receipts
- In
dart-backend/lib/google_play_purchase_handler.dart,GooglePlayPurchaseHandlerqueriesandroidPublisher.purchases.products.getfor one-time products andandroidPublisher.purchases.subscriptions.getfor subscriptions, strips..#renewal suffixes from subscription order IDs usingextractOrderId, and writes the resultingNonSubscriptionPurchaseorSubscriptionPurchaseto Cloud Firestore usingiapRepository. - In
dart-backend/lib/app_store_purchase_handler.dart,AppStorePurchaseHandlercalls_iTunesAPI.verifyReceiptusing theapp_store_server_sdkpackage and persists each verified receipt inresponse.latestReceiptInfoto Cloud Firestore.
Run and test the backend
Start the backend server from dart-backend/:
cd dart-backend
dart run bin/server.dart
11. Keep track of purchases
Subscriptions can renew, expire, or be canceled outside your app. In this step, you configure the backend to poll store billing updates from Google Cloud Pub/Sub and the App Store Server API, and update the Flutter client to reactively sync the user's active entitlements from Cloud Firestore using IAPRepo.
Configure Cloud Pub/Sub and App Store Server API keys
Google Play Cloud Pub/Sub setup
- Set
googleCloudProjectIdindart-backend/lib/constants.dartto your Google Cloud and Firebase project ID. - Open the Cloud Pub/Sub Topics page in the Google Cloud Console, ensure your project is selected, and click + Create Topic.

- Set the Topic ID to
play_billing(matchinggooglePlayPubsubBillingTopicindart-backend/lib/constants.dart, which automatically creates a default subscriptionplay_billing-sub), and click Create.
- Open the three-dot menu on your
play_billingtopic and select View permissions.
- Click Add principal, enter
google-play-developer-notifications@system.gserviceaccount.com, assign the Pub/Sub Publisher role, and click Save.
- Copy the full topic name, open your app in the Google Play Console, go to Monetize with Play > Monetization setup, paste the topic name, and click Save changes.

App Store Server API key setup
- Sign in to App Store Connect and select Users and Access.
- Navigate to Integrations > Keys > In-App Purchase and click the + button to generate a new key (for example,
Codelab key). - Download the
.p8key file and save it asdart-backend/assets/SubscriptionKey.p8. - Copy the Key ID and Issuer ID into
appStoreKeyIdandappStoreIssuerIdindart-backend/lib/constants.dart.

Prompt Antigravity to poll store events and synchronize client state
Send the following prompt in Antigravity:
1. In `dart-backend/`:
- Update `GooglePlayPurchaseHandler` in `dart-backend/lib/google_play_purchase_handler.dart` to accept `pubsub.PubsubApi pubsubApi` from `package:googleapis/pubsub/v1.dart`, start a 10-second `Timer.periodic` calling `_pullMessageFromPubSub()`, decode base64 Pub/Sub messages in `_processMessage(String data64, String? ackId)` (handling `testNotification`, `subscriptionNotification`, and `oneTimeProductNotification`), and acknowledge processed messages in `_ackMessage(String id)`.
- Update `AppStorePurchaseHandler` in `dart-backend/lib/app_store_purchase_handler.dart` to accept `AppStoreServerAPI appStoreServerAPI`, start a 10-second `Timer.periodic` calling `_pullStatus()`, query `appStoreServerAPI.getAllSubscriptionStatuses(purchase.orderId)` for active App Store subscriptions in `iapRepository`, and update their expiration date and `SubscriptionStatus` in Firestore.
- Update `dart-backend/bin/server.dart` to add `pubsub.PubsubApi.cloudPlatformScope` to the Google Play client scopes, construct `PubsubApi` and `AppStoreServerAPI` (reading `assets/SubscriptionKey.p8` and caching JWT tokens in `assets/appstore.token`), and pass them to `GooglePlayPurchaseHandler` and `AppStorePurchaseHandler`.
- Create unit tests in `dart-backend/test/firebase_backend_dart_test.dart` verifying `extractOrderId` (with and without a `..0` suffix) and `getPurchaseData` (valid and invalid payloads).
2. In `app/`:
- Update `DashPurchases` in `app/lib/logic/dash_purchases.dart` (and its provider in `app/lib/main.dart`) to accept `this.iapRepo` (`IAPRepo`), register `iapRepo.addListener(purchasesUpdate)` in the constructor and `iapRepo.removeListener(purchasesUpdate)` in `dispose()`, and implement `purchasesUpdate()` and `_updateStatus(PurchasableProduct product, ProductStatus status)` (setting `product.status = status` when `product.status != status`) so `iapRepo.hasActiveSubscription` applies or removes the paid counter multiplier and `iapRepo.hasUpgrade` updates `_beautifiedDashUpgrade` and product statuses.
Understanding the generated code
Polling Google Play Pub/Sub and the App Store Server API on the backend
In dart-backend/lib/google_play_purchase_handler.dart, _pullMessageFromPubSub polls the projects/$googleCloudProjectId/subscriptions/$googlePlayPubsubBillingTopic-sub subscription every 10 seconds, decodes each base64 notification payload, re-runs handleSubscription or handleNonSubscription to refresh Firestore, and acknowledges the message using _ackMessage:
Future<void> _pullMessageFromPubSub() async {
print('Polling Google Play messages');
final request = pubsub.PullRequest(maxMessages: 1000);
final topicName =
'projects/$googleCloudProjectId/subscriptions/$googlePlayPubsubBillingTopic-sub';
final pullResponse = await pubsubApi.projects.subscriptions.pull(
request,
topicName,
);
final messages = pullResponse.receivedMessages ?? [];
for (final message in messages) {
final data64 = message.message?.data;
if (data64 != null) {
await _processMessage(data64, message.ackId);
}
}
}
Similarly, in dart-backend/lib/app_store_purchase_handler.dart, _pullStatus queries appStoreServerAPI.getAllSubscriptionStatuses(purchase.orderId) every 10 seconds and updates each subscription's expiryDate and SubscriptionStatus (active or expired) in Cloud Firestore.
Synchronizing Firestore purchases on the device
In app/lib/repo/iap_repo.dart, IAPRepo listens to the authenticated user's purchases documents in Cloud Firestore in real time and computes hasActiveSubscription and hasUpgrade:
var purchaseStream = _firestore
.collection('purchases')
.where('userId', isEqualTo: user.uid)
.snapshots();
_purchaseSubscription = purchaseStream.listen((snapshot) {
purchases = snapshot.docs.map((document) {
var data = document.data();
return PastPurchase.fromJson(data);
}).toList();
hasActiveSubscription = purchases.any(
(element) =>
element.productId == storeKeySubscription &&
element.status != Status.expired,
);
hasUpgrade = purchases.any(
(element) => element.productId == storeKeyUpgrade,
);
notifyListeners();
});
Whenever IAPRepo notifies its listeners, DashPurchases.purchasesUpdate() in app/lib/logic/dash_purchases.dart enables or disables the 10x click multiplier, toggles _beautifiedDashUpgrade, and updates the product statuses displayed on PurchasePage:
void purchasesUpdate() {
var subscriptions = <PurchasableProduct>[];
var upgrades = <PurchasableProduct>[];
if (products.isNotEmpty) {
subscriptions = products
.where((element) => element.productDetails.id == storeKeySubscription)
.toList();
upgrades = products
.where((element) => element.productDetails.id == storeKeyUpgrade)
.toList();
}
if (iapRepo.hasActiveSubscription) {
counter.applyPaidMultiplier();
for (var element in subscriptions) {
_updateStatus(element, ProductStatus.purchased);
}
} else {
counter.removePaidMultiplier();
for (var element in subscriptions) {
_updateStatus(element, ProductStatus.purchasable);
}
}
if (iapRepo.hasUpgrade != _beautifiedDashUpgrade) {
_beautifiedDashUpgrade = iapRepo.hasUpgrade;
for (var element in upgrades) {
_updateStatus(
element,
_beautifiedDashUpgrade
? ProductStatus.purchased
: ProductStatus.purchasable,
);
}
notifyListeners();
}
}
void _updateStatus(PurchasableProduct product, ProductStatus status) {
if (product.status != status) {
product.status = status;
notifyListeners();
}
}
Run and test the app and backend
Run the unit and widget tests across both projects to verify that everything analyzes and passes cleanly:
cd dart-backend
dart test
cd ../app
flutter test
12. Congratulations
Congratulations! You have collaborated with Google Antigravity to build a full-stack in-app purchase integration in Flutter with a Dart verification backend.
What you've built
- Configured consumable (
dash_consumable_2k), non-consumable (dash_upgrade_3d), and auto-renewing subscription (dash_subscription_doubler) products in App Store Connect and Google Play Console. - Connected the Dash Clicker Flutter app (
app/) to thein_app_purchaseplugin, querying product details and listening topurchaseStream. - Built a Dart
shelfbackend (dart-backend/) that verifies purchase tokens with the Google Play Android Developer API and App Store, polls billing updates using Cloud Pub/Sub and the App Store Server API, and persists purchase state in Cloud Firestore. - Synchronized verified purchase entitlements back to the Flutter client in real time using
IAPRepo.
Next steps
- Add Firebase Auth ID token verification middleware to
POST /verifypurchaseindart-backend/bin/server.dart. - Deploy
dart-backend/to Cloud Run and configure push webhooks for Google Cloud Pub/Sub and App Store Server Notifications.






