@capgo/native-purchases 8.4.3 → 8.4.5

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.
@@ -31,9 +31,7 @@ import java.util.ArrayList;
31
31
  import java.util.Collections;
32
32
  import java.util.List;
33
33
  import java.util.concurrent.CountDownLatch;
34
- import java.util.concurrent.Phaser;
35
34
  import java.util.concurrent.TimeUnit;
36
- import java.util.concurrent.TimeoutException;
37
35
  import java.util.concurrent.atomic.AtomicBoolean;
38
36
  import java.util.concurrent.atomic.AtomicInteger;
39
37
  import org.json.JSONArray;
@@ -41,12 +39,13 @@ import org.json.JSONArray;
41
39
  @CapacitorPlugin(name = "NativePurchases")
42
40
  public class NativePurchasesPlugin extends Plugin {
43
41
 
44
- private final String pluginVersion = "8.4.3";
42
+ private final String pluginVersion = "8.4.5";
45
43
  public static final String TAG = "NativePurchases";
46
- private static final Phaser semaphoreReady = new Phaser(1);
44
+ private static final int BILLING_CONNECTION_MAX_ATTEMPTS = 3;
45
+ private static final long BILLING_SETUP_TIMEOUT_SECONDS = 10;
46
+ private static final long[] BILLING_CONNECTION_BACKOFF_MS = { 0, 1000, 2000 };
47
+ private final Object billingClientLock = new Object();
47
48
  private BillingClient billingClient;
48
- private PluginCall pendingCall = null;
49
- private BillingResult lastBillingError = null;
50
49
 
51
50
  @PluginMethod
52
51
  public void isBillingSupported(PluginCall call) {
@@ -84,62 +83,46 @@ public class NativePurchasesPlugin extends Plugin {
84
83
  super.load();
85
84
  Log.d(TAG, "Plugin load() called");
86
85
  Log.i(NativePurchasesPlugin.TAG, "load");
87
- semaphoreDown();
88
86
  Log.d(TAG, "Plugin load() completed");
89
87
  }
90
88
 
91
- private void semaphoreWait() {
92
- Log.d(TAG, "semaphoreWait() called with waitTime: " + (Number) 10);
93
- Log.i(NativePurchasesPlugin.TAG, "semaphoreWait " + (Number) 10);
94
- try {
95
- // Log.i(CapacitorUpdater.TAG, "semaphoreReady count " + CapacitorUpdaterPlugin.this.semaphoreReady.getCount());
96
- semaphoreReady.awaitAdvanceInterruptibly(semaphoreReady.getPhase(), ((Number) 10).longValue(), TimeUnit.SECONDS);
97
- // Log.i(CapacitorUpdater.TAG, "semaphoreReady await " + res);
98
- Log.i(NativePurchasesPlugin.TAG, "semaphoreReady count " + semaphoreReady.getPhase());
99
- Log.d(TAG, "semaphoreWait() completed successfully");
100
- } catch (InterruptedException e) {
101
- Log.d(TAG, "semaphoreWait() InterruptedException: " + e.getMessage());
102
- Log.i(NativePurchasesPlugin.TAG, "semaphoreWait InterruptedException");
103
- e.printStackTrace();
104
- } catch (TimeoutException e) {
105
- Log.d(TAG, "semaphoreWait() TimeoutException: " + e.getMessage());
106
- throw new RuntimeException(e);
89
+ private void closeBillingClient() {
90
+ synchronized (billingClientLock) {
91
+ closeBillingClientLocked();
107
92
  }
108
93
  }
109
94
 
110
- private void semaphoreUp() {
111
- Log.d(TAG, "semaphoreUp() called");
112
- Log.i(NativePurchasesPlugin.TAG, "semaphoreUp");
113
- semaphoreReady.register();
114
- Log.d(TAG, "semaphoreUp() completed");
115
- }
116
-
117
- private void semaphoreDown() {
118
- Log.d(TAG, "semaphoreDown() called");
119
- Log.i(NativePurchasesPlugin.TAG, "semaphoreDown");
120
- Log.i(NativePurchasesPlugin.TAG, "semaphoreDown count " + semaphoreReady.getPhase());
121
- semaphoreReady.arriveAndDeregister();
122
- Log.d(TAG, "semaphoreDown() completed");
123
- }
124
-
125
- private void closeBillingClient() {
95
+ private void closeBillingClientLocked() {
126
96
  Log.d(TAG, "closeBillingClient() called");
127
97
  if (billingClient != null) {
128
98
  Log.d(TAG, "Ending billing client connection");
129
99
  billingClient.endConnection();
130
100
  billingClient = null;
131
- semaphoreDown();
132
101
  Log.d(TAG, "Billing client closed and set to null");
133
102
  } else {
134
103
  Log.d(TAG, "Billing client was already null");
135
104
  }
105
+ }
106
+
107
+ private void rejectBillingSetupCall(PluginCall purchaseCall, AtomicBoolean callRejected, String code, String message) {
108
+ if (purchaseCall != null && callRejected.compareAndSet(false, true)) {
109
+ purchaseCall.reject(code, message);
110
+ }
111
+ }
136
112
 
137
- // Clear pending call and error state
138
- if (pendingCall != null) {
139
- Log.w(TAG, "Warning: Clearing pending call that was never resolved/rejected");
140
- pendingCall = null;
113
+ private String getBillingSetupErrorMessage(BillingResult billingResult) {
114
+ switch (billingResult.getResponseCode()) {
115
+ case BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE:
116
+ return "Billing service unavailable. Please check your internet connection and Google Play Services.";
117
+ case BillingClient.BillingResponseCode.BILLING_UNAVAILABLE:
118
+ return "Billing is not available on this device.";
119
+ case BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED:
120
+ return "This billing feature is not supported.";
121
+ case BillingClient.BillingResponseCode.SERVICE_DISCONNECTED:
122
+ return "Billing service disconnected. Please try again.";
123
+ default:
124
+ return "Billing setup failed: " + billingResult.getDebugMessage();
141
125
  }
142
- lastBillingError = null;
143
126
  }
144
127
 
145
128
  private void handlePurchase(Purchase purchase, PluginCall purchaseCall) {
@@ -265,137 +248,181 @@ public class NativePurchasesPlugin extends Plugin {
265
248
  Log.d(TAG, "initBillingClient() called");
266
249
  Log.d(TAG, "purchaseCall is null: " + (purchaseCall == null));
267
250
 
268
- // Store the pending call so we can reject it if billing setup fails
269
- this.pendingCall = purchaseCall;
270
- this.lastBillingError = null;
271
-
272
- semaphoreWait();
273
- closeBillingClient();
274
- semaphoreUp();
275
- CountDownLatch semaphoreReady = new CountDownLatch(1);
276
- Log.d(TAG, "Creating new BillingClient");
277
- billingClient = BillingClient.newBuilder(getContext())
278
- .setListener(
279
- new PurchasesUpdatedListener() {
280
- @Override
281
- public void onPurchasesUpdated(@NonNull BillingResult billingResult, List<Purchase> purchases) {
282
- Log.d(TAG, "onPurchasesUpdated() called");
283
- Log.d(TAG, "Billing result: " + billingResult.getResponseCode() + " - " + billingResult.getDebugMessage());
284
- Log.d(TAG, "Purchases count: " + (purchases != null ? purchases.size() : 0));
285
- Log.i(NativePurchasesPlugin.TAG, "onPurchasesUpdated" + billingResult);
286
- if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchases != null) {
287
- Log.d(TAG, "Purchase update successful, processing first purchase");
288
- // for (Purchase purchase : purchases) {
289
- // handlePurchase(purchase, purchaseCall);
290
- // }
291
- handlePurchase(purchases.get(0), purchaseCall);
292
- } else {
293
- // Handle any other error codes.
294
- Log.d(TAG, "Purchase update failed or purchases is null");
251
+ synchronized (billingClientLock) {
252
+ closeBillingClientLocked();
253
+ }
254
+
255
+ final AtomicBoolean setupCallRejected = new AtomicBoolean(false);
256
+ RuntimeException lastFailure = null;
257
+
258
+ for (int attempt = 1; attempt <= BILLING_CONNECTION_MAX_ATTEMPTS; attempt++) {
259
+ if (attempt > 1) {
260
+ long backoffMs = BILLING_CONNECTION_BACKOFF_MS[Math.min(attempt - 1, BILLING_CONNECTION_BACKOFF_MS.length - 1)];
261
+ Log.d(
262
+ TAG,
263
+ "Retrying billing client connection (attempt " +
264
+ attempt +
265
+ "/" +
266
+ BILLING_CONNECTION_MAX_ATTEMPTS +
267
+ ") after " +
268
+ backoffMs +
269
+ "ms"
270
+ );
271
+ try {
272
+ Thread.sleep(backoffMs);
273
+ } catch (InterruptedException e) {
274
+ Thread.currentThread().interrupt();
275
+ rejectBillingSetupCall(purchaseCall, setupCallRejected, "BILLING_INTERRUPTED", "Billing setup was interrupted");
276
+ throw new RuntimeException("Billing setup was interrupted", e);
277
+ }
278
+ synchronized (billingClientLock) {
279
+ closeBillingClientLocked();
280
+ }
281
+ }
282
+
283
+ try {
284
+ connectBillingClient(purchaseCall, setupCallRejected, attempt);
285
+ return;
286
+ } catch (RuntimeException e) {
287
+ lastFailure = e;
288
+ boolean willRetry = attempt < BILLING_CONNECTION_MAX_ATTEMPTS && isRetriableBillingSetupFailure(e);
289
+ Log.w(
290
+ TAG,
291
+ "Billing client connection attempt " + attempt + " failed: " + e.getMessage() + (willRetry ? " (will retry)" : "")
292
+ );
293
+ if (!willRetry) {
294
+ break;
295
+ }
296
+ }
297
+ }
298
+
299
+ String failureMessage = lastFailure != null && lastFailure.getMessage() != null ? lastFailure.getMessage() : "Billing setup failed";
300
+ String failureCode = failureMessage.contains("timed out") ? "BILLING_SETUP_TIMEOUT" : "BILLING_SETUP_FAILED";
301
+ rejectBillingSetupCall(purchaseCall, setupCallRejected, failureCode, failureMessage);
302
+ throw lastFailure != null ? lastFailure : new RuntimeException("Billing setup failed");
303
+ }
304
+
305
+ private boolean isRetriableBillingSetupFailure(RuntimeException failure) {
306
+ String message = failure.getMessage();
307
+ if (message == null) {
308
+ return true;
309
+ }
310
+ if (message.contains("timed out") || message.contains("disconnected") || message.contains("SERVICE_UNAVAILABLE")) {
311
+ return true;
312
+ }
313
+ return !message.contains("BILLING_UNAVAILABLE") && !message.contains("FEATURE_NOT_SUPPORTED");
314
+ }
315
+
316
+ private void connectBillingClient(PluginCall purchaseCall, AtomicBoolean setupCallRejected, int attempt) {
317
+ final CountDownLatch setupLatch = new CountDownLatch(1);
318
+ final BillingResult[] setupError = new BillingResult[1];
319
+ final AtomicBoolean setupSettled = new AtomicBoolean(false);
320
+
321
+ Log.d(TAG, "Creating new BillingClient (attempt " + attempt + "/" + BILLING_CONNECTION_MAX_ATTEMPTS + ")");
322
+ final BillingClient client;
323
+ synchronized (billingClientLock) {
324
+ client = BillingClient.newBuilder(getContext())
325
+ .setListener(
326
+ new PurchasesUpdatedListener() {
327
+ @Override
328
+ public void onPurchasesUpdated(@NonNull BillingResult billingResult, List<Purchase> purchases) {
329
+ Log.d(TAG, "onPurchasesUpdated() called");
330
+ Log.d(TAG, "Billing result: " + billingResult.getResponseCode() + " - " + billingResult.getDebugMessage());
331
+ Log.d(TAG, "Purchases count: " + (purchases != null ? purchases.size() : 0));
295
332
  Log.i(NativePurchasesPlugin.TAG, "onPurchasesUpdated" + billingResult);
296
- if (purchaseCall != null) {
297
- purchaseCall.reject("Purchase is not purchased");
333
+ if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchases != null) {
334
+ Log.d(TAG, "Purchase update successful, processing first purchase");
335
+ handlePurchase(purchases.get(0), purchaseCall);
336
+ } else {
337
+ Log.d(TAG, "Purchase update failed or purchases is null");
338
+ Log.i(NativePurchasesPlugin.TAG, "onPurchasesUpdated" + billingResult);
339
+ if (purchaseCall != null) {
340
+ purchaseCall.reject("Purchase is not purchased");
341
+ }
298
342
  }
343
+ closeBillingClient();
299
344
  }
300
- closeBillingClient();
301
- return;
302
345
  }
303
- }
304
- )
305
- .enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build())
306
- .build();
346
+ )
347
+ .enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build())
348
+ .build();
349
+ billingClient = client;
350
+ }
351
+
307
352
  Log.d(TAG, "Starting billing client connection");
308
- billingClient.startConnection(
353
+ client.startConnection(
309
354
  new BillingClientStateListener() {
310
355
  @Override
311
356
  public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
357
+ if (!setupSettled.compareAndSet(false, true)) {
358
+ Log.d(TAG, "Ignoring stale onBillingSetupFinished callback");
359
+ return;
360
+ }
312
361
  Log.d(TAG, "onBillingSetupFinished() called");
313
362
  Log.d(TAG, "Setup result: " + billingResult.getResponseCode() + " - " + billingResult.getDebugMessage());
314
363
  if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
315
364
  Log.d(TAG, "Billing setup successful, client is ready");
316
- // The BillingClient is ready. You can query purchases here.
317
- lastBillingError = null;
318
- semaphoreReady.countDown();
319
365
  } else {
320
366
  Log.e(TAG, "Billing setup failed with code: " + billingResult.getResponseCode());
321
367
  Log.e(TAG, "Error message: " + billingResult.getDebugMessage());
322
-
323
- // Store the error for later use
324
- lastBillingError = billingResult;
325
-
326
- // Release the latch so the waiting thread can continue
327
- semaphoreReady.countDown();
328
-
329
- // Reject the pending call if there is one
330
- if (pendingCall != null) {
331
- Log.d(TAG, "Rejecting pending call due to billing setup failure");
332
- String errorMessage = "Billing service unavailable";
333
- switch (billingResult.getResponseCode()) {
334
- case BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE:
335
- errorMessage =
336
- "Billing service unavailable. Please check your internet connection and Google Play Services.";
337
- break;
338
- case BillingClient.BillingResponseCode.BILLING_UNAVAILABLE:
339
- errorMessage = "Billing is not available on this device.";
340
- break;
341
- case BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED:
342
- errorMessage = "This billing feature is not supported.";
343
- break;
344
- case BillingClient.BillingResponseCode.SERVICE_DISCONNECTED:
345
- errorMessage = "Billing service disconnected. Please try again.";
346
- break;
347
- default:
348
- errorMessage = "Billing setup failed: " + billingResult.getDebugMessage();
349
- break;
350
- }
351
- pendingCall.reject("BILLING_SETUP_FAILED", errorMessage);
352
- pendingCall = null;
353
- }
368
+ setupError[0] = billingResult;
354
369
  }
370
+ setupLatch.countDown();
355
371
  }
356
372
 
357
373
  @Override
358
374
  public void onBillingServiceDisconnected() {
359
375
  Log.d(TAG, "onBillingServiceDisconnected() called");
360
- // Try to restart the connection on the next request to
361
- // Google Play by calling the startConnection() method.
376
+ synchronized (billingClientLock) {
377
+ if (billingClient == client) {
378
+ billingClient = null;
379
+ }
380
+ }
381
+ if (!setupSettled.compareAndSet(false, true)) {
382
+ return;
383
+ }
384
+ setupError[0] = BillingResult.newBuilder()
385
+ .setResponseCode(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
386
+ .setDebugMessage("Billing service disconnected during setup")
387
+ .build();
388
+ setupLatch.countDown();
362
389
  }
363
390
  }
364
391
  );
392
+
365
393
  try {
366
394
  Log.d(TAG, "Waiting for billing client setup to finish");
367
- boolean setupCompleted = semaphoreReady.await(10, TimeUnit.SECONDS);
395
+ boolean setupCompleted = setupLatch.await(BILLING_SETUP_TIMEOUT_SECONDS, TimeUnit.SECONDS);
368
396
 
369
397
  if (!setupCompleted) {
370
- Log.e(TAG, "Billing client setup timed out after 10 seconds");
371
- if (pendingCall != null) {
372
- pendingCall.reject("BILLING_SETUP_TIMEOUT", "Billing client initialization timed out");
373
- pendingCall = null;
398
+ setupSettled.compareAndSet(false, true);
399
+ Log.e(TAG, "Billing client setup timed out after " + BILLING_SETUP_TIMEOUT_SECONDS + " seconds");
400
+ synchronized (billingClientLock) {
401
+ closeBillingClientLocked();
374
402
  }
375
- closeBillingClient();
376
403
  throw new RuntimeException("Billing setup timed out");
377
404
  }
378
405
 
379
406
  Log.d(TAG, "Billing client setup wait completed");
380
407
 
381
- // Check if billing setup failed
382
- if (lastBillingError != null) {
408
+ if (setupError[0] != null) {
383
409
  Log.e(TAG, "Billing setup failed, throwing exception");
384
- throw new RuntimeException("Billing setup failed: " + lastBillingError.getDebugMessage());
410
+ synchronized (billingClientLock) {
411
+ closeBillingClientLocked();
412
+ }
413
+ throw new RuntimeException(getBillingSetupErrorMessage(setupError[0]));
385
414
  }
386
415
 
387
416
  Log.d(TAG, "Billing client setup completed successfully");
388
417
  } catch (InterruptedException e) {
418
+ Thread.currentThread().interrupt();
419
+ setupSettled.compareAndSet(false, true);
389
420
  Log.e(TAG, "InterruptedException while waiting for billing setup: " + e.getMessage());
390
- e.printStackTrace();
391
- if (pendingCall != null) {
392
- pendingCall.reject("BILLING_INTERRUPTED", "Billing setup was interrupted");
393
- pendingCall = null;
421
+ rejectBillingSetupCall(purchaseCall, setupCallRejected, "BILLING_INTERRUPTED", "Billing setup was interrupted");
422
+ synchronized (billingClientLock) {
423
+ closeBillingClientLocked();
394
424
  }
395
- } catch (RuntimeException e) {
396
- Log.e(TAG, "RuntimeException during billing setup: " + e.getMessage());
397
- // Don't reject here - already rejected in onBillingSetupFinished
398
- throw e;
425
+ throw new RuntimeException("Billing setup was interrupted", e);
399
426
  }
400
427
  }
401
428
 
@@ -21,7 +21,7 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
21
21
  CAPPluginMethod(name: "isEntitledToOldBusinessModel", returnType: CAPPluginReturnPromise)
22
22
  ]
23
23
 
24
- private let pluginVersion: String = "8.4.3"
24
+ private let pluginVersion: String = "8.4.5"
25
25
  private var transactionUpdatesTask: Task<Void, Never>?
26
26
 
27
27
  @objc func getPluginVersion(_ call: CAPPluginCall) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/native-purchases",
3
- "version": "8.4.3",
3
+ "version": "8.4.5",
4
4
  "description": "In-app Subscriptions Made Easy",
5
5
  "main": "dist/plugin.cjs.js",
6
6
  "module": "dist/esm/index.js",