createMiddleware method

Middleware<T> createMiddleware()

Implementation

Middleware<T> createMiddleware() {
  return (Store<T> store, dynamic action, NextDispatcher next) {
    final VirtualPumaPayState state = store.state;
    next(action);

    if (action is InitPayAction) {
      // Google Play
      initializeGooglePlay();
      isStoreAvailable().then((available) {
        store.dispatch(SetStoreAvailableAction(storeAvailable: available));
        if (available) {
          print("🛒 InitPayAction Received");
          print(action.productIDs);

          // Init singleton with the subscription
          StreamSubscriptionSingleton().init(store);

          // we retrieve products available on the store
          store.dispatch(GetProductsAction(productIDs: action.productIDs));
        } else {
          print("🚨 Store is not available");
        }
      });
    }

    if (action is IsStoreAvailableAction) {
      isStoreAvailable().then((available) {
        store.dispatch(SetStoreAvailableAction(storeAvailable: available));
        store.dispatch(IsStoreAvailableSuccessAction(available: available));
      });
    }

    if (action is GetProductsAction) {
      getProducts(action.productIDs!).then((products) {
        print("🤑 Products received!");
        print(products);
        store.dispatch(GetProductsSuccessAction(products: products));
      });
    }

    if (action is GetProductsSuccessAction) {
      store.dispatch(RestorePurchaseAction());
    }

    if (action is PurchaseProductAction) {
      Product product = store.state.pumaPayState.products
          .where((o) => o.id == action.productID)
          .first;
      clearTransactionsIos().then((e) {
        purchaseProduct(product);
      });
    }

    if (action is VerifyInAppPurchaseSuccessAction) {
      store.dispatch(SetRestoringPurchaseAction(restoringPurchase: false));
    }

    if (action is RestorePurchaseAction) {
      print("🔄 Restoring Purchase...");
      store.dispatch(SetRestoringPurchaseAction(restoringPurchase: true));
      InAppPurchase.instance.restorePurchases().then((value) {
        print("✅ Done restoring Purchase");
        store.dispatch(SetRestoringPurchaseAction(restoringPurchase: false));
      }, onError: (error) {
        print("⛔️ Error restoring Purchase");
      });
    }

    if (action is VerifyInAppPurchaseAction) {
      print("🕵️‍♂️ Verifying the following Purchase:");
      print("---> storeName: ${action.storeName}");
      print("---> ProductID: ${action.purchaseDetail.productID}");
      print("---> PurchaseID: ${action.purchaseDetail.purchaseID}");
      print("---> Status: ${action.purchaseDetail.status}");
      print("---> Date: ${action.purchaseDetail.transactionDate}");
      print("---> Valid: ${action.purchaseDetail.valid}");
      // print("---> VerificationDatas: ${action.receipt["receipt-data"]}");
      // print("---> Endpoint1: ${state.pumaPayState.verifyEndpoint}");

      var verifyEndpoint = "";
      if (state.pumaPayState.verifyEndpoint != null) {
        var body;
        if (Platform.isAndroid) {
          final receiptData = json.decode(action.receipt["receipt-data"]);
          body = {
            "productID": action.productID,
            "storeName": action.storeName,
            "packageName": receiptData["packageName"],
            "data": receiptData["purchaseToken"]
          };
        }
        if (Platform.isIOS) {
          body = {
            "productID": action.productID,
            "storeName": action.storeName,
            "data": action.receipt["receipt-data"],
          };
        }

        print("🚦 Calling provided endpoint with body = $body");
        // we use our server API route to check the receipt
        store.dispatch(VerifyInAppPurchaseWithEndpointAction(
            body: body,
            storeName: action.storeName,
            productID: action.productID,
            purchaseDetail: action.purchaseDetail,
            path: state.pumaPayState.verifyEndpoint!));
      } else {
        if (action.storeName == android) {
          final receiptData = json.decode(action.receipt["receipt-data"]);
          // TO-DO
          verifyEndpoint =
              "$googlePlayEndpoint/androidpublisher/v3/applications/${receiptData["packageName"]}/purchases/subscriptions/${receiptData["productId"]}/tokens/${receiptData["purchaseToken"]}";
        } else if (action.storeName == ios) {
          verifyEndpoint = "$appStoreEndpoint$appStoreVerifyRoute";
        }

        if (action.storeName == ios) {
          store.dispatch(
            VerifyInAppPurchaseWithoutEndpointAction(
              body: action.receipt,
              purchaseDetail: action.purchaseDetail,
              storeName: action.storeName,
              productID: action.productID,
              path: verifyEndpoint,
            ),
          );
        }
      }
    }

    if (action is ApiErrorAction) {
      if (action.originAction != null &&
          (action.originAction is VerifyInAppPurchaseWithEndpointAction ||
              action.originAction
                  is VerifyInAppPurchaseWithoutEndpointAction)) {
        final castAction =
            action.originAction as VerifyInAppPurchaseWithEndpointAction;

        print(
            "### ${castAction.purchaseDetail.purchaseID} is invalid (${action.error.description})");

        store.dispatch(VerifyInAppPurchaseErrorAction(
            productID: castAction.productID,
            purchaseDetail: castAction.purchaseDetail));
      }
    }
  };
}