purchaseWithOffer method

  1. @override
Future<void> purchaseWithOffer(
  1. PaywallProduct product,
  2. PurchaseOfferPreference offer
)
override

Implementation

@override
Future<void> purchaseWithOffer(PaywallProduct product, PurchaseOfferPreference offer) async {
  _checkActive();
  await ready;
  _checkActive();
  final response = await store.queryProductDetails({product.storeId});
  if (response.error != null) throw StateError(response.error!.message);
  _checkActive();
  final candidates = response.productDetails.where((d) => d.id == product.storeId).toList();
  if (candidates.isEmpty) throw StateError('Store product not found: ${product.storeId}');
  ProductDetails? selected;
  for (final candidate in candidates) {
    final value = await metadata.fromDetails(product.slot, candidate);
    if (value.basePlanId != product.basePlanId) continue;
    if (value.currency != product.currency || value.rawPrice != product.rawPrice || value.price != product.price) continue;
    final matches = switch (offer) {
      PurchaseOfferPreference.storeDefault => product.trial == null || (value.eligibleForTrial && value.trial != null),
      PurchaseOfferPreference.trial => value.eligibleForTrial && value.trial != null,
      PurchaseOfferPreference.standard => await _isStandard(candidate),
    };
    if (matches) { selected = candidate; break; }
  }
  if (selected == null) throw StateError('The requested ${offer.name} offer is unavailable for this account');
  final parameter = selected is GooglePlayProductDetails
      ? GooglePlayPurchaseParam(productDetails: selected, offerToken: selected.offerToken)
      : PurchaseParam(productDetails: selected);
  _checkActive();
  final started = await store.buyNonConsumable(purchaseParam: parameter);
  if (!started) _emit(PaywallResult(PaywallOutcome.canceled, productId: product.storeId));
}