restorePastPurchases method

Future<void> restorePastPurchases(
  1. BuildContext context,
  2. ListenerManager listenerManager
)

Implementation

Future<void> restorePastPurchases(
    BuildContext context, ListenerManager listenerManager) async {
  try {
    // Get a list of available purchases from the store.
    await FlutterInappPurchase.instance
        .getAvailablePurchases()
        .then((purchasedItems) async {
      log('Available purchases -------------> ${purchasedItems?.length}');

      if (purchasedItems != null) {
        // Iterate over each purchased item.
        for (var purchasedItem in purchasedItems) {
          if (Platform.isAndroid) {
            // On Android, decode the transaction receipt and check if it's acknowledged.
            var receiptData = json.decode(purchasedItem.transactionReceipt!);
            if (!receiptData['acknowledged']) {
              // Assume verification is successful for now.
              bool isValid = true;
              if (isValid) {
                // Finish the transaction and notify pro status changed listeners.
                await FlutterInappPurchase.instance
                    .finishTransaction(purchasedItem);

                PurchaseHandler().addPurchasedProduct(
                    purchasedItem.productId!, purchasedItem);
                listenerManager
                    .notifyProStatusChangedListeners(purchasedItem);
              }
            } else {
              // If the receipt is acknowledged, notify pro status changed listeners.
              listenerManager.notifyProStatusChangedListeners(purchasedItem);
            }
          } else if (Platform.isIOS) {
            // On iOS, finish the transaction and notify pro status changed listeners.
            await FlutterInappPurchase.instance
                .finishTransaction(purchasedItem);
            await FlutterInappPurchase.instance
                .finishTransactionIOS(purchasedItem.transactionId!);
            listenerManager.notifyProStatusChangedListeners(purchasedItem);
          }
        }
      }
    });
  } catch (e) {
    // Log an error if restoring past purchases fails.
    if (kDebugMode) {
      print("Failed to restore past purchases: $e");
    }
  }
}