flutter 对接 google play的内支付
import 'package:in_app_purchase/in_app_purchase.dart';
Future<void> initiatePurchase() async { const String _kConsumableId = 'testproduct'; const List<String> _kProductIds = <String>[_kConsumableId]; //final bool available = await InAppPurchaseConnection.instance.isAvailable(); final InAppPurchase _inAppPurchase = InAppPurchase.instance; final bool available = await _inAppPurchase.isAvailable(); if (!available) { // handle error print('not available'); return; } final ProductDetailsResponse productDetailResponse = await _inAppPurchase.queryProductDetails(_kProductIds.toSet()); print("到此了"); print(productDetailResponse); if (productDetailResponse.error != null) { // handle error return; } List<ProductDetails> products = productDetailResponse.productDetails; ProductDetails productDetails = productDetailResponse.productDetails.first; PurchaseParam purchaseParam = PurchaseParam( productDetails: productDetails, ); await _inAppPurchase.buyNonConsumable(purchaseParam: purchaseParam); //BillingResult result = await InAppPurchaseConnection.instance.buyNonConsumable(purchaseParam: purchasePar }
判断购买成功
final StreamSubscription<List<PurchaseDetails>> _subscription = InAppPurchaseConnection.instance.purchaseUpdatedStream.listen((detailsList) { detailsList.forEach((PurchaseDetails purchaseDetails) async { if (purchaseDetails.status == PurchaseStatus.purchased || purchaseDetails.status == PurchaseStatus.restored) { // 购买或恢复购买成功 // TODO: 处理购买成功逻辑 if (Platform.isIOS) { // 对于 iOS 平台,需要将交易完成状态告诉 App Store,并确保该状态已被验证。 await InAppPurchaseConnection.instance.completePurchase(purchaseDetails); } } else if (purchaseDetails.status == PurchaseStatus.error) { // 购买失败 // TODO: 处理购买失败逻辑 } }); });
PurchaseStatus
是 Flutter 中的一个枚举类型,表示购买的状态。它包含以下几个值:
PurchaseStatus.purchased
: 表示购买已经完成。PurchaseStatus.pending
: 表示交易已经被缓慢处理。PurchaseStatus.error
: 表示购买遇到了错误。PurchaseStatus.restored
: 表示已经恢复了先前的非消耗性购买。
当从 InAppPurchaseConnection
的 purchaseUpdatedStream
事件流中获取到 PurchaseDetails
对象时,我们可以通过检查 status
属性来判断购买的状态。
参考:
https://juejin.cn/s/flutter%20google%20play%20billing
https://pub.dev/packages/in_app_purchase/example