@capgo/native-purchases 8.9.17 → 8.11.0

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.
@@ -37,6 +37,7 @@ import java.util.List;
37
37
  import java.util.Map;
38
38
  import java.util.Set;
39
39
  import java.util.WeakHashMap;
40
+ import java.util.concurrent.ConcurrentHashMap;
40
41
  import java.util.concurrent.CountDownLatch;
41
42
  import java.util.concurrent.ExecutorService;
42
43
  import java.util.concurrent.Executors;
@@ -110,7 +111,7 @@ public class NativePurchasesPlugin extends Plugin {
110
111
  return SubscriptionOfferPurchaseResult.ok(selected.getOfferToken(), selected.getBasePlanId());
111
112
  }
112
113
 
113
- private final String pluginVersion = "8.9.17";
114
+ private final String pluginVersion = "8.11.0";
114
115
  public static final String TAG = "NativePurchases";
115
116
  private static final int BILLING_CONNECTION_MAX_ATTEMPTS = 2;
116
117
  private static final long BILLING_SETUP_TIMEOUT_SECONDS = 5;
@@ -152,6 +153,14 @@ public class NativePurchasesPlugin extends Plugin {
152
153
  /** Ensures purchaseProduct settles its promise once even if Play reports the failure twice. */
153
154
  private final Map<PluginCall, AtomicBoolean> purchaseCallSettlement = new WeakHashMap<>();
154
155
  private volatile boolean autoFinishTransactions = true;
156
+ private static final String TRANSACTION_UPDATED_EVENT = "transactionUpdated";
157
+ /** Billing client kept open while JS listens for {@link #TRANSACTION_UPDATED_EVENT}. */
158
+ private BillingClient updatesBillingClient;
159
+ private final Object updatesClientLock = new Object();
160
+ private static final String ACTIVE_FLOW_REGISTERED_PRODUCT_IDS = "nativePurchasesActiveFlowRegisteredProductIds";
161
+ private final Map<String, Integer> activePurchaseFlowProductIdRefCounts = new ConcurrentHashMap<>();
162
+ private final AtomicInteger updatesClientPendingAcknowledgements = new AtomicInteger(0);
163
+ private volatile boolean disconnectUpdatesClientWhenIdle;
155
164
 
156
165
  @PluginMethod
157
166
  public void configure(PluginCall call) {
@@ -264,6 +273,157 @@ public class NativePurchasesPlugin extends Plugin {
264
273
  return purchaseDateFormat.format(new java.util.Date(timeMillis));
265
274
  }
266
275
 
276
+ static String productTypeForBillingQuery(String billingProductType) {
277
+ return BillingClient.ProductType.SUBS.equals(billingProductType) ? "subs" : "inapp";
278
+ }
279
+
280
+ private static boolean containsPurchaseToken(List<Purchase> purchases, String purchaseToken) {
281
+ if (purchases == null || purchaseToken == null) {
282
+ return false;
283
+ }
284
+ for (Purchase purchase : purchases) {
285
+ if (purchaseToken.equals(purchase.getPurchaseToken())) {
286
+ return true;
287
+ }
288
+ }
289
+ return false;
290
+ }
291
+
292
+ void resolveProductTypeForPurchase(BillingClient client, Purchase purchase, Consumer<String> onResolved) {
293
+ if (client == null || !client.isReady() || purchase == null) {
294
+ NativePurchasesLog.w(TAG, "Cannot resolve product type without a ready billing client");
295
+ onResolved.accept(null);
296
+ return;
297
+ }
298
+ final String purchaseToken = purchase.getPurchaseToken();
299
+ QueryPurchasesParams inAppParams = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.INAPP).build();
300
+ try {
301
+ client.queryPurchasesAsync(inAppParams, (inAppResult, inAppPurchases) -> {
302
+ if (
303
+ inAppResult.getResponseCode() == BillingClient.BillingResponseCode.OK &&
304
+ containsPurchaseToken(inAppPurchases, purchaseToken)
305
+ ) {
306
+ onResolved.accept("inapp");
307
+ return;
308
+ }
309
+ if (inAppResult.getResponseCode() != BillingClient.BillingResponseCode.OK) {
310
+ NativePurchasesLog.w(TAG, "In-app query failed while resolving product type");
311
+ onResolved.accept(null);
312
+ return;
313
+ }
314
+ QueryPurchasesParams subsParams = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build();
315
+ try {
316
+ client.queryPurchasesAsync(subsParams, (subsResult, subsPurchases) -> {
317
+ if (
318
+ subsResult.getResponseCode() == BillingClient.BillingResponseCode.OK &&
319
+ containsPurchaseToken(subsPurchases, purchaseToken)
320
+ ) {
321
+ onResolved.accept("subs");
322
+ return;
323
+ }
324
+ if (subsResult.getResponseCode() != BillingClient.BillingResponseCode.OK) {
325
+ NativePurchasesLog.w(TAG, "Subs query failed while resolving product type");
326
+ onResolved.accept(null);
327
+ return;
328
+ }
329
+ NativePurchasesLog.w(TAG, "Purchase token missing from typed queries; skipping transactionUpdated");
330
+ onResolved.accept(null);
331
+ });
332
+ } catch (RuntimeException e) {
333
+ NativePurchasesLog.w(TAG, "Subs query failed while resolving product type: " + e.getMessage());
334
+ onResolved.accept(null);
335
+ }
336
+ });
337
+ } catch (RuntimeException e) {
338
+ NativePurchasesLog.w(TAG, "In-app query failed while resolving product type: " + e.getMessage());
339
+ onResolved.accept(null);
340
+ }
341
+ }
342
+
343
+ private boolean isPurchaseHandledByActiveFlow(Purchase purchase) {
344
+ if (purchase == null || purchase.getProducts().isEmpty()) {
345
+ return false;
346
+ }
347
+ String productId = purchase.getProducts().get(0);
348
+ synchronized (billingClientLock) {
349
+ Integer refCount = activePurchaseFlowProductIdRefCounts.get(productId);
350
+ return refCount != null && refCount > 0;
351
+ }
352
+ }
353
+
354
+ private void registerActivePurchaseFlowProduct(PluginCall call, String productIdentifier) {
355
+ if (call == null || productIdentifier == null || productIdentifier.isEmpty()) {
356
+ return;
357
+ }
358
+ synchronized (billingClientLock) {
359
+ activePurchaseFlowProductIdRefCounts.merge(productIdentifier, 1, Integer::sum);
360
+ }
361
+ appendActiveFlowRegisteredProductId(call, productIdentifier);
362
+ }
363
+
364
+ private void appendActiveFlowRegisteredProductId(PluginCall call, String productIdentifier) {
365
+ JSObject data = call.getData();
366
+ JSONArray registeredIds = data.optJSONArray(ACTIVE_FLOW_REGISTERED_PRODUCT_IDS);
367
+ if (registeredIds == null) {
368
+ registeredIds = new JSONArray();
369
+ data.put(ACTIVE_FLOW_REGISTERED_PRODUCT_IDS, registeredIds);
370
+ }
371
+ registeredIds.put(productIdentifier);
372
+ }
373
+
374
+ private void releaseRegisteredActivePurchaseFlowProducts(PluginCall purchaseCall) {
375
+ if (purchaseCall == null) {
376
+ return;
377
+ }
378
+ JSONArray registeredIds = purchaseCall.getData().optJSONArray(ACTIVE_FLOW_REGISTERED_PRODUCT_IDS);
379
+ if (registeredIds == null || registeredIds.length() == 0) {
380
+ return;
381
+ }
382
+ synchronized (billingClientLock) {
383
+ for (int i = 0; i < registeredIds.length(); i++) {
384
+ String productId = registeredIds.optString(i, "");
385
+ if (productId.isEmpty()) {
386
+ continue;
387
+ }
388
+ activePurchaseFlowProductIdRefCounts.compute(productId, (id, count) -> {
389
+ if (count == null || count <= 1) {
390
+ return null;
391
+ }
392
+ return count - 1;
393
+ });
394
+ }
395
+ }
396
+ purchaseCall.getData().remove(ACTIVE_FLOW_REGISTERED_PRODUCT_IDS);
397
+ }
398
+
399
+ void clearActivePurchaseFlowProducts(PluginCall purchaseCall, Purchase purchase) {
400
+ releaseRegisteredActivePurchaseFlowProducts(purchaseCall);
401
+ }
402
+
403
+ boolean isActivePurchaseFlowProductForTest(String productId) {
404
+ synchronized (billingClientLock) {
405
+ Integer refCount = activePurchaseFlowProductIdRefCounts.get(productId);
406
+ return refCount != null && refCount > 0;
407
+ }
408
+ }
409
+
410
+ private void maybeRefreshTransactionUpdatesAfterPurchaseFlow() {
411
+ synchronized (billingClientLock) {
412
+ if (!pendingBillingFlows.isEmpty()) {
413
+ return;
414
+ }
415
+ }
416
+ if (hasListeners(TRANSACTION_UPDATED_EVENT)) {
417
+ billingExecutor.execute(this::refreshTransactionUpdatesFromPlay);
418
+ }
419
+ }
420
+
421
+ private boolean isEphemeralBillingClient(BillingClient client) {
422
+ synchronized (updatesClientLock) {
423
+ return client != null && client != updatesBillingClient;
424
+ }
425
+ }
426
+
267
427
  private JSObject buildPurchaseTransactionObject(Purchase purchase, String productType) {
268
428
  AccountIdentifiers accountIdentifiers = purchase.getAccountIdentifiers();
269
429
  String purchaseAccountId = accountIdentifiers != null ? accountIdentifiers.getObfuscatedAccountId() : null;
@@ -282,6 +442,15 @@ public class NativePurchasesPlugin extends Plugin {
282
442
  return purchaseData;
283
443
  }
284
444
 
445
+ // Lets JS confirm that this native build understands oldPurchaseToken / replacementMode. Older builds ignore
446
+ // unknown options, so a replacement sent to them would silently become a second subscription instead.
447
+ @PluginMethod
448
+ public void isSubscriptionReplacementSupported(PluginCall call) {
449
+ JSObject ret = new JSObject();
450
+ ret.put("supported", true);
451
+ call.resolve(ret);
452
+ }
453
+
285
454
  @PluginMethod
286
455
  public void isBillingSupported(PluginCall call) {
287
456
  NativePurchasesLog.d(TAG, "isBillingSupported() called");
@@ -375,6 +544,261 @@ public class NativePurchasesPlugin extends Plugin {
375
544
  NativePurchasesLog.d(TAG, "Plugin load() completed");
376
545
  }
377
546
 
547
+ @PluginMethod(returnType = PluginMethod.RETURN_NONE)
548
+ @Override
549
+ public void addListener(PluginCall call) {
550
+ String eventName = call.getString("eventName");
551
+ boolean firstTransactionUpdatedListener = TRANSACTION_UPDATED_EVENT.equals(eventName) && !hasListeners(TRANSACTION_UPDATED_EVENT);
552
+ super.addListener(call);
553
+ if (firstTransactionUpdatedListener) {
554
+ billingExecutor.execute(this::ensureTransactionUpdatesBillingClient);
555
+ }
556
+ }
557
+
558
+ @PluginMethod(returnType = PluginMethod.RETURN_NONE)
559
+ @Override
560
+ public void removeListener(PluginCall call) {
561
+ String eventName = call.getString("eventName");
562
+ super.removeListener(call);
563
+ if (TRANSACTION_UPDATED_EVENT.equals(eventName) && !hasListeners(TRANSACTION_UPDATED_EVENT)) {
564
+ billingExecutor.execute(this::disconnectTransactionUpdatesBillingClient);
565
+ }
566
+ }
567
+
568
+ @PluginMethod(returnType = PluginMethod.RETURN_PROMISE)
569
+ @Override
570
+ public void removeAllListeners(PluginCall call) {
571
+ boolean hadTransactionUpdatedListeners = hasListeners(TRANSACTION_UPDATED_EVENT);
572
+ super.removeAllListeners(call);
573
+ if (hadTransactionUpdatedListeners) {
574
+ billingExecutor.execute(this::disconnectTransactionUpdatesBillingClient);
575
+ }
576
+ }
577
+
578
+ @Override
579
+ protected void handleOnResume() {
580
+ super.handleOnResume();
581
+ if (hasListeners(TRANSACTION_UPDATED_EVENT)) {
582
+ billingExecutor.execute(this::refreshTransactionUpdatesFromPlay);
583
+ }
584
+ }
585
+
586
+ private void refreshTransactionUpdatesFromPlay() {
587
+ BillingClient client;
588
+ synchronized (updatesClientLock) {
589
+ client = updatesBillingClient;
590
+ }
591
+ if (client != null && client.isReady()) {
592
+ queryUnacknowledgedPurchasesForTransactionUpdated(client);
593
+ return;
594
+ }
595
+ ensureTransactionUpdatesBillingClient();
596
+ }
597
+
598
+ private void ensureTransactionUpdatesBillingClient() {
599
+ if (!hasListeners(TRANSACTION_UPDATED_EVENT)) {
600
+ return;
601
+ }
602
+ synchronized (updatesClientLock) {
603
+ if (updatesBillingClient != null && updatesBillingClient.isReady()) {
604
+ queryUnacknowledgedPurchasesForTransactionUpdated(updatesBillingClient);
605
+ return;
606
+ }
607
+ if (updatesBillingClient != null) {
608
+ try {
609
+ updatesBillingClient.endConnection();
610
+ } catch (RuntimeException e) {
611
+ NativePurchasesLog.w(TAG, "Failed to end stale updates billing client: " + e.getMessage());
612
+ }
613
+ updatesBillingClient = null;
614
+ }
615
+ final BillingClient[] clientHolder = new BillingClient[1];
616
+ clientHolder[0] = BillingClient.newBuilder(getContext())
617
+ .setListener(
618
+ new PurchasesUpdatedListener() {
619
+ @Override
620
+ public void onPurchasesUpdated(@NonNull BillingResult billingResult, List<Purchase> purchases) {
621
+ handleUpdatesPurchasesUpdated(billingResult, purchases, clientHolder[0]);
622
+ }
623
+ }
624
+ )
625
+ .enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build())
626
+ .build();
627
+ updatesBillingClient = clientHolder[0];
628
+ NativePurchasesLog.d(TAG, "Starting updates billing client connection");
629
+ clientHolder[0].startConnection(
630
+ new BillingClientStateListener() {
631
+ @Override
632
+ public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
633
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
634
+ queryUnacknowledgedPurchasesForTransactionUpdated(clientHolder[0]);
635
+ } else {
636
+ NativePurchasesLog.w(TAG, "Updates billing client setup failed: " + billingResult.getDebugMessage());
637
+ }
638
+ }
639
+
640
+ @Override
641
+ public void onBillingServiceDisconnected() {
642
+ NativePurchasesLog.d(TAG, "Updates billing client disconnected");
643
+ synchronized (updatesClientLock) {
644
+ if (updatesBillingClient == clientHolder[0]) {
645
+ updatesBillingClient = null;
646
+ }
647
+ }
648
+ }
649
+ }
650
+ );
651
+ }
652
+ }
653
+
654
+ private void disconnectTransactionUpdatesBillingClient() {
655
+ if (updatesClientPendingAcknowledgements.get() > 0) {
656
+ disconnectUpdatesClientWhenIdle = true;
657
+ return;
658
+ }
659
+ disconnectTransactionUpdatesBillingClientNow();
660
+ }
661
+
662
+ private void disconnectTransactionUpdatesBillingClientNow() {
663
+ disconnectUpdatesClientWhenIdle = false;
664
+ synchronized (updatesClientLock) {
665
+ if (updatesBillingClient != null) {
666
+ try {
667
+ updatesBillingClient.endConnection();
668
+ } catch (RuntimeException e) {
669
+ NativePurchasesLog.w(TAG, "Failed to end updates billing client: " + e.getMessage());
670
+ }
671
+ updatesBillingClient = null;
672
+ }
673
+ }
674
+ }
675
+
676
+ private void maybeFinishDeferredUpdatesClientDisconnect() {
677
+ if (
678
+ disconnectUpdatesClientWhenIdle && updatesClientPendingAcknowledgements.get() == 0 && !hasListeners(TRANSACTION_UPDATED_EVENT)
679
+ ) {
680
+ disconnectTransactionUpdatesBillingClientNow();
681
+ }
682
+ }
683
+
684
+ private void queryUnacknowledgedPurchasesForTransactionUpdated(BillingClient client) {
685
+ if (client == null || !client.isReady() || !hasListeners(TRANSACTION_UPDATED_EVENT)) {
686
+ return;
687
+ }
688
+ queryUnacknowledgedPurchasesForTransactionUpdated(client, BillingClient.ProductType.INAPP);
689
+ queryUnacknowledgedPurchasesForTransactionUpdated(client, BillingClient.ProductType.SUBS);
690
+ }
691
+
692
+ private void queryUnacknowledgedPurchasesForTransactionUpdated(BillingClient client, String billingProductType) {
693
+ final String productType = productTypeForBillingQuery(billingProductType);
694
+ QueryPurchasesParams params = QueryPurchasesParams.newBuilder().setProductType(billingProductType).build();
695
+ try {
696
+ client.queryPurchasesAsync(params, (billingResult, purchases) -> {
697
+ if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK || purchases == null) {
698
+ return;
699
+ }
700
+ for (Purchase purchase : purchases) {
701
+ if (
702
+ purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED &&
703
+ !purchase.isAcknowledged() &&
704
+ !isPurchaseHandledByActiveFlow(purchase)
705
+ ) {
706
+ processPurchaseForTransactionUpdated(purchase, productType, client);
707
+ }
708
+ }
709
+ });
710
+ } catch (RuntimeException e) {
711
+ NativePurchasesLog.w(TAG, "queryPurchasesAsync failed for transactionUpdated recovery: " + e.getMessage());
712
+ }
713
+ }
714
+
715
+ void handleUpdatesPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases, BillingClient client) {
716
+ if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK || purchases == null) {
717
+ return;
718
+ }
719
+ for (Purchase purchase : purchases) {
720
+ if (isPurchaseHandledByActiveFlow(purchase)) {
721
+ NativePurchasesLog.d(TAG, "Skipping transactionUpdated for in-flight purchaseProduct");
722
+ continue;
723
+ }
724
+ processPurchaseForTransactionUpdatedWithResolvedType(purchase, client);
725
+ }
726
+ }
727
+
728
+ private void processPurchaseForTransactionUpdatedWithResolvedType(Purchase purchase, BillingClient client) {
729
+ resolveProductTypeForPurchase(client, purchase, (productType) ->
730
+ processPurchaseForTransactionUpdated(purchase, productType, client)
731
+ );
732
+ }
733
+
734
+ /**
735
+ * @return true when an async acknowledge is in flight on an ephemeral billing client that must
736
+ * stay open until the callback runs.
737
+ */
738
+ boolean processPurchaseForTransactionUpdated(Purchase purchase, String productType, BillingClient client) {
739
+ if (!hasListeners(TRANSACTION_UPDATED_EVENT)) {
740
+ return false;
741
+ }
742
+ if (productType == null) {
743
+ return false;
744
+ }
745
+ int purchaseState = purchase.getPurchaseState();
746
+ if (purchaseState != Purchase.PurchaseState.PURCHASED && purchaseState != Purchase.PurchaseState.PENDING) {
747
+ return false;
748
+ }
749
+ JSObject payload = buildPurchaseTransactionObject(purchase, productType);
750
+ if (purchaseState == Purchase.PurchaseState.PURCHASED) {
751
+ if (autoFinishTransactions) {
752
+ PurchaseAction action = PurchaseActionDecider.decide(false, purchase);
753
+ if (action == PurchaseAction.ACKNOWLEDGE && client != null && client.isReady()) {
754
+ final boolean trackFinishOnEphemeralClient = isEphemeralBillingClient(client);
755
+ final boolean trackFinishOnUpdatesClient = !trackFinishOnEphemeralClient;
756
+ if (trackFinishOnEphemeralClient && !beginFinishingPurchase(client)) {
757
+ NativePurchasesLog.w(TAG, "Ephemeral billing client unavailable for transactionUpdated ack");
758
+ if (!purchase.isAcknowledged()) {
759
+ payload.put("needsFinish", true);
760
+ }
761
+ notifyListeners(TRANSACTION_UPDATED_EVENT, payload);
762
+ return false;
763
+ }
764
+ if (trackFinishOnUpdatesClient) {
765
+ updatesClientPendingAcknowledgements.incrementAndGet();
766
+ }
767
+ acknowledgePurchase(client, purchase.getPurchaseToken(), (billingResult) -> {
768
+ if (billingResult != null && billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
769
+ payload.put("isAcknowledged", true);
770
+ } else if (!purchase.isAcknowledged()) {
771
+ payload.put("needsFinish", true);
772
+ }
773
+ if (trackFinishOnEphemeralClient) {
774
+ endFinishingPurchase(client);
775
+ }
776
+ if (trackFinishOnUpdatesClient) {
777
+ if (updatesClientPendingAcknowledgements.decrementAndGet() == 0) {
778
+ maybeFinishDeferredUpdatesClientDisconnect();
779
+ }
780
+ }
781
+ notifyListeners(TRANSACTION_UPDATED_EVENT, payload);
782
+ });
783
+ return trackFinishOnEphemeralClient;
784
+ } else if (action == PurchaseAction.ACKNOWLEDGE && !purchase.isAcknowledged()) {
785
+ payload.put("needsFinish", true);
786
+ }
787
+ } else if (!purchase.isAcknowledged()) {
788
+ payload.put("needsFinish", true);
789
+ }
790
+ }
791
+ notifyListeners(TRANSACTION_UPDATED_EVENT, payload);
792
+ return false;
793
+ }
794
+
795
+ private void finishEphemeralTransactionUpdatedHandling(BillingClient owner, boolean keepClientOpenForAsyncWork) {
796
+ endPendingBillingFlow(owner);
797
+ if (!keepClientOpenForAsyncWork) {
798
+ closeBillingClientIfCurrent(owner);
799
+ }
800
+ }
801
+
378
802
  @FunctionalInterface
379
803
  private interface BillingTask {
380
804
  void run() throws Exception;
@@ -402,6 +826,12 @@ public class NativePurchasesPlugin extends Plugin {
402
826
  protected void handleOnDestroy() {
403
827
  billingExecutor.shutdownNow();
404
828
  List<BillingClient> clientsToEnd = new ArrayList<>();
829
+ synchronized (updatesClientLock) {
830
+ if (updatesBillingClient != null) {
831
+ clientsToEnd.add(updatesBillingClient);
832
+ updatesBillingClient = null;
833
+ }
834
+ }
405
835
  synchronized (billingClientLock) {
406
836
  if (billingClient != null) {
407
837
  clientsToEnd.add(billingClient);
@@ -611,6 +1041,9 @@ public class NativePurchasesPlugin extends Plugin {
611
1041
  }
612
1042
  billingClientLock.notifyAll();
613
1043
  }
1044
+ if (last) {
1045
+ maybeRefreshTransactionUpdatesAfterPurchaseFlow();
1046
+ }
614
1047
  if (last && !finishInFlight) {
615
1048
  client.endConnection();
616
1049
  }
@@ -624,6 +1057,10 @@ public class NativePurchasesPlugin extends Plugin {
624
1057
  registerPurchaseCallSettlement(call);
625
1058
  }
626
1059
 
1060
+ void setAutoFinishTransactionsForTest(boolean value) {
1061
+ autoFinishTransactions = value;
1062
+ }
1063
+
627
1064
  private boolean trySettlePurchaseCall(PluginCall call) {
628
1065
  if (call == null) {
629
1066
  return false;
@@ -654,12 +1091,14 @@ public class NativePurchasesPlugin extends Plugin {
654
1091
  }
655
1092
 
656
1093
  private void abortPurchaseClientFlow(BillingClient purchaseClient, PluginCall call, String message) {
1094
+ clearActivePurchaseFlowProducts(call, null);
657
1095
  endPendingBillingFlow(purchaseClient);
658
1096
  closeBillingClientIfCurrent(purchaseClient);
659
1097
  rejectPurchaseCallOnce(call, message);
660
1098
  }
661
1099
 
662
1100
  private void abortPurchaseClientFlow(BillingClient purchaseClient, PluginCall call, String message, String code) {
1101
+ clearActivePurchaseFlowProducts(call, null);
663
1102
  endPendingBillingFlow(purchaseClient);
664
1103
  closeBillingClientIfCurrent(purchaseClient);
665
1104
  rejectPurchaseCallOnce(call, message, code);
@@ -670,13 +1109,19 @@ public class NativePurchasesPlugin extends Plugin {
670
1109
  * not the shared {@link #billingClient} field.
671
1110
  */
672
1111
  void launchPurchaseBillingFlow(BillingClient flowClient, PluginCall call, BillingFlowParams billingFlowParams) {
1112
+ registerActivePurchaseFlowProduct(call, call.getString("productIdentifier"));
1113
+ String oldPurchaseToken = call.getString("oldPurchaseToken");
1114
+ String oldProductIdentifier = call.getString("oldProductIdentifier");
1115
+ if (oldPurchaseToken != null && !oldPurchaseToken.isEmpty() && oldProductIdentifier != null && !oldProductIdentifier.isEmpty()) {
1116
+ registerActivePurchaseFlowProduct(call, oldProductIdentifier);
1117
+ }
673
1118
  if (flowClient == null || !flowClient.isReady()) {
674
1119
  NativePurchasesLog.w(TAG, "Purchase billing client closed before launch");
675
1120
  abortPurchaseClientFlow(
676
1121
  flowClient,
677
1122
  call,
678
1123
  "Purchase is not purchased",
679
- billingResponseCodeName(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
1124
+ BillingResponseCodes.name(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
680
1125
  );
681
1126
  return;
682
1127
  }
@@ -684,6 +1129,7 @@ public class NativePurchasesPlugin extends Plugin {
684
1129
  try {
685
1130
  billingResult2 = flowClient.launchBillingFlow(getActivity(), billingFlowParams);
686
1131
  } catch (RuntimeException launchError) {
1132
+ clearActivePurchaseFlowProducts(call, null);
687
1133
  endPendingBillingFlow(flowClient);
688
1134
  throw launchError;
689
1135
  }
@@ -693,12 +1139,35 @@ public class NativePurchasesPlugin extends Plugin {
693
1139
  );
694
1140
  NativePurchasesLog.i(NativePurchasesPlugin.TAG, "onProductDetailsResponse2" + billingResult2);
695
1141
  if (billingResult2.getResponseCode() != BillingClient.BillingResponseCode.OK) {
1142
+ clearActivePurchaseFlowProducts(call, null);
696
1143
  endPendingBillingFlow(flowClient);
697
- rejectPurchaseCallOnce(call, "Purchase is not purchased", billingResponseCodeName(billingResult2.getResponseCode()));
1144
+ rejectPurchaseCallOnce(call, "Purchase is not purchased", BillingResponseCodes.name(billingResult2.getResponseCode()));
698
1145
  closeBillingClientIfCurrent(flowClient);
699
1146
  }
700
1147
  }
701
1148
 
1149
+ /**
1150
+ * Play Billing calls {@code queryProductDetailsAsync} listeners on its worker pool, but
1151
+ * {@link BillingClient#launchBillingFlow} must run on the UI thread. Package-private for tests.
1152
+ */
1153
+ void launchPurchaseBillingFlowOnUiThread(BillingClient purchaseClient, PluginCall call, BillingFlowParams billingFlowParams) {
1154
+ final android.app.Activity launchActivity = getActivity();
1155
+ if (launchActivity == null) {
1156
+ NativePurchasesLog.e(TAG, "Cannot launch billing flow: no activity");
1157
+ abortPurchaseClientFlow(purchaseClient, call, "Purchase could not start");
1158
+ return;
1159
+ }
1160
+ NativePurchasesLog.d(TAG, "Launching billing flow on the UI thread");
1161
+ launchActivity.runOnUiThread(() -> {
1162
+ try {
1163
+ launchPurchaseBillingFlow(purchaseClient, call, billingFlowParams);
1164
+ } catch (RuntimeException launchError) {
1165
+ NativePurchasesLog.e(TAG, "Billing flow launch failed: " + launchError.getMessage());
1166
+ abortPurchaseClientFlow(purchaseClient, call, "Purchase could not start");
1167
+ }
1168
+ });
1169
+ }
1170
+
702
1171
  /**
703
1172
  * Reject a purchase whose {@code offerToken} matched no current offer.
704
1173
  *
@@ -732,46 +1201,11 @@ public class NativePurchasesPlugin extends Plugin {
732
1201
  }
733
1202
  }
734
1203
 
735
- /**
736
- * Maps a {@link BillingClient.BillingResponseCode} to a readable name so
737
- * consumers can tell why a purchase was refused - most importantly
738
- * USER_CANCELED (not an error) and ITEM_ALREADY_OWNED (the user already
739
- * paid and the app should restore instead of showing a failure).
740
- */
741
- private static String billingResponseCodeName(int code) {
742
- switch (code) {
743
- case BillingClient.BillingResponseCode.USER_CANCELED:
744
- return "USER_CANCELED";
745
- case BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED:
746
- return "ITEM_ALREADY_OWNED";
747
- case BillingClient.BillingResponseCode.ITEM_NOT_OWNED:
748
- return "ITEM_NOT_OWNED";
749
- case BillingClient.BillingResponseCode.ITEM_UNAVAILABLE:
750
- return "ITEM_UNAVAILABLE";
751
- case BillingClient.BillingResponseCode.BILLING_UNAVAILABLE:
752
- return "BILLING_UNAVAILABLE";
753
- case BillingClient.BillingResponseCode.SERVICE_DISCONNECTED:
754
- return "SERVICE_DISCONNECTED";
755
- case BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE:
756
- return "SERVICE_UNAVAILABLE";
757
- case BillingClient.BillingResponseCode.DEVELOPER_ERROR:
758
- return "DEVELOPER_ERROR";
759
- case BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED:
760
- return "FEATURE_NOT_SUPPORTED";
761
- case BillingClient.BillingResponseCode.NETWORK_ERROR:
762
- return "NETWORK_ERROR";
763
- case BillingClient.BillingResponseCode.ERROR:
764
- return "ERROR";
765
- default:
766
- return "UNKNOWN_" + code;
767
- }
768
- }
769
-
770
1204
  private static String describeQueryFailure(String productType, BillingResult billingResult) {
771
1205
  return (
772
1206
  productType +
773
1207
  ": " +
774
- billingResponseCodeName(billingResult.getResponseCode()) +
1208
+ BillingResponseCodes.name(billingResult.getResponseCode()) +
775
1209
  " (" +
776
1210
  billingResult.getResponseCode() +
777
1211
  ") " +
@@ -781,7 +1215,7 @@ public class NativePurchasesPlugin extends Plugin {
781
1215
 
782
1216
  private void rejectBillingSetupCall(PluginCall purchaseCall, AtomicBoolean callRejected, String code, String message) {
783
1217
  if (purchaseCall != null && callRejected.compareAndSet(false, true)) {
784
- purchaseCall.reject(code, message);
1218
+ purchaseCall.reject(message, code);
785
1219
  }
786
1220
  }
787
1221
 
@@ -928,7 +1362,7 @@ public class NativePurchasesPlugin extends Plugin {
928
1362
  } else if (purchase.getPurchaseState() == Purchase.PurchaseState.PENDING) {
929
1363
  NativePurchasesLog.d(TAG, "Purchase state is PENDING");
930
1364
  if (purchaseCall != null) {
931
- rejectPurchaseCallOnce(purchaseCall, "Purchase is pending");
1365
+ rejectPurchaseCallOnce(purchaseCall, "Purchase is pending", BillingResponseCodes.PURCHASE_PENDING);
932
1366
  } else {
933
1367
  NativePurchasesLog.d(TAG, "purchaseCall is null for pending purchase");
934
1368
  }
@@ -1047,24 +1481,58 @@ public class NativePurchasesPlugin extends Plugin {
1047
1481
  NativePurchasesLog.d(TAG, "Billing result: " + billingResult.getResponseCode() + " - " + billingResult.getDebugMessage());
1048
1482
  NativePurchasesLog.d(TAG, "Purchases count: " + (purchases != null ? purchases.size() : 0));
1049
1483
  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);
1484
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchases != null && purchaseCall == null) {
1485
+ NativePurchasesLog.d(TAG, "Purchase update outside purchaseProduct, emitting transactionUpdated");
1486
+ if (purchases.isEmpty()) {
1487
+ finishEphemeralTransactionUpdatedHandling(owner, false);
1054
1488
  return;
1055
1489
  }
1490
+ AtomicInteger pendingResolutions = new AtomicInteger(purchases.size());
1491
+ AtomicBoolean keepClientOpenForAsyncWork = new AtomicBoolean(false);
1492
+ for (Purchase purchase : purchases) {
1493
+ resolveProductTypeForPurchase(owner, purchase, (productType) -> {
1494
+ if (processPurchaseForTransactionUpdated(purchase, productType, owner)) {
1495
+ keepClientOpenForAsyncWork.set(true);
1496
+ }
1497
+ if (pendingResolutions.decrementAndGet() <= 0) {
1498
+ finishEphemeralTransactionUpdatedHandling(owner, keepClientOpenForAsyncWork.get());
1499
+ }
1500
+ });
1501
+ }
1502
+ return;
1503
+ }
1504
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
1505
+ if (purchases != null && !purchases.isEmpty()) {
1506
+ NativePurchasesLog.d(TAG, "Purchase update successful, processing first purchase");
1507
+ Purchase firstPurchase = purchases.get(0);
1508
+ if (handlePurchase(firstPurchase, purchaseCall, owner)) {
1509
+ clearActivePurchaseFlowProducts(purchaseCall, firstPurchase);
1510
+ endPendingBillingFlow(owner);
1511
+ return;
1512
+ }
1513
+ clearActivePurchaseFlowProducts(purchaseCall, firstPurchase);
1514
+ } else {
1515
+ NativePurchasesLog.d(TAG, "Purchase update OK but no purchases returned");
1516
+ if (purchaseCall != null) {
1517
+ clearActivePurchaseFlowProducts(purchaseCall, null);
1518
+ if (purchaseCallSettlement.containsKey(purchaseCall)) {
1519
+ rejectPurchaseCallOnce(purchaseCall, "Purchase is not purchased", BillingResponseCodes.PURCHASE_NOT_FOUND);
1520
+ } else {
1521
+ purchaseCall.reject("Purchase is not purchased", BillingResponseCodes.PURCHASE_NOT_FOUND);
1522
+ }
1523
+ }
1524
+ }
1056
1525
  } else {
1057
- NativePurchasesLog.d(TAG, "Purchase update failed or purchases is null");
1526
+ NativePurchasesLog.d(TAG, "Purchase update failed");
1058
1527
  NativePurchasesLog.i(NativePurchasesPlugin.TAG, "onPurchasesUpdated" + billingResult);
1059
1528
  if (purchaseCall != null) {
1529
+ String code = BillingResponseCodes.name(billingResult.getResponseCode());
1530
+ Purchase failedPurchase = purchases != null && !purchases.isEmpty() ? purchases.get(0) : null;
1531
+ clearActivePurchaseFlowProducts(purchaseCall, failedPurchase);
1060
1532
  if (purchaseCallSettlement.containsKey(purchaseCall)) {
1061
- rejectPurchaseCallOnce(
1062
- purchaseCall,
1063
- "Purchase is not purchased",
1064
- billingResponseCodeName(billingResult.getResponseCode())
1065
- );
1533
+ rejectPurchaseCallOnce(purchaseCall, "Purchase is not purchased", code);
1066
1534
  } else {
1067
- purchaseCall.reject("Purchase is not purchased", billingResponseCodeName(billingResult.getResponseCode()));
1535
+ purchaseCall.reject("Purchase is not purchased", code);
1068
1536
  }
1069
1537
  }
1070
1538
  }
@@ -1218,6 +1686,14 @@ public class NativePurchasesPlugin extends Plugin {
1218
1686
  final String accountIdentifier = appAccountToken != null && !appAccountToken.isEmpty() ? appAccountToken : null;
1219
1687
  boolean isConsumable = call.getBoolean("isConsumable", false);
1220
1688
  boolean autoAcknowledgePurchases = call.getBoolean("autoAcknowledgePurchases", true);
1689
+ // Subscription replacement (upgrade / downgrade): the purchase being replaced and how to replace it.
1690
+ final String oldPurchaseToken = call.getString("oldPurchaseToken");
1691
+ final String oldProductIdentifier = call.getString("oldProductIdentifier");
1692
+ final String replacementModeName = call.getString("replacementMode");
1693
+ final boolean isReplacement = oldPurchaseToken != null && !oldPurchaseToken.isEmpty();
1694
+ final int replacementMode = isReplacement
1695
+ ? SubscriptionReplacementModes.fromName(replacementModeName)
1696
+ : SubscriptionReplacementModes.UNKNOWN;
1221
1697
 
1222
1698
  NativePurchasesLog.d(TAG, "Product identifier: " + productIdentifier);
1223
1699
  NativePurchasesLog.d(TAG, "Plan identifier: " + planIdentifier);
@@ -1227,6 +1703,7 @@ public class NativePurchasesPlugin extends Plugin {
1227
1703
  NativePurchasesLog.d(TAG, "Account identifier provided: " + (accountIdentifier != null ? "[REDACTED]" : "none"));
1228
1704
  NativePurchasesLog.d(TAG, "Is consumable: " + isConsumable);
1229
1705
  NativePurchasesLog.d(TAG, "Auto-acknowledge purchases: " + autoAcknowledgePurchases);
1706
+ NativePurchasesLog.d(TAG, "Subscription replacement: " + isReplacement);
1230
1707
 
1231
1708
  // cannot use quantity, because it's done in native modal
1232
1709
  NativePurchasesLog.d("CapacitorPurchases", "purchaseProduct: " + productIdentifier);
@@ -1262,6 +1739,16 @@ public class NativePurchasesPlugin extends Plugin {
1262
1739
  NativePurchasesLog.d(TAG, "isConsumable is not supported for subscriptions, ignoring flag");
1263
1740
  isConsumable = false;
1264
1741
  }
1742
+ String replacementError = SubscriptionReplacementModes.validationError(
1743
+ productType,
1744
+ oldPurchaseToken,
1745
+ oldProductIdentifier,
1746
+ replacementModeName
1747
+ );
1748
+ if (replacementError != null) {
1749
+ call.reject(replacementError);
1750
+ return;
1751
+ }
1265
1752
 
1266
1753
  call.getData().put("isConsumable", isConsumable);
1267
1754
  call.getData().put("autoAcknowledgePurchases", autoAcknowledgePurchases);
@@ -1286,7 +1773,7 @@ public class NativePurchasesPlugin extends Plugin {
1286
1773
  purchaseClient,
1287
1774
  call,
1288
1775
  "Purchase is not purchased",
1289
- billingResponseCodeName(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
1776
+ BillingResponseCodes.name(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
1290
1777
  );
1291
1778
  return;
1292
1779
  }
@@ -1312,14 +1799,14 @@ public class NativePurchasesPlugin extends Plugin {
1312
1799
  purchaseClient,
1313
1800
  call,
1314
1801
  "Purchase is not purchased",
1315
- billingResponseCodeName(billingResult.getResponseCode())
1802
+ BillingResponseCodes.name(billingResult.getResponseCode())
1316
1803
  );
1317
1804
  return;
1318
1805
  }
1319
1806
 
1320
1807
  if (productDetailsList.isEmpty()) {
1321
1808
  NativePurchasesLog.d(TAG, "No products found");
1322
- abortPurchaseClientFlow(purchaseClient, call, "Product not found");
1809
+ abortPurchaseClientFlow(purchaseClient, call, "Product not found", BillingResponseCodes.PRODUCT_NOT_FOUND);
1323
1810
  return;
1324
1811
  }
1325
1812
  // Process the result
@@ -1357,6 +1844,23 @@ public class NativePurchasesPlugin extends Plugin {
1357
1844
  rejectOfferTokenNotFoundForPurchase(call, productIdentifier, purchaseClient);
1358
1845
  return;
1359
1846
  }
1847
+ if (
1848
+ isReplacement &&
1849
+ !hasOfferToken &&
1850
+ planIdentifier != null &&
1851
+ !planIdentifier.isEmpty() &&
1852
+ !SubscriptionOfferSelector.hasBasePlan(
1853
+ SubscriptionOfferSelector.adapt(subscriptionOffers),
1854
+ planIdentifier
1855
+ )
1856
+ ) {
1857
+ abortPurchaseClientFlow(
1858
+ purchaseClient,
1859
+ call,
1860
+ "planIdentifier not found for subscription replacement: " + planIdentifier
1861
+ );
1862
+ return;
1863
+ }
1360
1864
 
1361
1865
  NativePurchasesLog.d(TAG, "Selected base plan: " + subscriptionSelection.basePlanId);
1362
1866
  productDetailsParams.setOfferToken(subscriptionSelection.offerToken);
@@ -1364,6 +1868,14 @@ public class NativePurchasesPlugin extends Plugin {
1364
1868
  TAG,
1365
1869
  "Set offer token: " + NativePurchasesLog.redactSensitive(subscriptionSelection.offerToken)
1366
1870
  );
1871
+ if (isReplacement) {
1872
+ productDetailsParams.setSubscriptionProductReplacementParams(
1873
+ BillingFlowParams.ProductDetailsParams.SubscriptionProductReplacementParams.newBuilder()
1874
+ .setOldProductId(oldProductIdentifier)
1875
+ .setReplacementMode(replacementMode)
1876
+ .build()
1877
+ );
1878
+ }
1367
1879
  } else if (productType.equals("inapp")) {
1368
1880
  NativePurchasesLog.d(TAG, "Processing in-app product");
1369
1881
  List<ProductDetails.OneTimePurchaseOfferDetails> oneTimeOffers =
@@ -1402,9 +1914,14 @@ public class NativePurchasesPlugin extends Plugin {
1402
1914
  if (accountIdentifier != null && !accountIdentifier.isEmpty()) {
1403
1915
  billingFlowBuilder.setObfuscatedAccountId(accountIdentifier);
1404
1916
  }
1917
+ if (isReplacement) {
1918
+ billingFlowBuilder.setSubscriptionUpdateParams(
1919
+ BillingFlowParams.SubscriptionUpdateParams.newBuilder().setOldPurchaseToken(oldPurchaseToken).build()
1920
+ );
1921
+ }
1405
1922
  BillingFlowParams billingFlowParams = billingFlowBuilder.build();
1406
1923
  NativePurchasesLog.d(TAG, "Launching billing flow");
1407
- launchPurchaseBillingFlow(purchaseClient, call, billingFlowParams);
1924
+ launchPurchaseBillingFlowOnUiThread(purchaseClient, call, billingFlowParams);
1408
1925
  }
1409
1926
  }
1410
1927
  );
@@ -1518,7 +2035,7 @@ public class NativePurchasesPlugin extends Plugin {
1518
2035
  /** Body of restorePurchases once a client exists. Package-private for tests. */
1519
2036
  void restoreWithClient(PluginCall call, BillingClient client) {
1520
2037
  if (!processUnfinishedPurchases(client)) {
1521
- call.reject("Billing client closed before restore could run. Please try again.");
2038
+ call.reject("Billing client closed before restore could run. Please try again.", BillingResponseCodes.BILLING_CLIENT_CLOSED);
1522
2039
  return;
1523
2040
  }
1524
2041
  call.resolve();
@@ -1541,8 +2058,9 @@ public class NativePurchasesPlugin extends Plugin {
1541
2058
  QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder().setProductList(productList).build();
1542
2059
  NativePurchasesLog.d(TAG, "Initializing billing client for single product query");
1543
2060
  withBillingClient(call, () -> {
2061
+ final BillingClient queryClient = billingClient;
1544
2062
  NativePurchasesLog.d(TAG, "Querying product details");
1545
- billingClient.queryProductDetailsAsync(
2063
+ queryClient.queryProductDetailsAsync(
1546
2064
  params,
1547
2065
  new ProductDetailsResponseListener() {
1548
2066
  @Override
@@ -1558,6 +2076,15 @@ public class NativePurchasesPlugin extends Plugin {
1558
2076
  );
1559
2077
  NativePurchasesLog.d(TAG, "Product details count: " + productDetailsList.size());
1560
2078
 
2079
+ if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK) {
2080
+ closeBillingClientIfCurrent(queryClient);
2081
+ call.reject(
2082
+ "Failed to query product details: " + billingResult.getDebugMessage(),
2083
+ BillingResponseCodes.name(billingResult.getResponseCode())
2084
+ );
2085
+ return;
2086
+ }
2087
+
1561
2088
  if (productDetailsList.isEmpty()) {
1562
2089
  NativePurchasesLog.d(TAG, "No product found in query");
1563
2090
  NativePurchasesLog.d(TAG, "This usually means:");
@@ -1565,8 +2092,8 @@ public class NativePurchasesPlugin extends Plugin {
1565
2092
  NativePurchasesLog.d(TAG, "2. Product is not published/active");
1566
2093
  NativePurchasesLog.d(TAG, "3. App is not properly configured for the product type");
1567
2094
  NativePurchasesLog.d(TAG, "4. Wrong product ID or type");
1568
- closeBillingClient();
1569
- call.reject("Product not found");
2095
+ closeBillingClientIfCurrent(queryClient);
2096
+ call.reject("Product not found", BillingResponseCodes.PRODUCT_NOT_FOUND);
1570
2097
  return;
1571
2098
  }
1572
2099
 
@@ -1587,7 +2114,7 @@ public class NativePurchasesPlugin extends Plugin {
1587
2114
  TAG,
1588
2115
  "No one-time purchase offer details found for product: " + productDetails.getProductId()
1589
2116
  );
1590
- closeBillingClient();
2117
+ closeBillingClientIfCurrent(queryClient);
1591
2118
  call.reject("No one-time purchase offer details found for product: " + productDetails.getProductId());
1592
2119
  return;
1593
2120
  }
@@ -1607,7 +2134,7 @@ public class NativePurchasesPlugin extends Plugin {
1607
2134
  TAG,
1608
2135
  "No subscription offer details found for product: " + productDetails.getProductId()
1609
2136
  );
1610
- closeBillingClient();
2137
+ closeBillingClientIfCurrent(queryClient);
1611
2138
  call.reject("No subscription offers found for product: " + productDetails.getProductId());
1612
2139
  return;
1613
2140
  }
@@ -1628,7 +2155,7 @@ public class NativePurchasesPlugin extends Plugin {
1628
2155
  TAG,
1629
2156
  "No offers with pricing phases found for product: " + productDetails.getProductId()
1630
2157
  );
1631
- closeBillingClient();
2158
+ closeBillingClientIfCurrent(queryClient);
1632
2159
  call.reject("No pricing phases found for product: " + productDetails.getProductId());
1633
2160
  return;
1634
2161
  }
@@ -1654,7 +2181,7 @@ public class NativePurchasesPlugin extends Plugin {
1654
2181
  JSObject ret = new JSObject();
1655
2182
  ret.put("product", product);
1656
2183
  NativePurchasesLog.d(TAG, "Returning single product");
1657
- closeBillingClient();
2184
+ closeBillingClientIfCurrent(queryClient);
1658
2185
  call.resolve(ret);
1659
2186
  }
1660
2187
  }
@@ -1682,8 +2209,9 @@ public class NativePurchasesPlugin extends Plugin {
1682
2209
  QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder().setProductList(productList).build();
1683
2210
  NativePurchasesLog.d(TAG, "Initializing billing client for product query");
1684
2211
  withBillingClient(call, () -> {
2212
+ final BillingClient queryClient = billingClient;
1685
2213
  NativePurchasesLog.d(TAG, "Querying product details");
1686
- billingClient.queryProductDetailsAsync(
2214
+ queryClient.queryProductDetailsAsync(
1687
2215
  params,
1688
2216
  new ProductDetailsResponseListener() {
1689
2217
  @Override
@@ -1699,6 +2227,15 @@ public class NativePurchasesPlugin extends Plugin {
1699
2227
  );
1700
2228
  NativePurchasesLog.d(TAG, "Product details count: " + productDetailsList.size());
1701
2229
 
2230
+ if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK) {
2231
+ closeBillingClientIfCurrent(queryClient);
2232
+ call.reject(
2233
+ "Failed to query product details: " + billingResult.getDebugMessage(),
2234
+ BillingResponseCodes.name(billingResult.getResponseCode())
2235
+ );
2236
+ return;
2237
+ }
2238
+
1702
2239
  if (productDetailsList.isEmpty()) {
1703
2240
  NativePurchasesLog.d(TAG, "No products found in query");
1704
2241
  NativePurchasesLog.d(TAG, "This usually means:");
@@ -1706,8 +2243,8 @@ public class NativePurchasesPlugin extends Plugin {
1706
2243
  NativePurchasesLog.d(TAG, "2. Product is not published/active");
1707
2244
  NativePurchasesLog.d(TAG, "3. App is not properly configured for the product type");
1708
2245
  NativePurchasesLog.d(TAG, "4. Wrong product ID or type");
1709
- closeBillingClient();
1710
- call.reject("Product not found");
2246
+ closeBillingClientIfCurrent(queryClient);
2247
+ call.reject("Product not found", BillingResponseCodes.PRODUCT_NOT_FOUND);
1711
2248
  return;
1712
2249
  }
1713
2250
  JSONArray products = new JSONArray();
@@ -1810,7 +2347,7 @@ public class NativePurchasesPlugin extends Plugin {
1810
2347
  JSObject ret = new JSObject();
1811
2348
  ret.put("products", products);
1812
2349
  NativePurchasesLog.d(TAG, "Returning " + products.length() + " products");
1813
- closeBillingClient();
2350
+ closeBillingClientIfCurrent(queryClient);
1814
2351
  call.resolve(ret);
1815
2352
  }
1816
2353
  }
@@ -2072,7 +2609,10 @@ public class NativePurchasesPlugin extends Plugin {
2072
2609
  }
2073
2610
  };
2074
2611
  if (!beginFinishingPurchase(client, onAbandon)) {
2075
- call.reject("Billing client closed before the acknowledge could run. Please try again.");
2612
+ call.reject(
2613
+ "Billing client closed before the acknowledge could run. Please try again.",
2614
+ BillingResponseCodes.BILLING_CLIENT_CLOSED
2615
+ );
2076
2616
  return;
2077
2617
  }
2078
2618
  AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
@@ -2093,7 +2633,10 @@ public class NativePurchasesPlugin extends Plugin {
2093
2633
  call.resolve();
2094
2634
  } else {
2095
2635
  NativePurchasesLog.d(TAG, "Purchase acknowledgment failed");
2096
- call.reject("Failed to acknowledge purchase: " + billingResult.getDebugMessage());
2636
+ call.reject(
2637
+ "Failed to acknowledge purchase: " + billingResult.getDebugMessage(),
2638
+ BillingResponseCodes.name(billingResult.getResponseCode())
2639
+ );
2097
2640
  }
2098
2641
  };
2099
2642
  try {
@@ -2130,7 +2673,10 @@ public class NativePurchasesPlugin extends Plugin {
2130
2673
  }
2131
2674
  };
2132
2675
  if (!beginFinishingPurchase(client, onAbandon)) {
2133
- call.reject("Billing client closed before the consume could run. Please try again.");
2676
+ call.reject(
2677
+ "Billing client closed before the consume could run. Please try again.",
2678
+ BillingResponseCodes.BILLING_CLIENT_CLOSED
2679
+ );
2134
2680
  return;
2135
2681
  }
2136
2682
  ConsumeParams consumeParams = ConsumeParams.newBuilder().setPurchaseToken(purchaseToken).build();
@@ -2149,7 +2695,10 @@ public class NativePurchasesPlugin extends Plugin {
2149
2695
  call.resolve();
2150
2696
  } else {
2151
2697
  NativePurchasesLog.d(TAG, "Purchase consumption failed");
2152
- call.reject("Failed to consume purchase: " + billingResult.getDebugMessage());
2698
+ call.reject(
2699
+ "Failed to consume purchase: " + billingResult.getDebugMessage(),
2700
+ BillingResponseCodes.name(billingResult.getResponseCode())
2701
+ );
2153
2702
  }
2154
2703
  };
2155
2704
  try {