@capgo/native-purchases 8.9.16 → 8.10.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.16";
114
+ private final String pluginVersion = "8.10.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,13 @@ 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 final Set<String> activePurchaseFlowProductIds = Collections.newSetFromMap(new ConcurrentHashMap<>());
161
+ private final AtomicInteger updatesClientPendingAcknowledgements = new AtomicInteger(0);
162
+ private volatile boolean disconnectUpdatesClientWhenIdle;
155
163
 
156
164
  @PluginMethod
157
165
  public void configure(PluginCall call) {
@@ -264,6 +272,127 @@ public class NativePurchasesPlugin extends Plugin {
264
272
  return purchaseDateFormat.format(new java.util.Date(timeMillis));
265
273
  }
266
274
 
275
+ static String productTypeForBillingQuery(String billingProductType) {
276
+ return BillingClient.ProductType.SUBS.equals(billingProductType) ? "subs" : "inapp";
277
+ }
278
+
279
+ private static boolean containsPurchaseToken(List<Purchase> purchases, String purchaseToken) {
280
+ if (purchases == null || purchaseToken == null) {
281
+ return false;
282
+ }
283
+ for (Purchase purchase : purchases) {
284
+ if (purchaseToken.equals(purchase.getPurchaseToken())) {
285
+ return true;
286
+ }
287
+ }
288
+ return false;
289
+ }
290
+
291
+ void resolveProductTypeForPurchase(BillingClient client, Purchase purchase, Consumer<String> onResolved) {
292
+ if (client == null || !client.isReady() || purchase == null) {
293
+ NativePurchasesLog.w(TAG, "Cannot resolve product type without a ready billing client");
294
+ onResolved.accept(null);
295
+ return;
296
+ }
297
+ final String purchaseToken = purchase.getPurchaseToken();
298
+ QueryPurchasesParams inAppParams = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.INAPP).build();
299
+ try {
300
+ client.queryPurchasesAsync(inAppParams, (inAppResult, inAppPurchases) -> {
301
+ if (
302
+ inAppResult.getResponseCode() == BillingClient.BillingResponseCode.OK &&
303
+ containsPurchaseToken(inAppPurchases, purchaseToken)
304
+ ) {
305
+ onResolved.accept("inapp");
306
+ return;
307
+ }
308
+ if (inAppResult.getResponseCode() != BillingClient.BillingResponseCode.OK) {
309
+ NativePurchasesLog.w(TAG, "In-app query failed while resolving product type");
310
+ onResolved.accept(null);
311
+ return;
312
+ }
313
+ QueryPurchasesParams subsParams = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build();
314
+ try {
315
+ client.queryPurchasesAsync(subsParams, (subsResult, subsPurchases) -> {
316
+ if (
317
+ subsResult.getResponseCode() == BillingClient.BillingResponseCode.OK &&
318
+ containsPurchaseToken(subsPurchases, purchaseToken)
319
+ ) {
320
+ onResolved.accept("subs");
321
+ return;
322
+ }
323
+ if (subsResult.getResponseCode() != BillingClient.BillingResponseCode.OK) {
324
+ NativePurchasesLog.w(TAG, "Subs query failed while resolving product type");
325
+ onResolved.accept(null);
326
+ return;
327
+ }
328
+ NativePurchasesLog.w(TAG, "Purchase token missing from typed queries; skipping transactionUpdated");
329
+ onResolved.accept(null);
330
+ });
331
+ } catch (RuntimeException e) {
332
+ NativePurchasesLog.w(TAG, "Subs query failed while resolving product type: " + e.getMessage());
333
+ onResolved.accept(null);
334
+ }
335
+ });
336
+ } catch (RuntimeException e) {
337
+ NativePurchasesLog.w(TAG, "In-app query failed while resolving product type: " + e.getMessage());
338
+ onResolved.accept(null);
339
+ }
340
+ }
341
+
342
+ private boolean isPurchaseHandledByActiveFlow(Purchase purchase) {
343
+ if (purchase == null || purchase.getProducts().isEmpty()) {
344
+ return false;
345
+ }
346
+ String productId = purchase.getProducts().get(0);
347
+ synchronized (billingClientLock) {
348
+ return activePurchaseFlowProductIds.contains(productId);
349
+ }
350
+ }
351
+
352
+ private void registerActivePurchaseFlowProduct(String productIdentifier) {
353
+ if (productIdentifier == null || productIdentifier.isEmpty()) {
354
+ return;
355
+ }
356
+ synchronized (billingClientLock) {
357
+ activePurchaseFlowProductIds.add(productIdentifier);
358
+ }
359
+ }
360
+
361
+ private void clearActivePurchaseFlowProducts(PluginCall purchaseCall, Purchase purchase) {
362
+ if (purchaseCall != null) {
363
+ String requestedId = purchaseCall.getString("productIdentifier");
364
+ if (requestedId != null && !requestedId.isEmpty()) {
365
+ synchronized (billingClientLock) {
366
+ activePurchaseFlowProductIds.remove(requestedId);
367
+ }
368
+ }
369
+ }
370
+ if (purchase != null) {
371
+ for (String productId : purchase.getProducts()) {
372
+ synchronized (billingClientLock) {
373
+ activePurchaseFlowProductIds.remove(productId);
374
+ }
375
+ }
376
+ }
377
+ }
378
+
379
+ private void maybeRefreshTransactionUpdatesAfterPurchaseFlow() {
380
+ synchronized (billingClientLock) {
381
+ if (!pendingBillingFlows.isEmpty()) {
382
+ return;
383
+ }
384
+ }
385
+ if (hasListeners(TRANSACTION_UPDATED_EVENT)) {
386
+ billingExecutor.execute(this::refreshTransactionUpdatesFromPlay);
387
+ }
388
+ }
389
+
390
+ private boolean isEphemeralBillingClient(BillingClient client) {
391
+ synchronized (updatesClientLock) {
392
+ return client != null && client != updatesBillingClient;
393
+ }
394
+ }
395
+
267
396
  private JSObject buildPurchaseTransactionObject(Purchase purchase, String productType) {
268
397
  AccountIdentifiers accountIdentifiers = purchase.getAccountIdentifiers();
269
398
  String purchaseAccountId = accountIdentifiers != null ? accountIdentifiers.getObfuscatedAccountId() : null;
@@ -375,6 +504,261 @@ public class NativePurchasesPlugin extends Plugin {
375
504
  NativePurchasesLog.d(TAG, "Plugin load() completed");
376
505
  }
377
506
 
507
+ @PluginMethod(returnType = PluginMethod.RETURN_NONE)
508
+ @Override
509
+ public void addListener(PluginCall call) {
510
+ String eventName = call.getString("eventName");
511
+ boolean firstTransactionUpdatedListener = TRANSACTION_UPDATED_EVENT.equals(eventName) && !hasListeners(TRANSACTION_UPDATED_EVENT);
512
+ super.addListener(call);
513
+ if (firstTransactionUpdatedListener) {
514
+ billingExecutor.execute(this::ensureTransactionUpdatesBillingClient);
515
+ }
516
+ }
517
+
518
+ @PluginMethod(returnType = PluginMethod.RETURN_NONE)
519
+ @Override
520
+ public void removeListener(PluginCall call) {
521
+ String eventName = call.getString("eventName");
522
+ super.removeListener(call);
523
+ if (TRANSACTION_UPDATED_EVENT.equals(eventName) && !hasListeners(TRANSACTION_UPDATED_EVENT)) {
524
+ billingExecutor.execute(this::disconnectTransactionUpdatesBillingClient);
525
+ }
526
+ }
527
+
528
+ @PluginMethod(returnType = PluginMethod.RETURN_PROMISE)
529
+ @Override
530
+ public void removeAllListeners(PluginCall call) {
531
+ boolean hadTransactionUpdatedListeners = hasListeners(TRANSACTION_UPDATED_EVENT);
532
+ super.removeAllListeners(call);
533
+ if (hadTransactionUpdatedListeners) {
534
+ billingExecutor.execute(this::disconnectTransactionUpdatesBillingClient);
535
+ }
536
+ }
537
+
538
+ @Override
539
+ protected void handleOnResume() {
540
+ super.handleOnResume();
541
+ if (hasListeners(TRANSACTION_UPDATED_EVENT)) {
542
+ billingExecutor.execute(this::refreshTransactionUpdatesFromPlay);
543
+ }
544
+ }
545
+
546
+ private void refreshTransactionUpdatesFromPlay() {
547
+ BillingClient client;
548
+ synchronized (updatesClientLock) {
549
+ client = updatesBillingClient;
550
+ }
551
+ if (client != null && client.isReady()) {
552
+ queryUnacknowledgedPurchasesForTransactionUpdated(client);
553
+ return;
554
+ }
555
+ ensureTransactionUpdatesBillingClient();
556
+ }
557
+
558
+ private void ensureTransactionUpdatesBillingClient() {
559
+ if (!hasListeners(TRANSACTION_UPDATED_EVENT)) {
560
+ return;
561
+ }
562
+ synchronized (updatesClientLock) {
563
+ if (updatesBillingClient != null && updatesBillingClient.isReady()) {
564
+ queryUnacknowledgedPurchasesForTransactionUpdated(updatesBillingClient);
565
+ return;
566
+ }
567
+ if (updatesBillingClient != null) {
568
+ try {
569
+ updatesBillingClient.endConnection();
570
+ } catch (RuntimeException e) {
571
+ NativePurchasesLog.w(TAG, "Failed to end stale updates billing client: " + e.getMessage());
572
+ }
573
+ updatesBillingClient = null;
574
+ }
575
+ final BillingClient[] clientHolder = new BillingClient[1];
576
+ clientHolder[0] = BillingClient.newBuilder(getContext())
577
+ .setListener(
578
+ new PurchasesUpdatedListener() {
579
+ @Override
580
+ public void onPurchasesUpdated(@NonNull BillingResult billingResult, List<Purchase> purchases) {
581
+ handleUpdatesPurchasesUpdated(billingResult, purchases, clientHolder[0]);
582
+ }
583
+ }
584
+ )
585
+ .enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build())
586
+ .build();
587
+ updatesBillingClient = clientHolder[0];
588
+ NativePurchasesLog.d(TAG, "Starting updates billing client connection");
589
+ clientHolder[0].startConnection(
590
+ new BillingClientStateListener() {
591
+ @Override
592
+ public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
593
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
594
+ queryUnacknowledgedPurchasesForTransactionUpdated(clientHolder[0]);
595
+ } else {
596
+ NativePurchasesLog.w(TAG, "Updates billing client setup failed: " + billingResult.getDebugMessage());
597
+ }
598
+ }
599
+
600
+ @Override
601
+ public void onBillingServiceDisconnected() {
602
+ NativePurchasesLog.d(TAG, "Updates billing client disconnected");
603
+ synchronized (updatesClientLock) {
604
+ if (updatesBillingClient == clientHolder[0]) {
605
+ updatesBillingClient = null;
606
+ }
607
+ }
608
+ }
609
+ }
610
+ );
611
+ }
612
+ }
613
+
614
+ private void disconnectTransactionUpdatesBillingClient() {
615
+ if (updatesClientPendingAcknowledgements.get() > 0) {
616
+ disconnectUpdatesClientWhenIdle = true;
617
+ return;
618
+ }
619
+ disconnectTransactionUpdatesBillingClientNow();
620
+ }
621
+
622
+ private void disconnectTransactionUpdatesBillingClientNow() {
623
+ disconnectUpdatesClientWhenIdle = false;
624
+ synchronized (updatesClientLock) {
625
+ if (updatesBillingClient != null) {
626
+ try {
627
+ updatesBillingClient.endConnection();
628
+ } catch (RuntimeException e) {
629
+ NativePurchasesLog.w(TAG, "Failed to end updates billing client: " + e.getMessage());
630
+ }
631
+ updatesBillingClient = null;
632
+ }
633
+ }
634
+ }
635
+
636
+ private void maybeFinishDeferredUpdatesClientDisconnect() {
637
+ if (
638
+ disconnectUpdatesClientWhenIdle && updatesClientPendingAcknowledgements.get() == 0 && !hasListeners(TRANSACTION_UPDATED_EVENT)
639
+ ) {
640
+ disconnectTransactionUpdatesBillingClientNow();
641
+ }
642
+ }
643
+
644
+ private void queryUnacknowledgedPurchasesForTransactionUpdated(BillingClient client) {
645
+ if (client == null || !client.isReady() || !hasListeners(TRANSACTION_UPDATED_EVENT)) {
646
+ return;
647
+ }
648
+ queryUnacknowledgedPurchasesForTransactionUpdated(client, BillingClient.ProductType.INAPP);
649
+ queryUnacknowledgedPurchasesForTransactionUpdated(client, BillingClient.ProductType.SUBS);
650
+ }
651
+
652
+ private void queryUnacknowledgedPurchasesForTransactionUpdated(BillingClient client, String billingProductType) {
653
+ final String productType = productTypeForBillingQuery(billingProductType);
654
+ QueryPurchasesParams params = QueryPurchasesParams.newBuilder().setProductType(billingProductType).build();
655
+ try {
656
+ client.queryPurchasesAsync(params, (billingResult, purchases) -> {
657
+ if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK || purchases == null) {
658
+ return;
659
+ }
660
+ for (Purchase purchase : purchases) {
661
+ if (
662
+ purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED &&
663
+ !purchase.isAcknowledged() &&
664
+ !isPurchaseHandledByActiveFlow(purchase)
665
+ ) {
666
+ processPurchaseForTransactionUpdated(purchase, productType, client);
667
+ }
668
+ }
669
+ });
670
+ } catch (RuntimeException e) {
671
+ NativePurchasesLog.w(TAG, "queryPurchasesAsync failed for transactionUpdated recovery: " + e.getMessage());
672
+ }
673
+ }
674
+
675
+ void handleUpdatesPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases, BillingClient client) {
676
+ if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK || purchases == null) {
677
+ return;
678
+ }
679
+ for (Purchase purchase : purchases) {
680
+ if (isPurchaseHandledByActiveFlow(purchase)) {
681
+ NativePurchasesLog.d(TAG, "Skipping transactionUpdated for in-flight purchaseProduct");
682
+ continue;
683
+ }
684
+ processPurchaseForTransactionUpdatedWithResolvedType(purchase, client);
685
+ }
686
+ }
687
+
688
+ private void processPurchaseForTransactionUpdatedWithResolvedType(Purchase purchase, BillingClient client) {
689
+ resolveProductTypeForPurchase(client, purchase, (productType) ->
690
+ processPurchaseForTransactionUpdated(purchase, productType, client)
691
+ );
692
+ }
693
+
694
+ /**
695
+ * @return true when an async acknowledge is in flight on an ephemeral billing client that must
696
+ * stay open until the callback runs.
697
+ */
698
+ boolean processPurchaseForTransactionUpdated(Purchase purchase, String productType, BillingClient client) {
699
+ if (!hasListeners(TRANSACTION_UPDATED_EVENT)) {
700
+ return false;
701
+ }
702
+ if (productType == null) {
703
+ return false;
704
+ }
705
+ int purchaseState = purchase.getPurchaseState();
706
+ if (purchaseState != Purchase.PurchaseState.PURCHASED && purchaseState != Purchase.PurchaseState.PENDING) {
707
+ return false;
708
+ }
709
+ JSObject payload = buildPurchaseTransactionObject(purchase, productType);
710
+ if (purchaseState == Purchase.PurchaseState.PURCHASED) {
711
+ if (autoFinishTransactions) {
712
+ PurchaseAction action = PurchaseActionDecider.decide(false, purchase);
713
+ if (action == PurchaseAction.ACKNOWLEDGE && client != null && client.isReady()) {
714
+ final boolean trackFinishOnEphemeralClient = isEphemeralBillingClient(client);
715
+ final boolean trackFinishOnUpdatesClient = !trackFinishOnEphemeralClient;
716
+ if (trackFinishOnEphemeralClient && !beginFinishingPurchase(client)) {
717
+ NativePurchasesLog.w(TAG, "Ephemeral billing client unavailable for transactionUpdated ack");
718
+ if (!purchase.isAcknowledged()) {
719
+ payload.put("needsFinish", true);
720
+ }
721
+ notifyListeners(TRANSACTION_UPDATED_EVENT, payload);
722
+ return false;
723
+ }
724
+ if (trackFinishOnUpdatesClient) {
725
+ updatesClientPendingAcknowledgements.incrementAndGet();
726
+ }
727
+ acknowledgePurchase(client, purchase.getPurchaseToken(), (billingResult) -> {
728
+ if (billingResult != null && billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
729
+ payload.put("isAcknowledged", true);
730
+ } else if (!purchase.isAcknowledged()) {
731
+ payload.put("needsFinish", true);
732
+ }
733
+ if (trackFinishOnEphemeralClient) {
734
+ endFinishingPurchase(client);
735
+ }
736
+ if (trackFinishOnUpdatesClient) {
737
+ if (updatesClientPendingAcknowledgements.decrementAndGet() == 0) {
738
+ maybeFinishDeferredUpdatesClientDisconnect();
739
+ }
740
+ }
741
+ notifyListeners(TRANSACTION_UPDATED_EVENT, payload);
742
+ });
743
+ return trackFinishOnEphemeralClient;
744
+ } else if (action == PurchaseAction.ACKNOWLEDGE && !purchase.isAcknowledged()) {
745
+ payload.put("needsFinish", true);
746
+ }
747
+ } else if (!purchase.isAcknowledged()) {
748
+ payload.put("needsFinish", true);
749
+ }
750
+ }
751
+ notifyListeners(TRANSACTION_UPDATED_EVENT, payload);
752
+ return false;
753
+ }
754
+
755
+ private void finishEphemeralTransactionUpdatedHandling(BillingClient owner, boolean keepClientOpenForAsyncWork) {
756
+ endPendingBillingFlow(owner);
757
+ if (!keepClientOpenForAsyncWork) {
758
+ closeBillingClientIfCurrent(owner);
759
+ }
760
+ }
761
+
378
762
  @FunctionalInterface
379
763
  private interface BillingTask {
380
764
  void run() throws Exception;
@@ -402,6 +786,12 @@ public class NativePurchasesPlugin extends Plugin {
402
786
  protected void handleOnDestroy() {
403
787
  billingExecutor.shutdownNow();
404
788
  List<BillingClient> clientsToEnd = new ArrayList<>();
789
+ synchronized (updatesClientLock) {
790
+ if (updatesBillingClient != null) {
791
+ clientsToEnd.add(updatesBillingClient);
792
+ updatesBillingClient = null;
793
+ }
794
+ }
405
795
  synchronized (billingClientLock) {
406
796
  if (billingClient != null) {
407
797
  clientsToEnd.add(billingClient);
@@ -611,6 +1001,9 @@ public class NativePurchasesPlugin extends Plugin {
611
1001
  }
612
1002
  billingClientLock.notifyAll();
613
1003
  }
1004
+ if (last) {
1005
+ maybeRefreshTransactionUpdatesAfterPurchaseFlow();
1006
+ }
614
1007
  if (last && !finishInFlight) {
615
1008
  client.endConnection();
616
1009
  }
@@ -624,6 +1017,10 @@ public class NativePurchasesPlugin extends Plugin {
624
1017
  registerPurchaseCallSettlement(call);
625
1018
  }
626
1019
 
1020
+ void setAutoFinishTransactionsForTest(boolean value) {
1021
+ autoFinishTransactions = value;
1022
+ }
1023
+
627
1024
  private boolean trySettlePurchaseCall(PluginCall call) {
628
1025
  if (call == null) {
629
1026
  return false;
@@ -654,12 +1051,14 @@ public class NativePurchasesPlugin extends Plugin {
654
1051
  }
655
1052
 
656
1053
  private void abortPurchaseClientFlow(BillingClient purchaseClient, PluginCall call, String message) {
1054
+ clearActivePurchaseFlowProducts(call, null);
657
1055
  endPendingBillingFlow(purchaseClient);
658
1056
  closeBillingClientIfCurrent(purchaseClient);
659
1057
  rejectPurchaseCallOnce(call, message);
660
1058
  }
661
1059
 
662
1060
  private void abortPurchaseClientFlow(BillingClient purchaseClient, PluginCall call, String message, String code) {
1061
+ clearActivePurchaseFlowProducts(call, null);
663
1062
  endPendingBillingFlow(purchaseClient);
664
1063
  closeBillingClientIfCurrent(purchaseClient);
665
1064
  rejectPurchaseCallOnce(call, message, code);
@@ -670,13 +1069,14 @@ public class NativePurchasesPlugin extends Plugin {
670
1069
  * not the shared {@link #billingClient} field.
671
1070
  */
672
1071
  void launchPurchaseBillingFlow(BillingClient flowClient, PluginCall call, BillingFlowParams billingFlowParams) {
1072
+ registerActivePurchaseFlowProduct(call.getString("productIdentifier"));
673
1073
  if (flowClient == null || !flowClient.isReady()) {
674
1074
  NativePurchasesLog.w(TAG, "Purchase billing client closed before launch");
675
1075
  abortPurchaseClientFlow(
676
1076
  flowClient,
677
1077
  call,
678
1078
  "Purchase is not purchased",
679
- billingResponseCodeName(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
1079
+ BillingResponseCodes.name(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
680
1080
  );
681
1081
  return;
682
1082
  }
@@ -684,6 +1084,7 @@ public class NativePurchasesPlugin extends Plugin {
684
1084
  try {
685
1085
  billingResult2 = flowClient.launchBillingFlow(getActivity(), billingFlowParams);
686
1086
  } catch (RuntimeException launchError) {
1087
+ clearActivePurchaseFlowProducts(call, null);
687
1088
  endPendingBillingFlow(flowClient);
688
1089
  throw launchError;
689
1090
  }
@@ -693,12 +1094,35 @@ public class NativePurchasesPlugin extends Plugin {
693
1094
  );
694
1095
  NativePurchasesLog.i(NativePurchasesPlugin.TAG, "onProductDetailsResponse2" + billingResult2);
695
1096
  if (billingResult2.getResponseCode() != BillingClient.BillingResponseCode.OK) {
1097
+ clearActivePurchaseFlowProducts(call, null);
696
1098
  endPendingBillingFlow(flowClient);
697
- rejectPurchaseCallOnce(call, "Purchase is not purchased", billingResponseCodeName(billingResult2.getResponseCode()));
1099
+ rejectPurchaseCallOnce(call, "Purchase is not purchased", BillingResponseCodes.name(billingResult2.getResponseCode()));
698
1100
  closeBillingClientIfCurrent(flowClient);
699
1101
  }
700
1102
  }
701
1103
 
1104
+ /**
1105
+ * Play Billing calls {@code queryProductDetailsAsync} listeners on its worker pool, but
1106
+ * {@link BillingClient#launchBillingFlow} must run on the UI thread. Package-private for tests.
1107
+ */
1108
+ void launchPurchaseBillingFlowOnUiThread(BillingClient purchaseClient, PluginCall call, BillingFlowParams billingFlowParams) {
1109
+ final android.app.Activity launchActivity = getActivity();
1110
+ if (launchActivity == null) {
1111
+ NativePurchasesLog.e(TAG, "Cannot launch billing flow: no activity");
1112
+ abortPurchaseClientFlow(purchaseClient, call, "Purchase could not start");
1113
+ return;
1114
+ }
1115
+ NativePurchasesLog.d(TAG, "Launching billing flow on the UI thread");
1116
+ launchActivity.runOnUiThread(() -> {
1117
+ try {
1118
+ launchPurchaseBillingFlow(purchaseClient, call, billingFlowParams);
1119
+ } catch (RuntimeException launchError) {
1120
+ NativePurchasesLog.e(TAG, "Billing flow launch failed: " + launchError.getMessage());
1121
+ abortPurchaseClientFlow(purchaseClient, call, "Purchase could not start");
1122
+ }
1123
+ });
1124
+ }
1125
+
702
1126
  /**
703
1127
  * Reject a purchase whose {@code offerToken} matched no current offer.
704
1128
  *
@@ -732,46 +1156,11 @@ public class NativePurchasesPlugin extends Plugin {
732
1156
  }
733
1157
  }
734
1158
 
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
1159
  private static String describeQueryFailure(String productType, BillingResult billingResult) {
771
1160
  return (
772
1161
  productType +
773
1162
  ": " +
774
- billingResponseCodeName(billingResult.getResponseCode()) +
1163
+ BillingResponseCodes.name(billingResult.getResponseCode()) +
775
1164
  " (" +
776
1165
  billingResult.getResponseCode() +
777
1166
  ") " +
@@ -781,7 +1170,7 @@ public class NativePurchasesPlugin extends Plugin {
781
1170
 
782
1171
  private void rejectBillingSetupCall(PluginCall purchaseCall, AtomicBoolean callRejected, String code, String message) {
783
1172
  if (purchaseCall != null && callRejected.compareAndSet(false, true)) {
784
- purchaseCall.reject(code, message);
1173
+ purchaseCall.reject(message, code);
785
1174
  }
786
1175
  }
787
1176
 
@@ -928,7 +1317,7 @@ public class NativePurchasesPlugin extends Plugin {
928
1317
  } else if (purchase.getPurchaseState() == Purchase.PurchaseState.PENDING) {
929
1318
  NativePurchasesLog.d(TAG, "Purchase state is PENDING");
930
1319
  if (purchaseCall != null) {
931
- rejectPurchaseCallOnce(purchaseCall, "Purchase is pending");
1320
+ rejectPurchaseCallOnce(purchaseCall, "Purchase is pending", BillingResponseCodes.PURCHASE_PENDING);
932
1321
  } else {
933
1322
  NativePurchasesLog.d(TAG, "purchaseCall is null for pending purchase");
934
1323
  }
@@ -1047,24 +1436,58 @@ public class NativePurchasesPlugin extends Plugin {
1047
1436
  NativePurchasesLog.d(TAG, "Billing result: " + billingResult.getResponseCode() + " - " + billingResult.getDebugMessage());
1048
1437
  NativePurchasesLog.d(TAG, "Purchases count: " + (purchases != null ? purchases.size() : 0));
1049
1438
  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);
1439
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchases != null && purchaseCall == null) {
1440
+ NativePurchasesLog.d(TAG, "Purchase update outside purchaseProduct, emitting transactionUpdated");
1441
+ if (purchases.isEmpty()) {
1442
+ finishEphemeralTransactionUpdatedHandling(owner, false);
1054
1443
  return;
1055
1444
  }
1445
+ AtomicInteger pendingResolutions = new AtomicInteger(purchases.size());
1446
+ AtomicBoolean keepClientOpenForAsyncWork = new AtomicBoolean(false);
1447
+ for (Purchase purchase : purchases) {
1448
+ resolveProductTypeForPurchase(owner, purchase, (productType) -> {
1449
+ if (processPurchaseForTransactionUpdated(purchase, productType, owner)) {
1450
+ keepClientOpenForAsyncWork.set(true);
1451
+ }
1452
+ if (pendingResolutions.decrementAndGet() <= 0) {
1453
+ finishEphemeralTransactionUpdatedHandling(owner, keepClientOpenForAsyncWork.get());
1454
+ }
1455
+ });
1456
+ }
1457
+ return;
1458
+ }
1459
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
1460
+ if (purchases != null && !purchases.isEmpty()) {
1461
+ NativePurchasesLog.d(TAG, "Purchase update successful, processing first purchase");
1462
+ Purchase firstPurchase = purchases.get(0);
1463
+ if (handlePurchase(firstPurchase, purchaseCall, owner)) {
1464
+ clearActivePurchaseFlowProducts(purchaseCall, firstPurchase);
1465
+ endPendingBillingFlow(owner);
1466
+ return;
1467
+ }
1468
+ clearActivePurchaseFlowProducts(purchaseCall, firstPurchase);
1469
+ } else {
1470
+ NativePurchasesLog.d(TAG, "Purchase update OK but no purchases returned");
1471
+ if (purchaseCall != null) {
1472
+ clearActivePurchaseFlowProducts(purchaseCall, null);
1473
+ if (purchaseCallSettlement.containsKey(purchaseCall)) {
1474
+ rejectPurchaseCallOnce(purchaseCall, "Purchase is not purchased", BillingResponseCodes.PURCHASE_NOT_FOUND);
1475
+ } else {
1476
+ purchaseCall.reject("Purchase is not purchased", BillingResponseCodes.PURCHASE_NOT_FOUND);
1477
+ }
1478
+ }
1479
+ }
1056
1480
  } else {
1057
- NativePurchasesLog.d(TAG, "Purchase update failed or purchases is null");
1481
+ NativePurchasesLog.d(TAG, "Purchase update failed");
1058
1482
  NativePurchasesLog.i(NativePurchasesPlugin.TAG, "onPurchasesUpdated" + billingResult);
1059
1483
  if (purchaseCall != null) {
1484
+ String code = BillingResponseCodes.name(billingResult.getResponseCode());
1485
+ Purchase failedPurchase = purchases != null && !purchases.isEmpty() ? purchases.get(0) : null;
1486
+ clearActivePurchaseFlowProducts(purchaseCall, failedPurchase);
1060
1487
  if (purchaseCallSettlement.containsKey(purchaseCall)) {
1061
- rejectPurchaseCallOnce(
1062
- purchaseCall,
1063
- "Purchase is not purchased",
1064
- billingResponseCodeName(billingResult.getResponseCode())
1065
- );
1488
+ rejectPurchaseCallOnce(purchaseCall, "Purchase is not purchased", code);
1066
1489
  } else {
1067
- purchaseCall.reject("Purchase is not purchased", billingResponseCodeName(billingResult.getResponseCode()));
1490
+ purchaseCall.reject("Purchase is not purchased", code);
1068
1491
  }
1069
1492
  }
1070
1493
  }
@@ -1286,7 +1709,7 @@ public class NativePurchasesPlugin extends Plugin {
1286
1709
  purchaseClient,
1287
1710
  call,
1288
1711
  "Purchase is not purchased",
1289
- billingResponseCodeName(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
1712
+ BillingResponseCodes.name(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
1290
1713
  );
1291
1714
  return;
1292
1715
  }
@@ -1312,14 +1735,14 @@ public class NativePurchasesPlugin extends Plugin {
1312
1735
  purchaseClient,
1313
1736
  call,
1314
1737
  "Purchase is not purchased",
1315
- billingResponseCodeName(billingResult.getResponseCode())
1738
+ BillingResponseCodes.name(billingResult.getResponseCode())
1316
1739
  );
1317
1740
  return;
1318
1741
  }
1319
1742
 
1320
1743
  if (productDetailsList.isEmpty()) {
1321
1744
  NativePurchasesLog.d(TAG, "No products found");
1322
- abortPurchaseClientFlow(purchaseClient, call, "Product not found");
1745
+ abortPurchaseClientFlow(purchaseClient, call, "Product not found", BillingResponseCodes.PRODUCT_NOT_FOUND);
1323
1746
  return;
1324
1747
  }
1325
1748
  // Process the result
@@ -1404,7 +1827,7 @@ public class NativePurchasesPlugin extends Plugin {
1404
1827
  }
1405
1828
  BillingFlowParams billingFlowParams = billingFlowBuilder.build();
1406
1829
  NativePurchasesLog.d(TAG, "Launching billing flow");
1407
- launchPurchaseBillingFlow(purchaseClient, call, billingFlowParams);
1830
+ launchPurchaseBillingFlowOnUiThread(purchaseClient, call, billingFlowParams);
1408
1831
  }
1409
1832
  }
1410
1833
  );
@@ -1518,7 +1941,7 @@ public class NativePurchasesPlugin extends Plugin {
1518
1941
  /** Body of restorePurchases once a client exists. Package-private for tests. */
1519
1942
  void restoreWithClient(PluginCall call, BillingClient client) {
1520
1943
  if (!processUnfinishedPurchases(client)) {
1521
- call.reject("Billing client closed before restore could run. Please try again.");
1944
+ call.reject("Billing client closed before restore could run. Please try again.", BillingResponseCodes.BILLING_CLIENT_CLOSED);
1522
1945
  return;
1523
1946
  }
1524
1947
  call.resolve();
@@ -1541,8 +1964,9 @@ public class NativePurchasesPlugin extends Plugin {
1541
1964
  QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder().setProductList(productList).build();
1542
1965
  NativePurchasesLog.d(TAG, "Initializing billing client for single product query");
1543
1966
  withBillingClient(call, () -> {
1967
+ final BillingClient queryClient = billingClient;
1544
1968
  NativePurchasesLog.d(TAG, "Querying product details");
1545
- billingClient.queryProductDetailsAsync(
1969
+ queryClient.queryProductDetailsAsync(
1546
1970
  params,
1547
1971
  new ProductDetailsResponseListener() {
1548
1972
  @Override
@@ -1558,6 +1982,15 @@ public class NativePurchasesPlugin extends Plugin {
1558
1982
  );
1559
1983
  NativePurchasesLog.d(TAG, "Product details count: " + productDetailsList.size());
1560
1984
 
1985
+ if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK) {
1986
+ closeBillingClientIfCurrent(queryClient);
1987
+ call.reject(
1988
+ "Failed to query product details: " + billingResult.getDebugMessage(),
1989
+ BillingResponseCodes.name(billingResult.getResponseCode())
1990
+ );
1991
+ return;
1992
+ }
1993
+
1561
1994
  if (productDetailsList.isEmpty()) {
1562
1995
  NativePurchasesLog.d(TAG, "No product found in query");
1563
1996
  NativePurchasesLog.d(TAG, "This usually means:");
@@ -1565,8 +1998,8 @@ public class NativePurchasesPlugin extends Plugin {
1565
1998
  NativePurchasesLog.d(TAG, "2. Product is not published/active");
1566
1999
  NativePurchasesLog.d(TAG, "3. App is not properly configured for the product type");
1567
2000
  NativePurchasesLog.d(TAG, "4. Wrong product ID or type");
1568
- closeBillingClient();
1569
- call.reject("Product not found");
2001
+ closeBillingClientIfCurrent(queryClient);
2002
+ call.reject("Product not found", BillingResponseCodes.PRODUCT_NOT_FOUND);
1570
2003
  return;
1571
2004
  }
1572
2005
 
@@ -1587,7 +2020,7 @@ public class NativePurchasesPlugin extends Plugin {
1587
2020
  TAG,
1588
2021
  "No one-time purchase offer details found for product: " + productDetails.getProductId()
1589
2022
  );
1590
- closeBillingClient();
2023
+ closeBillingClientIfCurrent(queryClient);
1591
2024
  call.reject("No one-time purchase offer details found for product: " + productDetails.getProductId());
1592
2025
  return;
1593
2026
  }
@@ -1607,7 +2040,7 @@ public class NativePurchasesPlugin extends Plugin {
1607
2040
  TAG,
1608
2041
  "No subscription offer details found for product: " + productDetails.getProductId()
1609
2042
  );
1610
- closeBillingClient();
2043
+ closeBillingClientIfCurrent(queryClient);
1611
2044
  call.reject("No subscription offers found for product: " + productDetails.getProductId());
1612
2045
  return;
1613
2046
  }
@@ -1628,7 +2061,7 @@ public class NativePurchasesPlugin extends Plugin {
1628
2061
  TAG,
1629
2062
  "No offers with pricing phases found for product: " + productDetails.getProductId()
1630
2063
  );
1631
- closeBillingClient();
2064
+ closeBillingClientIfCurrent(queryClient);
1632
2065
  call.reject("No pricing phases found for product: " + productDetails.getProductId());
1633
2066
  return;
1634
2067
  }
@@ -1654,7 +2087,7 @@ public class NativePurchasesPlugin extends Plugin {
1654
2087
  JSObject ret = new JSObject();
1655
2088
  ret.put("product", product);
1656
2089
  NativePurchasesLog.d(TAG, "Returning single product");
1657
- closeBillingClient();
2090
+ closeBillingClientIfCurrent(queryClient);
1658
2091
  call.resolve(ret);
1659
2092
  }
1660
2093
  }
@@ -1682,8 +2115,9 @@ public class NativePurchasesPlugin extends Plugin {
1682
2115
  QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder().setProductList(productList).build();
1683
2116
  NativePurchasesLog.d(TAG, "Initializing billing client for product query");
1684
2117
  withBillingClient(call, () -> {
2118
+ final BillingClient queryClient = billingClient;
1685
2119
  NativePurchasesLog.d(TAG, "Querying product details");
1686
- billingClient.queryProductDetailsAsync(
2120
+ queryClient.queryProductDetailsAsync(
1687
2121
  params,
1688
2122
  new ProductDetailsResponseListener() {
1689
2123
  @Override
@@ -1699,6 +2133,15 @@ public class NativePurchasesPlugin extends Plugin {
1699
2133
  );
1700
2134
  NativePurchasesLog.d(TAG, "Product details count: " + productDetailsList.size());
1701
2135
 
2136
+ if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK) {
2137
+ closeBillingClientIfCurrent(queryClient);
2138
+ call.reject(
2139
+ "Failed to query product details: " + billingResult.getDebugMessage(),
2140
+ BillingResponseCodes.name(billingResult.getResponseCode())
2141
+ );
2142
+ return;
2143
+ }
2144
+
1702
2145
  if (productDetailsList.isEmpty()) {
1703
2146
  NativePurchasesLog.d(TAG, "No products found in query");
1704
2147
  NativePurchasesLog.d(TAG, "This usually means:");
@@ -1706,8 +2149,8 @@ public class NativePurchasesPlugin extends Plugin {
1706
2149
  NativePurchasesLog.d(TAG, "2. Product is not published/active");
1707
2150
  NativePurchasesLog.d(TAG, "3. App is not properly configured for the product type");
1708
2151
  NativePurchasesLog.d(TAG, "4. Wrong product ID or type");
1709
- closeBillingClient();
1710
- call.reject("Product not found");
2152
+ closeBillingClientIfCurrent(queryClient);
2153
+ call.reject("Product not found", BillingResponseCodes.PRODUCT_NOT_FOUND);
1711
2154
  return;
1712
2155
  }
1713
2156
  JSONArray products = new JSONArray();
@@ -1810,7 +2253,7 @@ public class NativePurchasesPlugin extends Plugin {
1810
2253
  JSObject ret = new JSObject();
1811
2254
  ret.put("products", products);
1812
2255
  NativePurchasesLog.d(TAG, "Returning " + products.length() + " products");
1813
- closeBillingClient();
2256
+ closeBillingClientIfCurrent(queryClient);
1814
2257
  call.resolve(ret);
1815
2258
  }
1816
2259
  }
@@ -2072,7 +2515,10 @@ public class NativePurchasesPlugin extends Plugin {
2072
2515
  }
2073
2516
  };
2074
2517
  if (!beginFinishingPurchase(client, onAbandon)) {
2075
- call.reject("Billing client closed before the acknowledge could run. Please try again.");
2518
+ call.reject(
2519
+ "Billing client closed before the acknowledge could run. Please try again.",
2520
+ BillingResponseCodes.BILLING_CLIENT_CLOSED
2521
+ );
2076
2522
  return;
2077
2523
  }
2078
2524
  AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
@@ -2093,7 +2539,10 @@ public class NativePurchasesPlugin extends Plugin {
2093
2539
  call.resolve();
2094
2540
  } else {
2095
2541
  NativePurchasesLog.d(TAG, "Purchase acknowledgment failed");
2096
- call.reject("Failed to acknowledge purchase: " + billingResult.getDebugMessage());
2542
+ call.reject(
2543
+ "Failed to acknowledge purchase: " + billingResult.getDebugMessage(),
2544
+ BillingResponseCodes.name(billingResult.getResponseCode())
2545
+ );
2097
2546
  }
2098
2547
  };
2099
2548
  try {
@@ -2130,7 +2579,10 @@ public class NativePurchasesPlugin extends Plugin {
2130
2579
  }
2131
2580
  };
2132
2581
  if (!beginFinishingPurchase(client, onAbandon)) {
2133
- call.reject("Billing client closed before the consume could run. Please try again.");
2582
+ call.reject(
2583
+ "Billing client closed before the consume could run. Please try again.",
2584
+ BillingResponseCodes.BILLING_CLIENT_CLOSED
2585
+ );
2134
2586
  return;
2135
2587
  }
2136
2588
  ConsumeParams consumeParams = ConsumeParams.newBuilder().setPurchaseToken(purchaseToken).build();
@@ -2149,7 +2601,10 @@ public class NativePurchasesPlugin extends Plugin {
2149
2601
  call.resolve();
2150
2602
  } else {
2151
2603
  NativePurchasesLog.d(TAG, "Purchase consumption failed");
2152
- call.reject("Failed to consume purchase: " + billingResult.getDebugMessage());
2604
+ call.reject(
2605
+ "Failed to consume purchase: " + billingResult.getDebugMessage(),
2606
+ BillingResponseCodes.name(billingResult.getResponseCode())
2607
+ );
2153
2608
  }
2154
2609
  };
2155
2610
  try {