Skip to content
Flutter SDK

Flutter purchases and entitlements

Native App Store and Google Play purchases with server verification, restore, the entitlement cache, and credit balances.

On this page

Paid access comes only from the server. The store callback on the device never unlocks anything. The flow is:

Code
purchase intent  →  native store sheet  →  server verify  →  finish transaction  →  entitlement refresh
POST /v1/commerce/   StoreKit 2 /          POST /v1/commerce/   StoreBridge.finish()   GET /v1/entitlements/me
purchase-intents     Play Billing          purchases/verify     (only after accept)

Concepts: Entitlements and credits. Store setup: App Store Connect, Google Play. Endpoints: Commerce API, Catalog API, Entitlements API.

Warning

Not yet enabled: real store testing. Every state below is fixture-tested with a fake StoreBridge. No StoreKit sandbox or Play license-tester purchase has been made through the SDK.

Only the native stores are supported: apple and google_play. The contract also lists razorpay and stripe checkout actions (web_redirect, web_sdk). The SDK treats any checkout action that is not native_store as PurchaseStage.unavailable.

Attach the store at startup

Dart
if (core.capabilities.public.purchaseProviders.isNotEmpty) {
  await core.commerce.attach(IapStoreBridge()); // reference adapter, examples/flutter-reference/lib/adapters/iap_store.dart
}

Attach once, early. The store redelivers transactions that were not finished, for example when the app was killed mid-purchase. attach subscribes to StoreBridge.transactions, so those are verified and finished at the next launch. core.commerce throws FEATURE_UNAVAILABLE when no purchase provider is enabled.

The StoreBridge port:

Dart
abstract class StoreBridge {
  String get provider; // 'apple' | 'google_play'
  Future<bool> isAvailable();
  Future<List<StoreProduct>> queryProducts(Set<String> providerProductIds);
  Future<void> buy(StoreProduct product, {required String accountBinding, String? basePlanId, String? offerRef});
  Stream<List<StoreTransaction>> get transactions;
  Future<void> finish(StoreTransaction tx); // only after the server accepted it
  Future<void> restore();
}

Show products

Catalog products come from AppCore. Prices come only from the store, localized. Never take them from remote config or the catalog.

Dart
final commerce = core.commerce;
final catalog = await commerce.products();                     // Page<CatalogProduct>
final store = await commerce.storeProducts(catalog.items);     // Map<providerProductId, StoreProduct>
final provider = Platform.isIOS ? 'apple' : 'google_play';

for (final p in catalog.items) {
  final mapping = p.mappingFor(provider);                      // only status == 'active' mappings
  final sp = mapping == null ? null : store[mapping.productId];
  if (sp != null) print('${p.name}: ${sp.price} ${sp.billingPeriod ?? ''}');
}

commerce.plans() returns the raw GET /v1/catalog/plans body (Map<String, dynamic>).

Buy

purchase() starts the flow and returns early. Follow the outcome on commerce.states:

Dart
final sub = commerce.states.listen((s) {
  switch (s.stage) {
    case PurchaseStage.verified:
      // entitlements were refreshed; s.purchase is the VerifiedPurchase
      break;
    case PurchaseStage.conflict:
      // s.problem?.nextAction == NextAction.signInToExistingAccount, or a restore ownership conflict
      break;
    default:
      break;
  }
});

if (await commerce.available()) {
  await commerce.purchase(product, storeProduct);
}

What purchase does:

  1. If no store is attached, isAvailable() is false, or the store's provider is not enabled, it emits unavailable and creates no intent.
  2. POST /v1/commerce/purchase-intents with {provider, catalog_product_id}. This is never retried automatically. A 409 becomes conflict; any other error becomes failed.
  3. It remembers the intent id for this provider product. The record is bound to the signed-in user and kept in secure storage.
  4. bridge.buy(...) with the server's account_binding. That becomes StoreKit's appAccountToken or Play's obfuscatedAccountId. basePlanId and offerRef come from the server's checkout action.

When the store reports purchased, the SDK calls POST /v1/commerce/purchases/verify with intent_id, provider, transaction_reference and verification_payload. Apple sends the transaction id and the signed JWS. Google Play sends the purchaseToken and no payload. The Idempotency-Key is derived from provider and the transaction reference. A redelivered transaction therefore reuses the same key and cannot be charged or granted twice.

Purchase stages

PurchaseStageMeaningTransaction finished?
unavailableBilling unavailable, provider disabled, or the checkout action is not native_store (reason says which)—
creatingIntent, awaitingStoreIn progress—
pendingStore "ask to buy" or deferred payment, or the server answered pending. Nothing is granted.No
cancelledUser closed the sheet. Nothing was charged. The SDK tracks product.purchase_ui_cancelled.v1 if analytics consent is on.Yes (nothing to keep)
verifyingServer verification in progressNo
verificationDelayedRetryable failure (network, 429, 5xx other than FEATURE_UNAVAILABLE). The store redelivers it and the SDK verifies again with the same key.No
verifiedServer accepted it; entitlements refreshedYes
restoring, restoredRestore in progress / restore job succeededYes, after success
conflict409, for example PURCHASE_OWNED_BY_OTHER_ACCOUNT, or a restore job in awaiting_manualNo
failedNon-retryable error, store error (reason = store error code), or a missing transaction referenceNo

defaultPurchaseMessage(state) and the PurchaseStatusBanner widget provide consumer copy for every stage.

A purchased transaction with no remembered intent (bought on another install, or before a reinstall) goes through restore instead of verify.

Google Play consumables (credit packs) are consumed by the server through the Play Developer API after verification, and non-consumables and subscriptions are acknowledged there too. The reference adapter therefore buys every product with buyNonConsumable and only calls completePurchase to finish the client transaction; do not consume on the device yourself.

Warning

Not yet tested: this flow has not been run against Google Play with real sandbox credentials.

Restore

Dart
await commerce.restore(); // emits restoring, then restored | conflict | failed | verificationDelayed

The SDK asks the store to restore and collects the restored transactions for 200 ms. It then sends POST /v1/commerce/restore with up to 100 references (Apple: JWS; Play: purchaseToken), using a key derived from the sorted references. It polls GET /v1/jobs/{id} up to 10 times. The transactions are finished and entitlements refreshed only when the job ends in succeeded. awaiting_manual means the purchase belongs to another account (conflict). A failed or unfinished job leaves the transactions unfinished.

Subscriptions and documents

Warning

Not yet tested: commerce.subscriptions(), commerce.documents() and commerce.plans(). They are implemented, but the fixture server has no routes for them, and they have not been run against a real backend.

Dart
final subs = await commerce.subscriptions(); // Page<Subscription>
for (final s in subs.items) {
  // s.status: pending | trialing | active | grace | on_hold | paused | cancelled_active | expired | revoked
  // s.managementUrl comes from the server; never build a store URL yourself
}
final docs = await commerce.documents();      // Page<FinanceDocument>, amounts as Money (BigInt minor units)

Amounts are always Money, with amountMinor (a BigInt of minor units) and currency. They are never a double.

Entitlements

Dart
final ent = core.entitlements;
final snap = await ent.refresh();                       // GET /v1/entitlements/me, cached for this user
final premium = snap.feature('<entitlement-key>')?.allowed ?? false;

EntitlementSnapshot has features (FeatureAccess: key, allowed, validUntil, reason, value), balances, generatedAt, cacheValidUntil and snapshotVersion.

Cache rules (fixture-tested)

The cache is for display. It is bound to app, environment and user, and another user's snapshot is never returned.

Dart
final view = await ent.view(online: isOnline);           // EntitlementView
view.freshness;                                          // cached | offlineGrace | stale | none
view.displayAllowed('<entitlement-key>');                // badges, labels: display only

// Content already on the device:
final open = await ent.allowsLocalUse('<entitlement-key>', online: isOnline);

// Anything valuable on the server (generate, download, spend):
final ok = await ent.requireLive('<entitlement-key>');   // always hits the server; throws when offline
  • Within cache_valid_until, the snapshot may gate content already on the device (cached).
  • Offline, access stays usable for offlineGrace beyond cache_valid_until (offlineGrace). The default is 15 minutes and the hard maximum is 24 hours. It never extends past the feature's own valid_until.
  • If the device clock is more than 5 minutes before generated_at (a clock rollback), the result is stale, and allowsLocalUse returns false.
  • Sign-out, a user switch and account deletion clear the cache.

The EntitlementsClient that core.entitlements creates uses the default 15-minute grace. AppCore does not expose a setting to change it.

Refresh on app resume. The reference app does this in didChangeAppLifecycleState. The SDK also refreshes after every verified purchase and every successful restore.

EntitlementGate wraps this for display.

Credits and usage

Balances arrive in the same snapshot:

Dart
for (final b in snap.balances) {
  // b.key, b.availableUnits (BigInt), b.reservedUnits (BigInt)
}

The app reads balances. It never spends them. Usage is reserved and finalized by your backend through POST /v1/entitlements/reservations and POST /v1/entitlements/reservations/{id}, which need a service capability, not a consumer session. A client cannot debit or grant credits. After your backend uses credits, call refresh() to show the new balance. See Entitlements and credits.