checkSubscribed method
Check if a subscription is active on Android
and iOS
.
This is a quick and dirty way to check if a subscription is active. It is highly recommended to do server-side validation for all subscriptions. This method is NOT secure and untested in production.
Implementation
Future<bool> checkSubscribed({
required String sku,
Duration duration = const Duration(days: 30),
Duration grace = const Duration(days: 3),
}) async {
if (_platform.isIOS) {
var history = await getPurchaseHistory();
if (history == null) {
return false;
}
for (var purchase in history) {
Duration difference =
DateTime.now().difference(purchase.transactionDate!);
if (difference.inMinutes <= (duration + grace).inMinutes &&
purchase.productId == sku) return true;
}
return false;
} else if (_platform.isAndroid) {
var purchases = await (getAvailablePurchases());
for (var purchase in purchases ?? []) {
if (purchase.productId == sku) return true;
}
return false;
}
throw PlatformException(
code: _platform.operatingSystem, message: "platform not supported");
}