Flutter Google IAP Subscription Front and Server Side Validation

This is kind of over my head, I am successfully created the serverside validation for the subscription but I don’t know where to put it ( From logic perspective ) on my Flutter app.

Now in Flutter, I have to listen to the purchase stream to get purchase details ( token and ..etc ), and here’s the weird part, one below function I get responses under PurchaseStatus.purchased and PurchaseStatus.restored when the purchase has been canceled and expired at the same time.

So the _handleSuccessfullySubscribed(); get’s run!

I have another function for server-side validation but don’t know where to place it in my code without doing an infinite loop here.

void _initiated() async {
  await _subscription?.cancel();

  _subscription = _inAppPurchase.purchaseStream.listen((purchases) async {
    for (final purchase in purchases) {
      switch (purchase.status) {
        case PurchaseStatus.purchased:
        case PurchaseStatus.restored:
          // handle if purchased here
          _handleSuccessfullySubscribed();
          break;

        case PurchaseStatus.pending:
          // handle if pending here
          log('Purchase is pending');
          break;

        case PurchaseStatus.canceled:
          // handle if canceled here
          log('Purchase is canceled');
          break;

        case PurchaseStatus.error:
          // handle if error here
          log('Purchase has an error');
          break;
        default:
      }

      if (purchase.pendingCompletePurchase) {
        await _inAppPurchase.completePurchase(purchase);
      }
    }
  });

  await _inAppPurchase.restorePurchases();
}

The validation function

@override
Future<Either<Failure, Unit>> verifySubscription(
    {required String token, required String productId}) async {
  try {
    final settings = locator<ISettingsRepository>();

    final InternetConnectionChecker connectionChecker =
        InternetConnectionChecker();
    final either = await settings.get();

    either.fold((f) {
      // return left(const Failure(code: FailureCode.unexpected));
    }, (settings) async {
      if (settings.membership == Membership.paid &&
          (await connectionChecker.connectionStatus) ==
              InternetConnectionStatus.connected) {
        await locator<Dio>().post('google-subscriptions/v1/validate', data: {
          "productId": productId,
          "purchaseToken": token,
          "packageName": "app.expamle"
        });
      }
    });

    return right(unit);
  } on DioException catch (_) {
    _handleFailedSubscribed();
    return left(const Failure(code: FailureCode.unexpected));
  }
}

The whole class

class IapRepository extends IIapRepository {
  IapRepository(this._inAppPurchase, this._settingsDAO) {
    _initiated();
  }

  final InAppPurchase _inAppPurchase;
  final SettingsDAO _settingsDAO;

  StreamSubscription<void>? _subscription;

  void _initiated() async {
    await _subscription?.cancel();

    _subscription = _inAppPurchase.purchaseStream.listen((purchases) async {
      for (final purchase in purchases) {
        switch (purchase.status) {
          case PurchaseStatus.purchased:
          case PurchaseStatus.restored:
            // handle if purchased here
            log(''' Purchase details: 
productID ${purchase.productID}
purchaseID ${purchase.purchaseID}
status ${purchase.status}
transactionDate ${purchase.transactionDate}
verificationData ${purchase.verificationData.localVerificationData} - ${purchase.verificationData.serverVerificationData} - ${purchase.verificationData.source}

''');

            _handleSuccessfullySubscribed();
            break;

          case PurchaseStatus.pending:
            // handle if pending here
            log('Purchase is pending');
            break;

          case PurchaseStatus.canceled:
            // handle if canceled here
            log('Purchase is canceled');
            break;

          case PurchaseStatus.error:
            // handle if error here
            log('Purchase has an error');
            break;
          default:
        }

        if (purchase.pendingCompletePurchase) {
          await _inAppPurchase.completePurchase(purchase);
        }
      }
    });

    await _inAppPurchase.restorePurchases();
  }

  void _handleSuccessfullySubscribed() async {
    await _settingsDAO.customUpdate(
      r"UPDATE settings SET details = json_set(details, '$.membership', ?) WHERE id = 1;",
      variables: [
        Variable<String>(Membership.paid.name),
      ],
      updates: {
        _settingsDAO.settingsTable,
      },
    );

    final settings = await _settingsDAO.get();

    log('Settings data log ${settings.data}');
  }

  void _handleFailedSubscribed() async {
    await _settingsDAO.customUpdate(
      r"UPDATE settings SET details = json_set(details, '$.membership', ?) WHERE id = 1;",
      variables: [
        Variable<String>(Membership.free.name),
      ],
      updates: {
        _settingsDAO.settingsTable,
      },
    );

    final settings = await _settingsDAO.get();

    log('Settings data log ${settings.data}');
  }

  @override
  Future<Either<Failure, List<ProductDetails>>> getProducts() async {
    try {
      final bool isAvailable = await _inAppPurchase.isAvailable();

      if (!isAvailable) {
        return left(const Failure(code: FailureCode.unexpected));
      }

      final Set<String> productsIds = {
        'expample',
      };

      final ProductDetailsResponse response =
          await _inAppPurchase.queryProductDetails(productsIds);

      final List<ProductDetails> products = response.productDetails;

      return right(products);
    } catch (e) {
      return left(const Failure(code: FailureCode.unexpected));
    }
  }

  @override
  Future<Either<Failure, Unit>> subscribe(ProductDetails details) async {
    try {
      await _inAppPurchase.buyNonConsumable(
          purchaseParam: PurchaseParam(productDetails: details));

      return right(unit);
    } catch (e) {
      return left(const Failure(code: FailureCode.unexpected));
    }
  }

  @override
  Future<Either<Failure, Unit>> verifySubscription(
      {required String token, required String productId}) async {
    try {
      final settings = locator<ISettingsRepository>();

      final InternetConnectionChecker connectionChecker =
          InternetConnectionChecker();
      final either = await settings.get();

      either.fold((f) {
        // return left(const Failure(code: FailureCode.unexpected));
      }, (settings) async {
        if (settings.membership == Membership.paid &&
            (await connectionChecker.connectionStatus) ==
                InternetConnectionStatus.connected) {
          await locator<Dio>().post('google-subscriptions/v1/validate', data: {
            "productId": productId,
            "purchaseToken": token,
            "packageName": "app.example"
          });
        }
      });

      return right(unit);
    } on DioException catch (_) {
      _handleFailedSubscribed();
      return left(const Failure(code: FailureCode.unexpected));
    }
  }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật