← NewsGuide · Flutter

Flutter In-App Purchases on Android: Offer Token & Restore

Articles#Flutter#in_app_purchase#Google Play Billing#in-app purchases#Android#Dart#game dev

In a Flutter game a purchase rarely breaks on the "Buy" button itself. It breaks at the edges: when Play returns a product with a list of offers, when a restore runs without a Google account, when a transaction is never closed. We hit all three in AI Inc: Tycoon: after a release, Crashlytics showed an INVALID_OFFER_TOKEN crash on a tablet, right inside the game's shop. Below are seven steps to set up in_app_purchase for Android so the game doesn't close, plus the four tests that keep it that way.

In short:

  • One product ID: the same in the console and in the game.
  • One listener on the purchase stream for the whole process, not one per purchase.
  • Buy a product that comes with a list of offers using an offer token; an empty list means don't buy.
  • Wrap buyNonConsumable in try … on PlatformException and restorePurchases in try … on Exception.
  • Grant the entitlement before closing the transaction, and always call completePurchase.
  • Move the logic that picks purchase parameters into its own function and test it without a phone.

Step 1. Use one product ID

The ID in Play Console must match the key under which the game stores what was bought. Don't create a second name: any "store → game" table becomes a second source of truth and drifts from the first at the very next new product. Then a player pays for something they never receive. In our project this is the id field of the shop catalog, and a separate test checks that the IDs match.

Decide the product type deliberately, too. Everything our game sells is a look that stays forever, so these are non-consumable purchases (buyNonConsumable). A consumable product would mean a currency, and the game has none.

Step 2. Subscribe to the purchase stream once

The plugin's purchaseStream is one per process and delivers everything: what was just bought, what was restored, and what was paid later between launches. Subscribe to it at startup and handle events by status.

_sub ??= _store.purchaseStream.listen(_onPurchases);

Two subscriptions would handle one purchase twice, and the ??= operator doesn't let a second one appear. In the game the subscription also has onDone and onError; they are shortened here.

Step 3. Build the purchase parameter and don't forget the token

This is where we got caught. The in_app_purchase_android package, version 0.5.x, checks the offer token in launchBillingFlow: as soon as a product has a subscriptionOfferDetails list, the plugin demands a token, even if the product is one-time and you never created any offers in the console. We bought the "No ads" product without a token and got INVALID_OFFER_TOKEN.

Now a separate function builds the parameter:

PurchaseParam? purchaseParamFor(List<ProductDetails> found) {
  if (found.isEmpty) return null;
  final play = found.whereType<GooglePlayProductDetails>().toList();
  if (play.isEmpty) return PurchaseParam(productDetails: found.first);
  final d = play.firstWhere(
    (p) => p.productDetails.productType == ProductType.inapp,
    orElse: () => play.first,
  );
  final offers = d.productDetails.subscriptionOfferDetails;
  if (offers == null) return PurchaseParam(productDetails: d);
  if (offers.isEmpty) return null;
  return GooglePlayPurchaseParam(
    productDetails: d,
    offerToken: d.offerToken ?? offers.first.offerIdToken,
  );
}

It reads like this: the store found nothing, so we don't buy; there is no offer list, so a regular purchase; there is a list but it's empty, so we don't buy (the plugin will reject any token); there is a list, so we take the token from it. Because of ProductType and GooglePlayPurchaseParam, we had to add the in_app_purchase_android package to pubspec as a direct dependency.

Step 4. Wrap the purchase itself in try

Even with the right token, the store can refuse. An unhandled PlatformException closes the game right on the button, and the player only sees that the app crashed.

bool started;
try {
  started = await _store.buyNonConsumable(purchaseParam: param);
} on PlatformException catch (e) {
  debugPrint('purchase $id: ${e.code}');
  started = false;
}
if (!started) {
  _waiting.remove(id);
  return false;
}

A refusal becomes an ordinary "didn't work": the game tells the player and breaks nothing. Two more small things: limit the wait for a reply with a timeout (we wait three minutes), and remember that a late payment still arrives through the stream.

Step 5. Grant the entitlement before closing the transaction

For every event from the stream, work in this order: check the status, grant the entitlement, close the transaction.

for (final p in list) {
  final ok = p.status == PurchaseStatus.purchased ||
      p.status == PurchaseStatus.restored;
  if (ok) {
    purchaseGranted?.call(
      p.productID,
      restored: p.status == PurchaseStatus.restored,
    );
  }
  if (p.pendingCompletePurchase) await _store.completePurchase(p);
  if (p.status == PurchaseStatus.pending) continue;
  _waiting.remove(p.productID)?.complete(ok);
}

The order matters. If the game were interrupted between closing the transaction and granting the entitlement, the player would be left with something paid for but locked. And you must always close pendingCompletePurchase, otherwise the store considers the purchase unfinished and returns it on every launch. Besides, under Play Billing rules Google refunds unacknowledged purchases to the player after a few days. So close every transaction the plugin asks you to close.

Step 6. Restore must be able to stay quiet

A quiet restore on every game start is a good idea, but restorePurchases throws when Play didn't answer: no Google account, no network, or Play isn't ready. Unhandled, it becomes a "fatal" in Crashlytics. We wrapped the call and added a separate flag so the "Restore purchases" button can honestly say "Google Play isn't responding".

try {
  await _store.restorePurchases();
} on Exception catch (e) {
  debugPrint('restore: $e');
  _restoreFailed = true;
  return {..._restored};
}
await Future<void>.delayed(const Duration(seconds: 2));
return {..._restored};

The two-second pause is not a flaw but a consequence of the answer arriving through a stream, while the store never says "nothing more will come". We return what managed to arrive. If something is missing, the restore can be repeated.

Step 7. Write four tests

The parameter-picking function is pure, so ordinary flutter test checks it without a phone or Play. Four cases were enough for us:

  1. A regular one-time product is bought as before, without a token.
  2. A product with a list of offers is bought with a token from that product's list.
  3. An empty offer list means don't buy.
  4. The store found nothing, so don't buy.

These tests appeared after the real crash. Now a similar error will show up in tests, not in Crashlytics.

Checklist

  • ✓ The product ID is the same in the console and in the game.
  • ✓ One subscriber listens to purchaseStream.
  • ✓ A separate function builds the purchase parameter, with tests for the token.
  • ✓ buyNonConsumable and restorePurchases are wrapped in try.
  • ✓ The entitlement is granted before completePurchase, and completePurchase is always called.
  • ✓ The game has a message for the "Play isn't responding" case.

FAQ

Do I need an offer token for a one-time product?

Only if the store returned the product with a list of offers. If subscriptionOfferDetails is null, buy without a token, as in our first test.

Why does "Restore purchases" wait two seconds?

The store delivers the answer through a stream and doesn't say which part is the last. A short pause lets you collect everything that arrived. The player doesn't notice it.

Why must I always close the transaction?

Until it is closed, the store considers the purchase unfinished and returns it on every launch. So close every transaction the plugin asks you to close.

Do I need to add in_app_purchase_android separately?

If you use its types, such as GooglePlayPurchaseParam or ProductType, yes: add it to pubspec.yaml as a direct dependency instead of relying on in_app_purchase to pull it in.


Need purchases, rewarded ads and restore in a mobile game with no surprises at release? We set them up turnkey, with tests. Read more on the services page. For publishers and studios there is cooperation with companies. And for why we chose Flutter, read Flutter vs Unity.