m7c: Play Billing and a complete deletion path
- billing module with a testable seam: models (product ids, purchase events), StoreClient + PlayStoreClient over in_app_purchase, Entitlements persisted in SharedPreferences, BillingService orchestrating query/buy/restore/grant. - rules encoded: grant before completePurchase (Play refunds unacknowledged purchases after three days), pending purchases are shown but never granted, restorePurchases on start so a reinstall keeps the purchase, and Remove Ads only hides interstitials - rewarded video stays available. - ads gate: AdsService.adsRemoved stops both the counter and the preload, so an owner never requests an interstitial. - settings sheet: shop section (price from the store, never hardcoded), "restore purchases", and "delete local data" with confirmation; the existing mail-based deletion request stays the account-deletion path since the app has no accounts. - 9 new tests with a fake store cover purchase, restore, pending, cancel, error, restart persistence, missing store and a store that throws. 17 total. - verified on device: the app talks to the real Play Billing service (IInAppBillingService in logcat) and degrades to "no products created" without a crash; com.android.vending.BILLING is in the merged manifest. - docs: monetization 7c (rules + verification), decision D6 (local entitlement until purchases affect the server), compliance rows for billing/restore/ deletion, blocked.md 3c (create remove_ads in the Console). - release 0.9.0 (13).
This commit is contained in:
@@ -30,6 +30,10 @@ class AdsService {
|
||||
InterstitialAd? _interstitial;
|
||||
bool _started = false;
|
||||
bool _adsAllowed = false;
|
||||
|
||||
/// Set from the store entitlements ("Remove Ads"). Owners never see an
|
||||
/// interstitial; rewarded video stays available on purpose.
|
||||
bool adsRemoved = false;
|
||||
int _matchesFinished = 0;
|
||||
|
||||
ConsentStatus _consentStatus = ConsentStatus.unknown;
|
||||
@@ -168,6 +172,7 @@ class AdsService {
|
||||
}
|
||||
|
||||
void _loadInterstitial() {
|
||||
if (adsRemoved) return; // owner: never request an interstitial
|
||||
InterstitialAd.load(
|
||||
adUnitId: interstitialUnitId,
|
||||
request: const AdRequest(),
|
||||
@@ -215,7 +220,7 @@ class AdsService {
|
||||
|
||||
/// Called when a match ends; applies the frequency caps from the GDD.
|
||||
void onMatchFinished() {
|
||||
if (!_adsAllowed) return;
|
||||
if (!_adsAllowed || adsRemoved) return;
|
||||
_matchesFinished++;
|
||||
if (_matchesFinished <= skipFirstMatches) return;
|
||||
if (_matchesFinished % everyNthMatch != 0) return;
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'entitlements.dart';
|
||||
import 'models.dart';
|
||||
import 'store_client.dart';
|
||||
|
||||
/// Orchestrates the store: product query, purchase, restore, entitlement write.
|
||||
///
|
||||
/// Rules from docs/monetization.md:
|
||||
/// * prices come from the store, never from the app;
|
||||
/// * `queryPurchases` on start, so a reinstall restores what was bought;
|
||||
/// * pending transactions are reported but never granted;
|
||||
/// * every purchased/restored item is completed (Play refunds after 3 days).
|
||||
class BillingService extends ChangeNotifier {
|
||||
BillingService({required this.entitlements, required this.client});
|
||||
|
||||
final Entitlements entitlements;
|
||||
final StoreClient client;
|
||||
|
||||
StreamSubscription<PurchaseEvent>? _sub;
|
||||
final Map<String, StoreProduct> _products = {};
|
||||
|
||||
bool _available = false;
|
||||
bool _busy = false;
|
||||
bool _initialised = false;
|
||||
String? _error;
|
||||
|
||||
bool get available => _available;
|
||||
bool get busy => _busy;
|
||||
bool get initialised => _initialised;
|
||||
String? get error => _error;
|
||||
bool get adsRemoved => entitlements.adsRemoved;
|
||||
|
||||
StoreProduct? product(String id) => _products[id];
|
||||
Iterable<StoreProduct> get products => _products.values;
|
||||
|
||||
/// True when the store answered and offered at least one product.
|
||||
bool get canPurchase => _available && _products.isNotEmpty;
|
||||
|
||||
Future<void> init() async {
|
||||
if (_initialised) return;
|
||||
_initialised = true;
|
||||
_sub = client.events.listen(_onEvent);
|
||||
|
||||
try {
|
||||
_available = await client.isAvailable();
|
||||
} catch (e) {
|
||||
_available = false;
|
||||
_error = 'Play Store nicht erreichbar';
|
||||
}
|
||||
if (!_available) {
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
await refreshProducts();
|
||||
// Owned products are re-delivered through the event stream.
|
||||
await restore(silent: true);
|
||||
}
|
||||
|
||||
Future<void> refreshProducts() async {
|
||||
if (!_available) return;
|
||||
try {
|
||||
final found = await client.queryProducts(ProductIds.offered);
|
||||
_products
|
||||
..clear()
|
||||
..addEntries(found.map((p) => MapEntry(p.id, p)));
|
||||
_error = found.isEmpty ? 'Keine Produkte im Play Store angelegt' : null;
|
||||
} catch (e) {
|
||||
_error = 'Produkte konnten nicht geladen werden';
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Starts the purchase flow. The result arrives asynchronously via the
|
||||
/// stream - this only reports whether the flow could be started at all.
|
||||
Future<bool> buy(String productId) async {
|
||||
final item = _products[productId];
|
||||
if (item == null) {
|
||||
_error = 'Produkt nicht verfügbar';
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
_busy = true;
|
||||
_error = null;
|
||||
notifyListeners();
|
||||
try {
|
||||
final started = await client.buy(item);
|
||||
if (!started) _error = 'Kauf konnte nicht gestartet werden';
|
||||
return started;
|
||||
} catch (e) {
|
||||
_error = 'Kauf abgebrochen: $e';
|
||||
return false;
|
||||
} finally {
|
||||
_busy = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> restore({bool silent = false}) async {
|
||||
if (!_available) return;
|
||||
_busy = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
await client.restore();
|
||||
} catch (e) {
|
||||
if (!silent) _error = 'Wiederherstellen fehlgeschlagen';
|
||||
} finally {
|
||||
_busy = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onEvent(PurchaseEvent event) async {
|
||||
switch (event.state) {
|
||||
case PurchaseState.purchased:
|
||||
case PurchaseState.restored:
|
||||
// Grant first, then complete: a crash in between re-delivers the
|
||||
// purchase instead of losing it.
|
||||
await entitlements.grant(event.productId);
|
||||
await client.complete(event);
|
||||
_error = null;
|
||||
break;
|
||||
case PurchaseState.pending:
|
||||
_error = 'Kauf wird geprüft (pending)';
|
||||
break;
|
||||
case PurchaseState.canceled:
|
||||
_error = null;
|
||||
break;
|
||||
case PurchaseState.error:
|
||||
_error = event.error ?? 'Kauf fehlgeschlagen';
|
||||
break;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_sub?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'models.dart';
|
||||
|
||||
/// Non-consumable products the player owns, persisted on the device.
|
||||
///
|
||||
/// The Play Console is the source of truth for money; this is the local mirror
|
||||
/// that the UI and the ad gate read. `BillingService` only grants after the
|
||||
/// store reported `purchased` or `restored`, and every grant is written through
|
||||
/// to disk immediately.
|
||||
class Entitlements extends ChangeNotifier {
|
||||
Entitlements._(this._prefs, this._owned);
|
||||
|
||||
static const String storageKey = 'iron_arc.entitlements';
|
||||
|
||||
final SharedPreferences _prefs;
|
||||
final Set<String> _owned;
|
||||
|
||||
static Future<Entitlements> load() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final owned = prefs.getStringList(storageKey)?.toSet() ?? <String>{};
|
||||
return Entitlements._(prefs, owned);
|
||||
}
|
||||
|
||||
Set<String> get owned => Set.unmodifiable(_owned);
|
||||
|
||||
bool owns(String productId) => _owned.contains(productId);
|
||||
|
||||
/// Interstitials are hidden for owners; rewarded video stays opt-in.
|
||||
bool get adsRemoved => owns(ProductIds.removeAds);
|
||||
|
||||
Future<void> grant(String productId) async {
|
||||
if (!_owned.add(productId)) return;
|
||||
await _prefs.setStringList(storageKey, _owned.toList());
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Used when the store reports that a product is no longer owned (refund).
|
||||
Future<void> revoke(String productId) async {
|
||||
if (!_owned.remove(productId)) return;
|
||||
await _prefs.setStringList(storageKey, _owned.toList());
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> clearAll() async {
|
||||
if (_owned.isEmpty) return;
|
||||
_owned.clear();
|
||||
await _prefs.remove(storageKey);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/// Product catalogue. Ids must match the entries created in the Play Console -
|
||||
/// prices are **never** hardcoded in the app, the store returns them.
|
||||
///
|
||||
/// Only [removeAds] is wired into the UI so far (M7c); the rest of the table in
|
||||
/// docs/monetization.md needs the economy that does not exist yet.
|
||||
abstract final class ProductIds {
|
||||
/// Non-consumable: hides interstitials. Rewarded video stays opt-in.
|
||||
static const String removeAds = 'remove_ads';
|
||||
|
||||
/// Documents the seasonal pass that will follow in MVP-3.
|
||||
static const String seasonPass = 'season_pass';
|
||||
|
||||
/// Consumable hard currency - needs server-side bookkeeping, not wired yet.
|
||||
static const String coresSmall = 'cores_small';
|
||||
|
||||
static const Set<String> all = {removeAds, seasonPass, coresSmall};
|
||||
|
||||
/// Products the UI offers today.
|
||||
static const Set<String> offered = {removeAds};
|
||||
}
|
||||
|
||||
/// One purchasable item as the store describes it.
|
||||
class StoreProduct {
|
||||
const StoreProduct({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.price,
|
||||
this.raw,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String title;
|
||||
final String price;
|
||||
final Object? raw;
|
||||
|
||||
@override
|
||||
String toString() => '$id ($price)';
|
||||
}
|
||||
|
||||
/// State of a purchase event, mapped from the platform.
|
||||
enum PurchaseState { pending, purchased, restored, canceled, error }
|
||||
|
||||
class PurchaseEvent {
|
||||
const PurchaseEvent({
|
||||
required this.productId,
|
||||
required this.state,
|
||||
this.error,
|
||||
this.complete = false,
|
||||
this.raw,
|
||||
});
|
||||
|
||||
final String productId;
|
||||
final PurchaseState state;
|
||||
final String? error;
|
||||
|
||||
/// True when the platform waits for `completePurchase` (Play: acknowledge
|
||||
/// within three days, otherwise the purchase is refunded automatically).
|
||||
final bool complete;
|
||||
final Object? raw;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:in_app_purchase/in_app_purchase.dart';
|
||||
|
||||
import 'models.dart';
|
||||
|
||||
/// Thin seam over the platform billing plugin.
|
||||
///
|
||||
/// Everything above this interface (entitlements, UI) is testable with a fake
|
||||
/// implementation; only [PlayStoreClient] touches the real store.
|
||||
abstract class StoreClient {
|
||||
/// Emits every purchase state change, including restored purchases.
|
||||
Stream<PurchaseEvent> get events;
|
||||
|
||||
Future<bool> isAvailable();
|
||||
|
||||
Future<List<StoreProduct>> queryProducts(Set<String> ids);
|
||||
|
||||
/// Returns false when the platform refused to start the flow.
|
||||
Future<bool> buy(StoreProduct product);
|
||||
|
||||
/// Acknowledge/consume - must happen or Play refunds after three days.
|
||||
Future<void> complete(PurchaseEvent event);
|
||||
|
||||
/// Re-delivers owned non-consumables through [events].
|
||||
Future<void> restore();
|
||||
|
||||
Future<void> dispose();
|
||||
}
|
||||
|
||||
/// Google Play implementation.
|
||||
class PlayStoreClient implements StoreClient {
|
||||
PlayStoreClient({InAppPurchase? iap}) : _iap = iap ?? InAppPurchase.instance {
|
||||
_subscription = _iap.purchaseStream.listen(_onPurchases);
|
||||
}
|
||||
|
||||
final InAppPurchase _iap;
|
||||
late final StreamSubscription<List<PurchaseDetails>> _subscription;
|
||||
final StreamController<PurchaseEvent> _out = StreamController.broadcast();
|
||||
|
||||
@override
|
||||
Stream<PurchaseEvent> get events => _out.stream;
|
||||
|
||||
@override
|
||||
Future<bool> isAvailable() => _iap.isAvailable();
|
||||
|
||||
@override
|
||||
Future<List<StoreProduct>> queryProducts(Set<String> ids) async {
|
||||
final response = await _iap.queryProductDetails(ids);
|
||||
if (response.error != null) {
|
||||
throw StateError(response.error!.message);
|
||||
}
|
||||
return response.productDetails
|
||||
.map((d) => StoreProduct(
|
||||
id: d.id,
|
||||
title: d.title,
|
||||
price: d.price,
|
||||
raw: d,
|
||||
))
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> buy(StoreProduct product) async {
|
||||
final details = product.raw;
|
||||
if (details is! ProductDetails) return false;
|
||||
return _iap.buyNonConsumable(
|
||||
purchaseParam: PurchaseParam(productDetails: details),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> complete(PurchaseEvent event) async {
|
||||
final raw = event.raw;
|
||||
if (raw is PurchaseDetails && raw.pendingCompletePurchase) {
|
||||
await _iap.completePurchase(raw);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> restore() => _iap.restorePurchases();
|
||||
|
||||
void _onPurchases(List<PurchaseDetails> purchases) {
|
||||
for (final p in purchases) {
|
||||
_out.add(PurchaseEvent(
|
||||
productId: p.productID,
|
||||
state: switch (p.status) {
|
||||
PurchaseStatus.pending => PurchaseState.pending,
|
||||
PurchaseStatus.purchased => PurchaseState.purchased,
|
||||
PurchaseStatus.restored => PurchaseState.restored,
|
||||
PurchaseStatus.canceled => PurchaseState.canceled,
|
||||
PurchaseStatus.error => PurchaseState.error,
|
||||
},
|
||||
error: p.error?.message,
|
||||
complete: p.pendingCompletePurchase,
|
||||
raw: p,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> dispose() async {
|
||||
await _subscription.cancel();
|
||||
await _out.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user