apple_or_google_pay.dart 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import 'dart:async';
  2. import 'package:electronic_assistant/sdk/pay/assist/apple_or_google_pay_info.dart';
  3. import 'package:electronic_assistant/sdk/pay/assist/product_type.dart';
  4. import 'package:in_app_purchase/in_app_purchase.dart';
  5. import '../code/agile_pay_code.dart';
  6. import 'agile_pay_state_info.dart';
  7. abstract class AppleOrGooglePay extends AgilePayStateInfo {
  8. final AppleOrGooglePayInfo _payInfo;
  9. late final StreamSubscription<List<PurchaseDetails>>
  10. _purchaseUpdatedSubscription;
  11. late final InAppPurchase _iap;
  12. final Duration timeout = const Duration(seconds: 10);
  13. AppleOrGooglePay(this._payInfo) {
  14. _iap = InAppPurchase.instance;
  15. _purchaseUpdatedSubscription =
  16. _iap.purchaseStream.listen((purchaseDetailsList) {
  17. listenToPurchaseUpdated(purchaseDetailsList);
  18. }, onDone: () {
  19. _purchaseUpdatedSubscription.cancel();
  20. }, onError: (error) {});
  21. }
  22. void pay() async {
  23. sendPayBefore();
  24. try {
  25. final bool isAvailable = await _iap.isAvailable().timeout(timeout);
  26. if (!isAvailable) {
  27. sendError(AgilePayCode.payCodeNotConnectStore,
  28. AgilePayCode.getMessageByCode(AgilePayCode.payCodeNotConnectStore));
  29. return;
  30. }
  31. final ProductDetailsResponse response = await InAppPurchase.instance
  32. .queryProductDetails({_payInfo.productId});
  33. if (response.notFoundIDs.isNotEmpty || response.productDetails.isEmpty) {
  34. sendError(
  35. AgilePayCode.payCodeProductNotFindStore,
  36. AgilePayCode.getMessageByCode(
  37. AgilePayCode.payCodeProductNotFindStore));
  38. return;
  39. }
  40. List<ProductDetails> products = response.productDetails;
  41. for (var element in products) {
  42. bool isSend;
  43. if (_payInfo.type == ProductType.consumable) {
  44. isSend = await _iap.buyConsumable(
  45. purchaseParam: PurchaseParam(productDetails: element));
  46. } else {
  47. isSend = await _iap.buyNonConsumable(
  48. purchaseParam: PurchaseParam(productDetails: element));
  49. }
  50. if (!isSend) {
  51. sendError(
  52. AgilePayCode.payCodeRequestSendError,
  53. AgilePayCode.getMessageByCode(
  54. AgilePayCode.payCodeRequestSendError));
  55. return;
  56. }
  57. return;
  58. }
  59. } catch (e) {
  60. if (e is TimeoutException) {
  61. sendError(AgilePayCode.payCodeNotConnectStore,
  62. AgilePayCode.getMessageByCode(AgilePayCode.payCodeNotConnectStore));
  63. return;
  64. }
  65. sendError(AgilePayCode.payCodeOtherError,
  66. AgilePayCode.getMessageByCode(AgilePayCode.payCodeOtherError));
  67. return;
  68. }
  69. }
  70. void dispose() {
  71. _purchaseUpdatedSubscription.cancel();
  72. }
  73. void listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList);
  74. }