Created
May 27, 2020 23:26
-
-
Save mingsai/242a79f5a5fb5d62453a7c5eb4350741 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Subscribe to any incoming purchases at app initialization. These can | |
// propagate from either storefront so it's important to listen as soon as | |
// possible to avoid losing events. | |
class _MyAppState extends State<MyApp> { | |
StreamSubscription<List<PurchaseDetails>> _subscription; | |
@override | |
void initState() { | |
final Stream purchaseUpdates = | |
InAppPurchaseConnection.instance.purchaseUpdatedStream; | |
_subscription = purchaseUpdates.listen((purchases) { | |
_handlePurchaseUpdates(purchases); | |
}); | |
super.initState(); | |
} | |
@override | |
void dispose() { | |
_subscription.cancel(); | |
super.dispose(); | |
} | |
Connecting to the Storefront | |
final bool available = await InAppPurchaseConnection.instance.isAvailable(); | |
if (!available) { | |
// The store cannot be reached or accessed. Update the UI accordingly. | |
} | |
Loading products for sale | |
// Set literals require Dart 2.2. Alternatively, use `Set<String> _kIds = <String>['product1', 'product2'].toSet()`. | |
const Set<String> _kIds = {'product1', 'product2'}; | |
final ProductDetailsResponse response = await InAppPurchaseConnection.instance.queryProductDetails(_kIds); | |
if (!response.notFoundIDs.isEmpty) { | |
// Handle the error. | |
} | |
List<ProductDetails> products = response.productDetails; | |
Loading previous purchases | |
final QueryPurchaseDetailsResponse response = await InAppPurchaseConnection.instance.queryPastPurchases(); | |
if (response.error != null) { | |
// Handle the error. | |
} | |
for (PurchaseDetails purchase in response.pastPurchases) { | |
_verifyPurchase(purchase); // Verify the purchase following the best practices for each storefront. | |
_deliverPurchase(purchase); // Deliver the purchase to the user in your app. | |
if (Platform.isIOS) { | |
// Mark that you've delivered the purchase. Only the App Store requires | |
// this final confirmation. | |
InAppPurchaseConnection.instance.completePurchase(purchase); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment