@capgo/native-purchases 8.9.15 → 8.9.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -36,6 +36,7 @@ import java.util.IdentityHashMap;
36
36
  import java.util.List;
37
37
  import java.util.Map;
38
38
  import java.util.Set;
39
+ import java.util.WeakHashMap;
39
40
  import java.util.concurrent.CountDownLatch;
40
41
  import java.util.concurrent.ExecutorService;
41
42
  import java.util.concurrent.Executors;
@@ -109,7 +110,7 @@ public class NativePurchasesPlugin extends Plugin {
109
110
  return SubscriptionOfferPurchaseResult.ok(selected.getOfferToken(), selected.getBasePlanId());
110
111
  }
111
112
 
112
- private final String pluginVersion = "8.9.15";
113
+ private final String pluginVersion = "8.9.17";
113
114
  public static final String TAG = "NativePurchases";
114
115
  private static final int BILLING_CONNECTION_MAX_ATTEMPTS = 2;
115
116
  private static final long BILLING_SETUP_TIMEOUT_SECONDS = 5;
@@ -121,6 +122,11 @@ public class NativePurchasesPlugin extends Plugin {
121
122
  return thread;
122
123
  });
123
124
  BillingClient billingClient;
125
+ /**
126
+ * Open Play billing sheets per client. Guarded by {@link #billingClientLock}. A client with an open
127
+ * flow must not be ended until Play calls {@code onPurchasesUpdated}; later calls detach it instead.
128
+ */
129
+ private final Map<BillingClient, Integer> pendingBillingFlows = new IdentityHashMap<>();
124
130
  /**
125
131
  * Number of auto acknowledge or consume operations in flight per client. Guarded by
126
132
  * {@link #billingClientLock}. endConnection() drops queued work, so such a client is ended only
@@ -143,6 +149,8 @@ public class NativePurchasesPlugin extends Plugin {
143
149
  private static final long PENDING_FINISH_WAIT_MS = 10_000;
144
150
  /** Package-private so tests can shorten the wait. */
145
151
  long pendingFinishWaitMs = PENDING_FINISH_WAIT_MS;
152
+ /** Ensures purchaseProduct settles its promise once even if Play reports the failure twice. */
153
+ private final Map<PluginCall, AtomicBoolean> purchaseCallSettlement = new WeakHashMap<>();
146
154
  private volatile boolean autoFinishTransactions = true;
147
155
 
148
156
  @PluginMethod
@@ -393,25 +401,42 @@ public class NativePurchasesPlugin extends Plugin {
393
401
  @Override
394
402
  protected void handleOnDestroy() {
395
403
  billingExecutor.shutdownNow();
396
- List<BillingClient> detached = new ArrayList<>();
404
+ List<BillingClient> clientsToEnd = new ArrayList<>();
397
405
  synchronized (billingClientLock) {
398
- // Clients still finishing work, including set aside ones, would otherwise never be ended.
406
+ if (billingClient != null) {
407
+ clientsToEnd.add(billingClient);
408
+ }
409
+ for (BillingClient client : pendingBillingFlows.keySet()) {
410
+ if (!clientsToEnd.contains(client)) {
411
+ clientsToEnd.add(client);
412
+ }
413
+ }
399
414
  for (BillingClient client : pendingFinishes.keySet()) {
400
- if (client != billingClient) {
401
- detached.add(client);
415
+ if (!clientsToEnd.contains(client)) {
416
+ clientsToEnd.add(client);
402
417
  }
403
418
  }
419
+ billingClient = null;
420
+ pendingBillingFlows.clear();
404
421
  pendingFinishes.clear();
405
422
  abandonedFinishHandlers.clear();
406
423
  setAsideClients.clear();
424
+ purchaseCallSettlement.clear();
407
425
  }
408
- for (BillingClient client : detached) {
426
+ for (BillingClient client : clientsToEnd) {
409
427
  client.endConnection();
410
428
  }
411
- closeBillingClient();
412
429
  super.handleOnDestroy();
413
430
  }
414
431
 
432
+ BillingClient getBillingClientForTest() {
433
+ return billingClient;
434
+ }
435
+
436
+ void setBillingClientForTest(BillingClient client) {
437
+ billingClient = client;
438
+ }
439
+
415
440
  /** Package-private so tests can stand in for a later call that replaces the client. */
416
441
  void closeBillingClient() {
417
442
  synchronized (billingClientLock) {
@@ -472,11 +497,17 @@ public class NativePurchasesPlugin extends Plugin {
472
497
  }
473
498
  billingClientLock.notifyAll();
474
499
  }
475
- if (last) {
500
+ if (last && client != null && !hasOpenBillingFlow(client)) {
476
501
  client.endConnection();
477
502
  }
478
503
  }
479
504
 
505
+ private boolean hasOpenBillingFlow(BillingClient client) {
506
+ synchronized (billingClientLock) {
507
+ return pendingBillingFlows.containsKey(client);
508
+ }
509
+ }
510
+
480
511
  /**
481
512
  * Waits until no acknowledge or consume is in flight, so a new client is not created next to one
482
513
  * that can still receive purchase updates. After {@link #PENDING_FINISH_WAIT_MS} it gives up and
@@ -494,10 +525,6 @@ public class NativePurchasesPlugin extends Plugin {
494
525
  while (hasAwaitedFinishesLocked()) {
495
526
  long remainingMs = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime());
496
527
  if (remainingMs <= 0) {
497
- // Stop waiting on the unanswered finishes so they do not delay every later call too,
498
- // and settle the calls waiting on them. Their clients stay open and keep their real
499
- // pending counts: a slow finish is not a lost one, and endConnection() would drop it.
500
- // Each client still ends when its last finish answers.
501
528
  NativePurchasesLog.w(TAG, "Purchase finish still pending, no longer waiting on it");
502
529
  for (BillingClient stale : new ArrayList<>(pendingFinishes.keySet())) {
503
530
  if (!setAsideClients.add(stale)) {
@@ -524,12 +551,13 @@ public class NativePurchasesPlugin extends Plugin {
524
551
  }
525
552
  }
526
553
 
527
- /** True while some client that is not set aside has a finish in flight. */
554
+ /** True while some client that is not set aside has a finish in flight and no open purchase sheet. */
528
555
  private boolean hasAwaitedFinishesLocked() {
529
556
  for (BillingClient client : pendingFinishes.keySet()) {
530
- if (!setAsideClients.contains(client)) {
531
- return true;
557
+ if (setAsideClients.contains(client) || pendingBillingFlows.containsKey(client)) {
558
+ continue;
532
559
  }
560
+ return true;
533
561
  }
534
562
  return false;
535
563
  }
@@ -542,6 +570,135 @@ public class NativePurchasesPlugin extends Plugin {
542
570
  .build();
543
571
  }
544
572
 
573
+ /**
574
+ * Records an open billing flow on {@code client}. The flow ends in {@link #endPendingBillingFlow}.
575
+ *
576
+ * @return false when the client is already closed.
577
+ */
578
+ boolean beginPendingBillingFlow(BillingClient client) {
579
+ synchronized (billingClientLock) {
580
+ if (client == null || !client.isReady()) {
581
+ return false;
582
+ }
583
+ pendingBillingFlows.merge(client, 1, Integer::sum);
584
+ return true;
585
+ }
586
+ }
587
+
588
+ /**
589
+ * Records that Play answered the billing flow for {@code client}. The last one ends the client.
590
+ */
591
+ void endPendingBillingFlow(BillingClient client) {
592
+ if (client == null) {
593
+ return;
594
+ }
595
+ boolean last;
596
+ boolean finishInFlight;
597
+ synchronized (billingClientLock) {
598
+ finishInFlight = pendingFinishes.getOrDefault(client, 0) > 0;
599
+ Integer pending = pendingBillingFlows.get(client);
600
+ if (pending == null) {
601
+ return;
602
+ }
603
+ last = pending <= 1;
604
+ if (last) {
605
+ pendingBillingFlows.remove(client);
606
+ if (billingClient == client) {
607
+ billingClient = null;
608
+ }
609
+ } else {
610
+ pendingBillingFlows.put(client, pending - 1);
611
+ }
612
+ billingClientLock.notifyAll();
613
+ }
614
+ if (last && !finishInFlight) {
615
+ client.endConnection();
616
+ }
617
+ }
618
+
619
+ private void registerPurchaseCallSettlement(PluginCall call) {
620
+ purchaseCallSettlement.put(call, new AtomicBoolean(false));
621
+ }
622
+
623
+ void registerPurchaseCallSettlementForTest(PluginCall call) {
624
+ registerPurchaseCallSettlement(call);
625
+ }
626
+
627
+ private boolean trySettlePurchaseCall(PluginCall call) {
628
+ if (call == null) {
629
+ return false;
630
+ }
631
+ AtomicBoolean settled = purchaseCallSettlement.get(call);
632
+ if (settled != null) {
633
+ return settled.compareAndSet(false, true);
634
+ }
635
+ return true;
636
+ }
637
+
638
+ private void rejectPurchaseCallOnce(PluginCall call, String message, String code) {
639
+ if (trySettlePurchaseCall(call)) {
640
+ call.reject(message, code);
641
+ }
642
+ }
643
+
644
+ private void rejectPurchaseCallOnce(PluginCall call, String message) {
645
+ if (trySettlePurchaseCall(call)) {
646
+ call.reject(message);
647
+ }
648
+ }
649
+
650
+ private void resolvePurchaseCallOnce(PluginCall call, JSObject ret) {
651
+ if (trySettlePurchaseCall(call)) {
652
+ call.resolve(ret);
653
+ }
654
+ }
655
+
656
+ private void abortPurchaseClientFlow(BillingClient purchaseClient, PluginCall call, String message) {
657
+ endPendingBillingFlow(purchaseClient);
658
+ closeBillingClientIfCurrent(purchaseClient);
659
+ rejectPurchaseCallOnce(call, message);
660
+ }
661
+
662
+ private void abortPurchaseClientFlow(BillingClient purchaseClient, PluginCall call, String message, String code) {
663
+ endPendingBillingFlow(purchaseClient);
664
+ closeBillingClientIfCurrent(purchaseClient);
665
+ rejectPurchaseCallOnce(call, message, code);
666
+ }
667
+
668
+ /**
669
+ * Launches the Play sheet on {@code flowClient}, which must be the client captured for this purchase call,
670
+ * not the shared {@link #billingClient} field.
671
+ */
672
+ void launchPurchaseBillingFlow(BillingClient flowClient, PluginCall call, BillingFlowParams billingFlowParams) {
673
+ if (flowClient == null || !flowClient.isReady()) {
674
+ NativePurchasesLog.w(TAG, "Purchase billing client closed before launch");
675
+ abortPurchaseClientFlow(
676
+ flowClient,
677
+ call,
678
+ "Purchase is not purchased",
679
+ billingResponseCodeName(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
680
+ );
681
+ return;
682
+ }
683
+ BillingResult billingResult2;
684
+ try {
685
+ billingResult2 = flowClient.launchBillingFlow(getActivity(), billingFlowParams);
686
+ } catch (RuntimeException launchError) {
687
+ endPendingBillingFlow(flowClient);
688
+ throw launchError;
689
+ }
690
+ NativePurchasesLog.d(
691
+ TAG,
692
+ "Billing flow launch result: " + billingResult2.getResponseCode() + " - " + billingResult2.getDebugMessage()
693
+ );
694
+ NativePurchasesLog.i(NativePurchasesPlugin.TAG, "onProductDetailsResponse2" + billingResult2);
695
+ if (billingResult2.getResponseCode() != BillingClient.BillingResponseCode.OK) {
696
+ endPendingBillingFlow(flowClient);
697
+ rejectPurchaseCallOnce(call, "Purchase is not purchased", billingResponseCodeName(billingResult2.getResponseCode()));
698
+ closeBillingClientIfCurrent(flowClient);
699
+ }
700
+ }
701
+
545
702
  /**
546
703
  * Reject a purchase whose {@code offerToken} matched no current offer.
547
704
  *
@@ -555,11 +712,15 @@ public class NativePurchasesPlugin extends Plugin {
555
712
  call.reject("Offer token not found for product: " + productIdentifier);
556
713
  }
557
714
 
715
+ private void rejectOfferTokenNotFoundForPurchase(PluginCall call, String productIdentifier, BillingClient purchaseClient) {
716
+ NativePurchasesLog.d(TAG, "Offer token not found for product: " + productIdentifier);
717
+ abortPurchaseClientFlow(purchaseClient, call, "Offer token not found for product: " + productIdentifier);
718
+ }
719
+
558
720
  private void closeBillingClientLocked() {
559
721
  NativePurchasesLog.d(TAG, "closeBillingClient() called");
560
- if (billingClient != null && pendingFinishes.containsKey(billingClient)) {
561
- // Its acknowledge or consume callback ends it; ending it here would drop that work.
562
- NativePurchasesLog.d(TAG, "Detaching billing client that is still finishing a purchase");
722
+ if (billingClient != null && (pendingBillingFlows.containsKey(billingClient) || pendingFinishes.containsKey(billingClient))) {
723
+ NativePurchasesLog.d(TAG, "Detaching billing client that has an open purchase flow or pending finish");
563
724
  billingClient = null;
564
725
  } else if (billingClient != null) {
565
726
  NativePurchasesLog.d(TAG, "Ending billing client connection");
@@ -682,25 +843,22 @@ public class NativePurchasesPlugin extends Plugin {
682
843
  ret.put("willCancel", null); // Default to null, would need API call to determine actual cancellation date
683
844
 
684
845
  NativePurchasesLog.d(TAG, "Resolving purchase call for product: " + purchase.getProducts().get(0));
685
- // Settles purchaseCall once, from Play's answer or from giving up on a lost finish.
686
846
  AtomicBoolean settled = new AtomicBoolean(false);
687
847
  Runnable onAbandon = () -> {
688
848
  if (settled.compareAndSet(false, true) && purchaseCall != null) {
689
849
  NativePurchasesLog.w(TAG, "Purchase finish was never answered; resolving with isAcknowledged false");
690
- purchaseCall.resolve(ret);
850
+ if (purchaseCallSettlement.containsKey(purchaseCall)) {
851
+ resolvePurchaseCallOnce(purchaseCall, ret);
852
+ } else {
853
+ purchaseCall.resolve(ret);
854
+ }
691
855
  }
692
856
  };
693
857
  boolean canFinish = shouldAutoAcknowledge && action != PurchaseAction.NONE;
694
858
  if (canFinish && !beginFinishingPurchase(purchaseClient, onAbandon)) {
695
- // Another call already ended this client, so an acknowledge or consume would never
696
- // be answered. Resolve now; the payload shows isAcknowledged false and the app can
697
- // acknowledge or consume the purchase itself.
698
859
  NativePurchasesLog.w(TAG, "Billing client already closed, skipping auto acknowledge or consume");
699
860
  shouldAutoAcknowledge = false;
700
861
  }
701
- // Still resolves when Play rejects the finish: the user has been charged, and a rejection
702
- // would tell the app the purchase failed. isAcknowledged stays false in that case, so the
703
- // app can see it and call acknowledgePurchase() or consumePurchase() itself.
704
862
  Consumer<BillingResult> completePurchase = (finishResult) -> {
705
863
  if (finishResult != null && finishResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
706
864
  ret.put("isAcknowledged", true);
@@ -708,8 +866,13 @@ public class NativePurchasesPlugin extends Plugin {
708
866
  NativePurchasesLog.w(TAG, "Automatic purchase finish failed; isAcknowledged stays false");
709
867
  }
710
868
  endFinishingPurchase(purchaseClient);
869
+ endPendingBillingFlow(purchaseClient);
711
870
  if (settled.compareAndSet(false, true) && purchaseCall != null) {
712
- purchaseCall.resolve(ret);
871
+ if (purchaseCallSettlement.containsKey(purchaseCall)) {
872
+ resolvePurchaseCallOnce(purchaseCall, ret);
873
+ } else {
874
+ purchaseCall.resolve(ret);
875
+ }
713
876
  }
714
877
  };
715
878
 
@@ -754,26 +917,25 @@ public class NativePurchasesPlugin extends Plugin {
754
917
  }
755
918
 
756
919
  if (purchaseCall != null) {
757
- purchaseCall.resolve(ret);
920
+ if (purchaseCallSettlement.containsKey(purchaseCall)) {
921
+ resolvePurchaseCallOnce(purchaseCall, ret);
922
+ } else {
923
+ purchaseCall.resolve(ret);
924
+ }
758
925
  } else {
759
926
  NativePurchasesLog.d(TAG, "purchaseCall is null, cannot resolve");
760
927
  }
761
928
  } else if (purchase.getPurchaseState() == Purchase.PurchaseState.PENDING) {
762
929
  NativePurchasesLog.d(TAG, "Purchase state is PENDING");
763
- // Here you can confirm to the user that they've started the pending
764
- // purchase, and to complete it, they should follow instructions that are
765
- // given to them. You can also choose to remind the user to complete the
766
- // purchase if you detect that it is still pending.
767
930
  if (purchaseCall != null) {
768
- purchaseCall.reject("Purchase is pending");
931
+ rejectPurchaseCallOnce(purchaseCall, "Purchase is pending");
769
932
  } else {
770
933
  NativePurchasesLog.d(TAG, "purchaseCall is null for pending purchase");
771
934
  }
772
935
  } else {
773
936
  NativePurchasesLog.d(TAG, "Purchase state is OTHER: " + purchase.getPurchaseState());
774
- // Handle any other error codes.
775
937
  if (purchaseCall != null) {
776
- purchaseCall.reject("Purchase is not purchased", "PURCHASE_STATE_" + purchase.getPurchaseState());
938
+ rejectPurchaseCallOnce(purchaseCall, "Purchase is not purchased", "PURCHASE_STATE_" + purchase.getPurchaseState());
777
939
  } else {
778
940
  NativePurchasesLog.d(TAG, "purchaseCall is null for failed purchase");
779
941
  }
@@ -781,33 +943,20 @@ public class NativePurchasesPlugin extends Plugin {
781
943
  return false;
782
944
  }
783
945
 
784
- /**
785
- * Body of each client's PurchasesUpdatedListener. {@code owner} is the client the listener belongs
786
- * to. It stays open while handlePurchase has an acknowledge or consume in flight, and is closed
787
- * here otherwise.
788
- */
789
- void handlePurchasesUpdated(BillingResult billingResult, List<Purchase> purchases, PluginCall purchaseCall, BillingClient owner) {
790
- NativePurchasesLog.d(TAG, "onPurchasesUpdated() called");
791
- NativePurchasesLog.d(TAG, "Billing result: " + billingResult.getResponseCode() + " - " + billingResult.getDebugMessage());
792
- NativePurchasesLog.d(TAG, "Purchases count: " + (purchases != null ? purchases.size() : 0));
793
- NativePurchasesLog.i(NativePurchasesPlugin.TAG, "onPurchasesUpdated" + billingResult);
794
- if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchases != null) {
795
- NativePurchasesLog.d(TAG, "Purchase update successful, processing first purchase");
796
- if (handlePurchase(purchases.get(0), purchaseCall, owner)) {
797
- return;
798
- }
799
- } else {
800
- NativePurchasesLog.d(TAG, "Purchase update failed or purchases is null");
801
- NativePurchasesLog.i(NativePurchasesPlugin.TAG, "onPurchasesUpdated" + billingResult);
802
- if (purchaseCall != null) {
803
- purchaseCall.reject("Purchase is not purchased", billingResponseCodeName(billingResult.getResponseCode()));
804
- }
805
- }
806
- closeBillingClientIfCurrent(owner);
807
- }
808
-
809
946
  private void acknowledgePurchase(BillingClient client, String purchaseToken, Consumer<BillingResult> onComplete) {
810
947
  NativePurchasesLog.d(TAG, "acknowledgePurchase() called");
948
+ if (client == null) {
949
+ NativePurchasesLog.w(TAG, "Billing client unavailable, skipping acknowledge");
950
+ if (onComplete != null) {
951
+ onComplete.accept(
952
+ BillingResult.newBuilder()
953
+ .setResponseCode(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
954
+ .setDebugMessage("Billing client unavailable")
955
+ .build()
956
+ );
957
+ }
958
+ return;
959
+ }
811
960
  AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
812
961
  .setPurchaseToken(purchaseToken)
813
962
  .build();
@@ -819,7 +968,9 @@ public class NativePurchasesPlugin extends Plugin {
819
968
  NativePurchasesLog.d(TAG, "onAcknowledgePurchaseResponse() called");
820
969
  NativePurchasesLog.d(TAG, "Acknowledge result: " + billingResult.getResponseCode() + " - " + billingResult.getDebugMessage());
821
970
  NativePurchasesLog.i(NativePurchasesPlugin.TAG, "onAcknowledgePurchaseResponse" + billingResult);
822
- onComplete.accept(billingResult);
971
+ if (onComplete != null) {
972
+ onComplete.accept(billingResult);
973
+ }
823
974
  };
824
975
  try {
825
976
  client.acknowledgePurchase(acknowledgePurchaseParams, listener);
@@ -828,7 +979,6 @@ public class NativePurchasesPlugin extends Plugin {
828
979
  }
829
980
  }
830
981
 
831
- /** Package-private so tests can drive a new billing call. */
832
982
  void initBillingClient(PluginCall purchaseCall) {
833
983
  NativePurchasesLog.d(TAG, "initBillingClient() called");
834
984
  NativePurchasesLog.d(TAG, "purchaseCall is null: " + (purchaseCall == null));
@@ -888,6 +1038,40 @@ public class NativePurchasesPlugin extends Plugin {
888
1038
  throw lastFailure != null ? lastFailure : new RuntimeException("Billing setup failed");
889
1039
  }
890
1040
 
1041
+ /**
1042
+ * Body of each client's PurchasesUpdatedListener. {@code owner} is the client the listener belongs
1043
+ * to; it stays open while a billing flow is open and ends when Play answers here.
1044
+ */
1045
+ void handlePurchasesUpdated(BillingResult billingResult, List<Purchase> purchases, PluginCall purchaseCall, BillingClient owner) {
1046
+ NativePurchasesLog.d(TAG, "onPurchasesUpdated() called");
1047
+ NativePurchasesLog.d(TAG, "Billing result: " + billingResult.getResponseCode() + " - " + billingResult.getDebugMessage());
1048
+ NativePurchasesLog.d(TAG, "Purchases count: " + (purchases != null ? purchases.size() : 0));
1049
+ NativePurchasesLog.i(NativePurchasesPlugin.TAG, "onPurchasesUpdated" + billingResult);
1050
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchases != null) {
1051
+ NativePurchasesLog.d(TAG, "Purchase update successful, processing first purchase");
1052
+ if (handlePurchase(purchases.get(0), purchaseCall, owner)) {
1053
+ endPendingBillingFlow(owner);
1054
+ return;
1055
+ }
1056
+ } else {
1057
+ NativePurchasesLog.d(TAG, "Purchase update failed or purchases is null");
1058
+ NativePurchasesLog.i(NativePurchasesPlugin.TAG, "onPurchasesUpdated" + billingResult);
1059
+ if (purchaseCall != null) {
1060
+ if (purchaseCallSettlement.containsKey(purchaseCall)) {
1061
+ rejectPurchaseCallOnce(
1062
+ purchaseCall,
1063
+ "Purchase is not purchased",
1064
+ billingResponseCodeName(billingResult.getResponseCode())
1065
+ );
1066
+ } else {
1067
+ purchaseCall.reject("Purchase is not purchased", billingResponseCodeName(billingResult.getResponseCode()));
1068
+ }
1069
+ }
1070
+ }
1071
+ endPendingBillingFlow(owner);
1072
+ closeBillingClientIfCurrent(owner);
1073
+ }
1074
+
891
1075
  private boolean isRetriableBillingSetupFailure(RuntimeException failure) {
892
1076
  String message = failure.getMessage();
893
1077
  if (message == null) {
@@ -905,9 +1089,8 @@ public class NativePurchasesPlugin extends Plugin {
905
1089
  final AtomicBoolean setupSettled = new AtomicBoolean(false);
906
1090
 
907
1091
  NativePurchasesLog.d(TAG, "Creating new BillingClient (attempt " + attempt + "/" + BILLING_CONNECTION_MAX_ATTEMPTS + ")");
908
- final BillingClient client;
909
- // The listener is built before the client exists, so it reads its owner from here.
910
1092
  final BillingClient[] listenerOwner = new BillingClient[1];
1093
+ final BillingClient client;
911
1094
  synchronized (billingClientLock) {
912
1095
  client = BillingClient.newBuilder(getContext())
913
1096
  .setListener(
@@ -1082,6 +1265,7 @@ public class NativePurchasesPlugin extends Plugin {
1082
1265
 
1083
1266
  call.getData().put("isConsumable", isConsumable);
1084
1267
  call.getData().put("autoAcknowledgePurchases", autoAcknowledgePurchases);
1268
+ registerPurchaseCallSettlement(call);
1085
1269
 
1086
1270
  // For subscriptions, always use the productIdentifier (subscription ID) to query
1087
1271
  // The planIdentifier is used later when setting the offer token
@@ -1096,8 +1280,18 @@ public class NativePurchasesPlugin extends Plugin {
1096
1280
  QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder().setProductList(productList).build();
1097
1281
  NativePurchasesLog.d(TAG, "Initializing billing client for purchase");
1098
1282
  withBillingClient(call, () -> {
1283
+ final BillingClient purchaseClient = billingClient;
1284
+ if (!beginPendingBillingFlow(purchaseClient)) {
1285
+ abortPurchaseClientFlow(
1286
+ purchaseClient,
1287
+ call,
1288
+ "Purchase is not purchased",
1289
+ billingResponseCodeName(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
1290
+ );
1291
+ return;
1292
+ }
1099
1293
  NativePurchasesLog.d(TAG, "Querying product details for purchase");
1100
- billingClient.queryProductDetailsAsync(
1294
+ purchaseClient.queryProductDetailsAsync(
1101
1295
  params,
1102
1296
  new ProductDetailsResponseListener() {
1103
1297
  @Override
@@ -1113,10 +1307,19 @@ public class NativePurchasesPlugin extends Plugin {
1113
1307
  );
1114
1308
  NativePurchasesLog.d(TAG, "Product details count: " + productDetailsList.size());
1115
1309
 
1310
+ if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK) {
1311
+ abortPurchaseClientFlow(
1312
+ purchaseClient,
1313
+ call,
1314
+ "Purchase is not purchased",
1315
+ billingResponseCodeName(billingResult.getResponseCode())
1316
+ );
1317
+ return;
1318
+ }
1319
+
1116
1320
  if (productDetailsList.isEmpty()) {
1117
1321
  NativePurchasesLog.d(TAG, "No products found");
1118
- closeBillingClient();
1119
- call.reject("Product not found");
1322
+ abortPurchaseClientFlow(purchaseClient, call, "Product not found");
1120
1323
  return;
1121
1324
  }
1122
1325
  // Process the result
@@ -1143,12 +1346,15 @@ public class NativePurchasesPlugin extends Plugin {
1143
1346
  );
1144
1347
  if (subscriptionSelection.outcome == SubscriptionOfferPurchaseOutcome.NO_OFFERS) {
1145
1348
  NativePurchasesLog.w(TAG, "No subscription offer details found for product: " + productIdentifier);
1146
- closeBillingClient();
1147
- call.reject("No subscription offer details found for product: " + productIdentifier);
1349
+ abortPurchaseClientFlow(
1350
+ purchaseClient,
1351
+ call,
1352
+ "No subscription offer details found for product: " + productIdentifier
1353
+ );
1148
1354
  return;
1149
1355
  }
1150
1356
  if (subscriptionSelection.outcome == SubscriptionOfferPurchaseOutcome.OFFER_TOKEN_NOT_FOUND) {
1151
- rejectOfferTokenNotFound(call, productIdentifier);
1357
+ rejectOfferTokenNotFoundForPurchase(call, productIdentifier, purchaseClient);
1152
1358
  return;
1153
1359
  }
1154
1360
 
@@ -1171,7 +1377,7 @@ public class NativePurchasesPlugin extends Plugin {
1171
1377
  }
1172
1378
  }
1173
1379
  if (selectedOffer == null) {
1174
- rejectOfferTokenNotFound(call, productIdentifier);
1380
+ rejectOfferTokenNotFoundForPurchase(call, productIdentifier, purchaseClient);
1175
1381
  return;
1176
1382
  }
1177
1383
  productDetailsParams.setOfferToken(selectedOffer.getOfferToken());
@@ -1197,14 +1403,8 @@ public class NativePurchasesPlugin extends Plugin {
1197
1403
  billingFlowBuilder.setObfuscatedAccountId(accountIdentifier);
1198
1404
  }
1199
1405
  BillingFlowParams billingFlowParams = billingFlowBuilder.build();
1200
- // Launch the billing flow
1201
1406
  NativePurchasesLog.d(TAG, "Launching billing flow");
1202
- BillingResult billingResult2 = billingClient.launchBillingFlow(getActivity(), billingFlowParams);
1203
- NativePurchasesLog.d(
1204
- TAG,
1205
- "Billing flow launch result: " + billingResult2.getResponseCode() + " - " + billingResult2.getDebugMessage()
1206
- );
1207
- NativePurchasesLog.i(NativePurchasesPlugin.TAG, "onProductDetailsResponse2" + billingResult2);
1407
+ launchPurchaseBillingFlow(purchaseClient, call, billingFlowParams);
1208
1408
  }
1209
1409
  }
1210
1410
  );
@@ -1228,8 +1428,6 @@ public class NativePurchasesPlugin extends Plugin {
1228
1428
  boolean processUnfinishedPurchases(BillingClient client) {
1229
1429
  NativePurchasesLog.d(TAG, "processUnfinishedPurchases() called");
1230
1430
  String[] productTypes = { BillingClient.ProductType.INAPP, BillingClient.ProductType.SUBS };
1231
- // Count every query before sending any, so a fast callback for the first one cannot end the
1232
- // client before the second is sent.
1233
1431
  for (int registered = 0; registered < productTypes.length; registered++) {
1234
1432
  if (!beginFinishingPurchase(client)) {
1235
1433
  NativePurchasesLog.w(TAG, "Billing client already closed, skipping unfinished purchase recovery");
@@ -1286,7 +1484,6 @@ public class NativePurchasesPlugin extends Plugin {
1286
1484
  NativePurchasesLog.d(TAG, "Purchase already acknowledged, skipping consume");
1287
1485
  continue;
1288
1486
  }
1289
- // Registered before the query's own finish ends, so the client cannot close in between.
1290
1487
  if (!beginFinishingPurchase(client)) {
1291
1488
  NativePurchasesLog.w(TAG, "Billing client already closed, skipping recovery acknowledgment");
1292
1489
  continue;
@@ -26,7 +26,7 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
26
26
  CAPPluginMethod(name: "finishTransaction", returnType: CAPPluginReturnPromise)
27
27
  ]
28
28
 
29
- private let pluginVersion: String = "8.9.15"
29
+ private let pluginVersion: String = "8.9.17"
30
30
  var autoFinishTransactions: Bool = true
31
31
  private var transactionUpdatesTask: Task<Void, Never>?
32
32
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/native-purchases",
3
- "version": "8.9.15",
3
+ "version": "8.9.17",
4
4
  "description": "In-app Subscriptions Made Easy",
5
5
  "main": "dist/plugin.cjs.js",
6
6
  "module": "dist/esm/index.js",