@capgo/native-purchases 8.10.0 → 8.11.1
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.
- package/README.md +50 -5
- package/android/build.gradle +1 -1
- package/android/src/main/java/ee/forgr/nativepurchases/NativePurchasesPlugin.java +113 -19
- package/android/src/main/java/ee/forgr/nativepurchases/SubscriptionOfferSelector.java +15 -0
- package/android/src/main/java/ee/forgr/nativepurchases/SubscriptionReplacementModes.java +69 -0
- package/dist/docs.json +75 -4
- package/dist/esm/definitions.d.ts +74 -0
- package/dist/esm/definitions.js.map +1 -1
- package/dist/esm/web.d.ts +7 -1
- package/dist/esm/web.js +4 -0
- package/dist/esm/web.js.map +1 -1
- package/dist/plugin.cjs.js +4 -0
- package/dist/plugin.cjs.js.map +1 -1
- package/dist/plugin.js +4 -0
- package/dist/plugin.js.map +1 -1
- package/ios/Sources/NativePurchasesPlugin/NativePurchasesPlugin.swift +9 -2
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -33,7 +33,7 @@ We build, improve and fix our plugins with heavy use of AI, so issues usually ge
|
|
|
33
33
|
- **Products**: `getProducts()` and `getProduct()` return localized prices and details.
|
|
34
34
|
- **Purchases**: `purchaseProduct()` for consumables, non-consumables and subscriptions, with `acknowledgePurchase()`, plus `consumePurchase()` on Android.
|
|
35
35
|
- **Restore and history**: `restorePurchases()` and `getPurchases()`.
|
|
36
|
-
- **Subscription tools**: `manageSubscriptions()`, `presentOfferCodeRedeemSheet()` and `getStorefront()`.
|
|
36
|
+
- **Subscription tools**: `manageSubscriptions()`, `presentOfferCodeRedeemSheet()` and `getStorefront()`, plus Android subscription upgrade/downgrade via `purchaseProduct({ oldPurchaseToken, oldProductIdentifier, replacementMode })`.
|
|
37
37
|
- **Server validation**: receipt data, purchase tokens, and the `transactionUpdated` event on iOS and Android (`transactionVerificationFailed` is iOS only).
|
|
38
38
|
- **Platforms**: iOS and Android. Web mocks the purchase calls for development, except `consumePurchase()`, which is Android only.
|
|
39
39
|
|
|
@@ -717,6 +717,10 @@ const checkBillingSupport = async () => {
|
|
|
717
717
|
};
|
|
718
718
|
```
|
|
719
719
|
|
|
720
|
+
### Upgrade or downgrade a subscription (Android)
|
|
721
|
+
|
|
722
|
+
Replace an active Google Play subscription in-app instead of opening Play subscription settings. Pass the current `purchaseToken` from `getPurchases()`, the product being replaced, and a `replacementMode` name (`CHARGE_PRORATED_PRICE` for upgrades, `DEFERRED` for downgrades). Call `isSubscriptionReplacementSupported()` first so older native builds are not treated as supporting replacement. On iOS, purchase the other product in the same subscription group; StoreKit handles the change.
|
|
723
|
+
|
|
720
724
|
### Manage Subscriptions
|
|
721
725
|
|
|
722
726
|
Allow users to manage their subscriptions directly from your app. This opens the platform's native subscription management page:
|
|
@@ -1857,6 +1861,7 @@ With `autoFinishTransactions: true` (the default), call `restorePurchases()` at
|
|
|
1857
1861
|
* [`getAppTransaction()`](#getapptransaction)
|
|
1858
1862
|
* [`isEntitledToOldBusinessModel(...)`](#isentitledtooldbusinessmodel)
|
|
1859
1863
|
* [`purchaseProduct(...)`](#purchaseproduct)
|
|
1864
|
+
* [`isSubscriptionReplacementSupported()`](#issubscriptionreplacementsupported)
|
|
1860
1865
|
* [`getProducts(...)`](#getproducts)
|
|
1861
1866
|
* [`getProduct(...)`](#getproduct)
|
|
1862
1867
|
* [`isBillingSupported()`](#isbillingsupported)
|
|
@@ -1989,11 +1994,16 @@ to determine if they should be grandfathered into free features.
|
|
|
1989
1994
|
### purchaseProduct(...)
|
|
1990
1995
|
|
|
1991
1996
|
```typescript
|
|
1992
|
-
purchaseProduct(options: { productIdentifier: string; planIdentifier?: string; offerToken?: string; productType?: PURCHASE_TYPE; quantity?: number; billingPlanType?: 'monthly' | 'upFront'; appAccountToken?: string; isConsumable?: boolean; autoAcknowledgePurchases?: boolean; }) => Promise<Transaction>
|
|
1997
|
+
purchaseProduct(options: { productIdentifier: string; planIdentifier?: string; offerToken?: string; productType?: PURCHASE_TYPE; quantity?: number; billingPlanType?: 'monthly' | 'upFront'; appAccountToken?: string; isConsumable?: boolean; autoAcknowledgePurchases?: boolean; oldPurchaseToken?: string; oldProductIdentifier?: string; replacementMode?: SubscriptionReplacementMode; }) => Promise<Transaction>
|
|
1993
1998
|
```
|
|
1994
1999
|
|
|
1995
2000
|
Started purchase process for the given product.
|
|
1996
2001
|
|
|
2002
|
+
**Upgrade / downgrade a subscription (Android):** pass `oldPurchaseToken`, `oldProductIdentifier` and
|
|
2003
|
+
`replacementMode` together, with `productType` set to <a href="#purchase_type">PURCHASE_TYPE.SUBS</a>. Partial replacement options are rejected,
|
|
2004
|
+
and a `planIdentifier` that matches no base plan is rejected too (no first-offer fallback).
|
|
2005
|
+
On iOS, purchase the other product of the same subscription group instead (StoreKit handles the change).
|
|
2006
|
+
|
|
1997
2007
|
On Android, `offerToken` selects which offer is charged. If the token is
|
|
1998
2008
|
missing from the product details returned by the plugin's query, the plugin
|
|
1999
2009
|
rejects the purchase instead of selecting another offer. Other failures can
|
|
@@ -2024,15 +2034,34 @@ purchase option is marked backward-compatible, which is the first
|
|
|
2024
2034
|
option does the first offer in the list get used. So pass the token
|
|
2025
2035
|
whenever a specific one-time offer matters.
|
|
2026
2036
|
|
|
2027
|
-
| Param | Type
|
|
2028
|
-
| ------------- |
|
|
2029
|
-
| **`options`** | <code>{ productIdentifier: string; planIdentifier?: string; offerToken?: string; productType?: <a href="#purchase_type">PURCHASE_TYPE</a>; quantity?: number; billingPlanType?: 'upFront' \| 'monthly'; appAccountToken?: string; isConsumable?: boolean; autoAcknowledgePurchases?: boolean; }</code> | - The product to purchase |
|
|
2037
|
+
| Param | Type | Description |
|
|
2038
|
+
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |
|
|
2039
|
+
| **`options`** | <code>{ productIdentifier: string; planIdentifier?: string; offerToken?: string; productType?: <a href="#purchase_type">PURCHASE_TYPE</a>; quantity?: number; billingPlanType?: 'upFront' \| 'monthly'; appAccountToken?: string; isConsumable?: boolean; autoAcknowledgePurchases?: boolean; oldPurchaseToken?: string; oldProductIdentifier?: string; replacementMode?: <a href="#subscriptionreplacementmode">SubscriptionReplacementMode</a>; }</code> | - The product to purchase |
|
|
2030
2040
|
|
|
2031
2041
|
**Returns:** <code>Promise<<a href="#transaction">Transaction</a>></code>
|
|
2032
2042
|
|
|
2033
2043
|
--------------------
|
|
2034
2044
|
|
|
2035
2045
|
|
|
2046
|
+
### isSubscriptionReplacementSupported()
|
|
2047
|
+
|
|
2048
|
+
```typescript
|
|
2049
|
+
isSubscriptionReplacementSupported() => Promise<{ supported: boolean; }>
|
|
2050
|
+
```
|
|
2051
|
+
|
|
2052
|
+
Whether this native build can replace a subscription (`oldPurchaseToken` / `replacementMode` in `purchaseProduct()`).
|
|
2053
|
+
|
|
2054
|
+
Use it before an upgrade / downgrade: a native build without this feature ignores the replacement options,
|
|
2055
|
+
so the purchase would become a second subscription instead of replacing the current one.
|
|
2056
|
+
On native builds that predate this method the call rejects (not implemented): treat a rejection as not supported.
|
|
2057
|
+
|
|
2058
|
+
**Returns:** <code>Promise<{ supported: boolean; }></code>
|
|
2059
|
+
|
|
2060
|
+
**Since:** 8.10.0
|
|
2061
|
+
|
|
2062
|
+
--------------------
|
|
2063
|
+
|
|
2064
|
+
|
|
2036
2065
|
### getProducts(...)
|
|
2037
2066
|
|
|
2038
2067
|
```typescript
|
|
@@ -2594,6 +2623,22 @@ Android one-time product discount display metadata.
|
|
|
2594
2623
|
<code>'upFront' | 'monthly' | 'unknown'</code>
|
|
2595
2624
|
|
|
2596
2625
|
|
|
2626
|
+
#### SubscriptionReplacementMode
|
|
2627
|
+
|
|
2628
|
+
How Google Play replaces an active subscription when `purchaseProduct()` is called with `oldPurchaseToken`
|
|
2629
|
+
(Android only). Passed by name and mapped natively to Play Billing's item-level `ReplacementMode` constants.
|
|
2630
|
+
Do not pass numeric `PRORATION_MODE` values; use these names.
|
|
2631
|
+
|
|
2632
|
+
- `WITH_TIME_PRORATION`: replace now; the remaining time is credited by moving the next billing date.
|
|
2633
|
+
- `CHARGE_PRORATED_PRICE`: replace now and charge the price difference for the rest of the current period
|
|
2634
|
+
(upgrades only, where the price per unit of time increases).
|
|
2635
|
+
- `WITHOUT_PRORATION`: replace now; the new price is charged at the next renewal.
|
|
2636
|
+
- `CHARGE_FULL_PRICE`: replace now and charge the full price of the new plan.
|
|
2637
|
+
- `DEFERRED`: replace at the next renewal.
|
|
2638
|
+
|
|
2639
|
+
<code>'WITH_TIME_PRORATION' | 'CHARGE_PRORATED_PRICE' | 'WITHOUT_PRORATION' | 'CHARGE_FULL_PRICE' | 'DEFERRED'</code>
|
|
2640
|
+
|
|
2641
|
+
|
|
2597
2642
|
### Enums
|
|
2598
2643
|
|
|
2599
2644
|
|
package/android/build.gradle
CHANGED
|
@@ -58,7 +58,7 @@ dependencies {
|
|
|
58
58
|
implementation project(':capacitor-android')
|
|
59
59
|
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
|
|
60
60
|
testImplementation "junit:junit:$junitVersion"
|
|
61
|
-
testImplementation 'org.mockito:mockito-core:5.
|
|
61
|
+
testImplementation 'org.mockito:mockito-core:5.25.0'
|
|
62
62
|
// Real org.json for JVM unit tests, so tests can build and read JSObject payloads.
|
|
63
63
|
testImplementation 'org.json:json:20240303'
|
|
64
64
|
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
|
|
@@ -111,7 +111,7 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
111
111
|
return SubscriptionOfferPurchaseResult.ok(selected.getOfferToken(), selected.getBasePlanId());
|
|
112
112
|
}
|
|
113
113
|
|
|
114
|
-
private final String pluginVersion = "8.
|
|
114
|
+
private final String pluginVersion = "8.11.1";
|
|
115
115
|
public static final String TAG = "NativePurchases";
|
|
116
116
|
private static final int BILLING_CONNECTION_MAX_ATTEMPTS = 2;
|
|
117
117
|
private static final long BILLING_SETUP_TIMEOUT_SECONDS = 5;
|
|
@@ -157,7 +157,8 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
157
157
|
/** Billing client kept open while JS listens for {@link #TRANSACTION_UPDATED_EVENT}. */
|
|
158
158
|
private BillingClient updatesBillingClient;
|
|
159
159
|
private final Object updatesClientLock = new Object();
|
|
160
|
-
private final
|
|
160
|
+
private static final String ACTIVE_FLOW_REGISTERED_PRODUCT_IDS = "nativePurchasesActiveFlowRegisteredProductIds";
|
|
161
|
+
private final Map<String, Integer> activePurchaseFlowProductIdRefCounts = new ConcurrentHashMap<>();
|
|
161
162
|
private final AtomicInteger updatesClientPendingAcknowledgements = new AtomicInteger(0);
|
|
162
163
|
private volatile boolean disconnectUpdatesClientWhenIdle;
|
|
163
164
|
|
|
@@ -345,35 +346,65 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
345
346
|
}
|
|
346
347
|
String productId = purchase.getProducts().get(0);
|
|
347
348
|
synchronized (billingClientLock) {
|
|
348
|
-
|
|
349
|
+
Integer refCount = activePurchaseFlowProductIdRefCounts.get(productId);
|
|
350
|
+
return refCount != null && refCount > 0;
|
|
349
351
|
}
|
|
350
352
|
}
|
|
351
353
|
|
|
352
|
-
private void registerActivePurchaseFlowProduct(String productIdentifier) {
|
|
353
|
-
if (productIdentifier == null || productIdentifier.isEmpty()) {
|
|
354
|
+
private void registerActivePurchaseFlowProduct(PluginCall call, String productIdentifier) {
|
|
355
|
+
if (call == null || productIdentifier == null || productIdentifier.isEmpty()) {
|
|
354
356
|
return;
|
|
355
357
|
}
|
|
356
358
|
synchronized (billingClientLock) {
|
|
357
|
-
|
|
359
|
+
activePurchaseFlowProductIdRefCounts.merge(productIdentifier, 1, Integer::sum);
|
|
358
360
|
}
|
|
361
|
+
appendActiveFlowRegisteredProductId(call, productIdentifier);
|
|
359
362
|
}
|
|
360
363
|
|
|
361
|
-
private void
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
}
|
|
368
|
-
}
|
|
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);
|
|
369
370
|
}
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
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;
|
|
374
387
|
}
|
|
388
|
+
activePurchaseFlowProductIdRefCounts.compute(productId, (id, count) -> {
|
|
389
|
+
if (count == null || count <= 1) {
|
|
390
|
+
return null;
|
|
391
|
+
}
|
|
392
|
+
return count - 1;
|
|
393
|
+
});
|
|
375
394
|
}
|
|
376
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
|
+
}
|
|
377
408
|
}
|
|
378
409
|
|
|
379
410
|
private void maybeRefreshTransactionUpdatesAfterPurchaseFlow() {
|
|
@@ -411,6 +442,15 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
411
442
|
return purchaseData;
|
|
412
443
|
}
|
|
413
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
|
+
|
|
414
454
|
@PluginMethod
|
|
415
455
|
public void isBillingSupported(PluginCall call) {
|
|
416
456
|
NativePurchasesLog.d(TAG, "isBillingSupported() called");
|
|
@@ -1069,7 +1109,12 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
1069
1109
|
* not the shared {@link #billingClient} field.
|
|
1070
1110
|
*/
|
|
1071
1111
|
void launchPurchaseBillingFlow(BillingClient flowClient, PluginCall call, BillingFlowParams billingFlowParams) {
|
|
1072
|
-
registerActivePurchaseFlowProduct(call.getString("productIdentifier"));
|
|
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
|
+
}
|
|
1073
1118
|
if (flowClient == null || !flowClient.isReady()) {
|
|
1074
1119
|
NativePurchasesLog.w(TAG, "Purchase billing client closed before launch");
|
|
1075
1120
|
abortPurchaseClientFlow(
|
|
@@ -1641,6 +1686,14 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
1641
1686
|
final String accountIdentifier = appAccountToken != null && !appAccountToken.isEmpty() ? appAccountToken : null;
|
|
1642
1687
|
boolean isConsumable = call.getBoolean("isConsumable", false);
|
|
1643
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;
|
|
1644
1697
|
|
|
1645
1698
|
NativePurchasesLog.d(TAG, "Product identifier: " + productIdentifier);
|
|
1646
1699
|
NativePurchasesLog.d(TAG, "Plan identifier: " + planIdentifier);
|
|
@@ -1650,6 +1703,7 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
1650
1703
|
NativePurchasesLog.d(TAG, "Account identifier provided: " + (accountIdentifier != null ? "[REDACTED]" : "none"));
|
|
1651
1704
|
NativePurchasesLog.d(TAG, "Is consumable: " + isConsumable);
|
|
1652
1705
|
NativePurchasesLog.d(TAG, "Auto-acknowledge purchases: " + autoAcknowledgePurchases);
|
|
1706
|
+
NativePurchasesLog.d(TAG, "Subscription replacement: " + isReplacement);
|
|
1653
1707
|
|
|
1654
1708
|
// cannot use quantity, because it's done in native modal
|
|
1655
1709
|
NativePurchasesLog.d("CapacitorPurchases", "purchaseProduct: " + productIdentifier);
|
|
@@ -1685,6 +1739,16 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
1685
1739
|
NativePurchasesLog.d(TAG, "isConsumable is not supported for subscriptions, ignoring flag");
|
|
1686
1740
|
isConsumable = false;
|
|
1687
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
|
+
}
|
|
1688
1752
|
|
|
1689
1753
|
call.getData().put("isConsumable", isConsumable);
|
|
1690
1754
|
call.getData().put("autoAcknowledgePurchases", autoAcknowledgePurchases);
|
|
@@ -1780,6 +1844,23 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
1780
1844
|
rejectOfferTokenNotFoundForPurchase(call, productIdentifier, purchaseClient);
|
|
1781
1845
|
return;
|
|
1782
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
|
+
}
|
|
1783
1864
|
|
|
1784
1865
|
NativePurchasesLog.d(TAG, "Selected base plan: " + subscriptionSelection.basePlanId);
|
|
1785
1866
|
productDetailsParams.setOfferToken(subscriptionSelection.offerToken);
|
|
@@ -1787,6 +1868,14 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
1787
1868
|
TAG,
|
|
1788
1869
|
"Set offer token: " + NativePurchasesLog.redactSensitive(subscriptionSelection.offerToken)
|
|
1789
1870
|
);
|
|
1871
|
+
if (isReplacement) {
|
|
1872
|
+
productDetailsParams.setSubscriptionProductReplacementParams(
|
|
1873
|
+
BillingFlowParams.ProductDetailsParams.SubscriptionProductReplacementParams.newBuilder()
|
|
1874
|
+
.setOldProductId(oldProductIdentifier)
|
|
1875
|
+
.setReplacementMode(replacementMode)
|
|
1876
|
+
.build()
|
|
1877
|
+
);
|
|
1878
|
+
}
|
|
1790
1879
|
} else if (productType.equals("inapp")) {
|
|
1791
1880
|
NativePurchasesLog.d(TAG, "Processing in-app product");
|
|
1792
1881
|
List<ProductDetails.OneTimePurchaseOfferDetails> oneTimeOffers =
|
|
@@ -1825,6 +1914,11 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
1825
1914
|
if (accountIdentifier != null && !accountIdentifier.isEmpty()) {
|
|
1826
1915
|
billingFlowBuilder.setObfuscatedAccountId(accountIdentifier);
|
|
1827
1916
|
}
|
|
1917
|
+
if (isReplacement) {
|
|
1918
|
+
billingFlowBuilder.setSubscriptionUpdateParams(
|
|
1919
|
+
BillingFlowParams.SubscriptionUpdateParams.newBuilder().setOldPurchaseToken(oldPurchaseToken).build()
|
|
1920
|
+
);
|
|
1921
|
+
}
|
|
1828
1922
|
BillingFlowParams billingFlowParams = billingFlowBuilder.build();
|
|
1829
1923
|
NativePurchasesLog.d(TAG, "Launching billing flow");
|
|
1830
1924
|
launchPurchaseBillingFlowOnUiThread(purchaseClient, call, billingFlowParams);
|
|
@@ -99,6 +99,21 @@ public final class SubscriptionOfferSelector {
|
|
|
99
99
|
return isPresent(offerToken) || isPresent(planIdentifier);
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
+
/**
|
|
103
|
+
* Whether any offer uses the given base plan id.
|
|
104
|
+
*/
|
|
105
|
+
static boolean hasBasePlan(List<Offer> offers, String planIdentifier) {
|
|
106
|
+
if (!isPresent(planIdentifier) || offers == null || offers.isEmpty()) {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
for (Offer offer : offers) {
|
|
110
|
+
if (planIdentifier.equals(offer.getBasePlanId())) {
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
|
|
102
117
|
private static boolean isPresent(String value) {
|
|
103
118
|
return value != null && !value.isEmpty();
|
|
104
119
|
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
package ee.forgr.nativepurchases;
|
|
2
|
+
|
|
3
|
+
import com.android.billingclient.api.BillingFlowParams;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Maps the replacement mode name passed from JavaScript to Play Billing's item-level constant
|
|
7
|
+
* ({@code BillingFlowParams.ProductDetailsParams.SubscriptionProductReplacementParams.ReplacementMode}).
|
|
8
|
+
*
|
|
9
|
+
* <p>The name is mapped here instead of accepting a number because Play Billing exposes two tables with
|
|
10
|
+
* different values: {@code DEFERRED} is 5 in the item-level table and 6 in
|
|
11
|
+
* {@code SubscriptionUpdateParams.ReplacementMode}, and the exported JS {@code PRORATION_MODE} enum still uses
|
|
12
|
+
* the older ProrationMode numbering (4).
|
|
13
|
+
*/
|
|
14
|
+
final class SubscriptionReplacementModes {
|
|
15
|
+
|
|
16
|
+
/** Returned for a missing or unsupported name. Callers must reject the purchase instead of guessing. */
|
|
17
|
+
static final int UNKNOWN = 0;
|
|
18
|
+
|
|
19
|
+
private SubscriptionReplacementModes() {}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Returns {@code null} when the replacement options are consistent, otherwise the message to reject the call with.
|
|
23
|
+
*
|
|
24
|
+
* <p>A partial request ({@code oldProductIdentifier} or {@code replacementMode} without {@code oldPurchaseToken}) is
|
|
25
|
+
* rejected instead of being treated as a normal purchase, which would create a second subscription.
|
|
26
|
+
*/
|
|
27
|
+
static String validationError(String productType, String oldPurchaseToken, String oldProductIdentifier, String replacementModeName) {
|
|
28
|
+
boolean hasToken = isSet(oldPurchaseToken);
|
|
29
|
+
if (!hasToken) {
|
|
30
|
+
return isSet(oldProductIdentifier) || isSet(replacementModeName)
|
|
31
|
+
? "oldPurchaseToken is required when oldProductIdentifier or replacementMode is set"
|
|
32
|
+
: null;
|
|
33
|
+
}
|
|
34
|
+
if (!"subs".equals(productType)) {
|
|
35
|
+
return "oldPurchaseToken is only supported for subscriptions";
|
|
36
|
+
}
|
|
37
|
+
if (!isSet(oldProductIdentifier)) {
|
|
38
|
+
return "oldProductIdentifier cannot be empty when oldPurchaseToken is set";
|
|
39
|
+
}
|
|
40
|
+
if (fromName(replacementModeName) == UNKNOWN) {
|
|
41
|
+
return "Unknown replacementMode: " + replacementModeName;
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
private static boolean isSet(String value) {
|
|
47
|
+
return value != null && !value.isEmpty();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
static int fromName(String name) {
|
|
51
|
+
if (name == null) {
|
|
52
|
+
return UNKNOWN;
|
|
53
|
+
}
|
|
54
|
+
switch (name) {
|
|
55
|
+
case "WITH_TIME_PRORATION":
|
|
56
|
+
return BillingFlowParams.ProductDetailsParams.SubscriptionProductReplacementParams.ReplacementMode.WITH_TIME_PRORATION;
|
|
57
|
+
case "CHARGE_PRORATED_PRICE":
|
|
58
|
+
return BillingFlowParams.ProductDetailsParams.SubscriptionProductReplacementParams.ReplacementMode.CHARGE_PRORATED_PRICE;
|
|
59
|
+
case "WITHOUT_PRORATION":
|
|
60
|
+
return BillingFlowParams.ProductDetailsParams.SubscriptionProductReplacementParams.ReplacementMode.WITHOUT_PRORATION;
|
|
61
|
+
case "CHARGE_FULL_PRICE":
|
|
62
|
+
return BillingFlowParams.ProductDetailsParams.SubscriptionProductReplacementParams.ReplacementMode.CHARGE_FULL_PRICE;
|
|
63
|
+
case "DEFERRED":
|
|
64
|
+
return BillingFlowParams.ProductDetailsParams.SubscriptionProductReplacementParams.ReplacementMode.DEFERRED;
|
|
65
|
+
default:
|
|
66
|
+
return UNKNOWN;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
package/dist/docs.json
CHANGED
|
@@ -124,12 +124,12 @@
|
|
|
124
124
|
},
|
|
125
125
|
{
|
|
126
126
|
"name": "purchaseProduct",
|
|
127
|
-
"signature": "(options: { productIdentifier: string; planIdentifier?: string; offerToken?: string; productType?: PURCHASE_TYPE; quantity?: number; billingPlanType?: 'monthly' | 'upFront'; appAccountToken?: string; isConsumable?: boolean; autoAcknowledgePurchases?: boolean; }) => Promise<Transaction>",
|
|
127
|
+
"signature": "(options: { productIdentifier: string; planIdentifier?: string; offerToken?: string; productType?: PURCHASE_TYPE; quantity?: number; billingPlanType?: 'monthly' | 'upFront'; appAccountToken?: string; isConsumable?: boolean; autoAcknowledgePurchases?: boolean; oldPurchaseToken?: string; oldProductIdentifier?: string; replacementMode?: SubscriptionReplacementMode; }) => Promise<Transaction>",
|
|
128
128
|
"parameters": [
|
|
129
129
|
{
|
|
130
130
|
"name": "options",
|
|
131
131
|
"docs": "- The product to purchase",
|
|
132
|
-
"type": "{ productIdentifier: string; planIdentifier?: string | undefined; offerToken?: string | undefined; productType?: PURCHASE_TYPE | undefined; quantity?: number | undefined; billingPlanType?: 'upFront' | 'monthly' | undefined; appAccountToken?: string | undefined; isConsumable?: boolean | undefined; autoAcknowledgePurchases?: boolean | undefined; }"
|
|
132
|
+
"type": "{ productIdentifier: string; planIdentifier?: string | undefined; offerToken?: string | undefined; productType?: PURCHASE_TYPE | undefined; quantity?: number | undefined; billingPlanType?: 'upFront' | 'monthly' | undefined; appAccountToken?: string | undefined; isConsumable?: boolean | undefined; autoAcknowledgePurchases?: boolean | undefined; oldPurchaseToken?: string | undefined; oldProductIdentifier?: string | undefined; replacementMode?: SubscriptionReplacementMode | undefined; }"
|
|
133
133
|
}
|
|
134
134
|
],
|
|
135
135
|
"returns": "Promise<Transaction>",
|
|
@@ -173,15 +173,59 @@
|
|
|
173
173
|
{
|
|
174
174
|
"name": "param",
|
|
175
175
|
"text": "options.autoAcknowledgePurchases - When false, this purchase is not auto-finished/acknowledged when\n `autoFinishTransactions` is also true. Does not disable auto-finishing on\n the iOS `transactionUpdated` listener; use `configure({ autoFinishTransactions: false })`\n for manual finishing across purchase and recovery flows. Defaults to true.\n - **Android**: Must acknowledge within 3 days or Google Play will refund\n - **iOS**: Unfinished transactions remain in the queue and may block future purchases"
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
"name": "param",
|
|
179
|
+
"text": "options.oldPurchaseToken - Only Android, the purchase token of the active subscription to replace (upgrade / downgrade).\n When set, `oldProductIdentifier` and `replacementMode` are required and `productType` must be `subs`.\n On iOS, purchasing another product of the same subscription group is already the upgrade / downgrade.\n Call `isSubscriptionReplacementSupported()` first: older native builds ignore this option, which would\n create a second subscription instead of replacing the first one."
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
"name": "param",
|
|
183
|
+
"text": "options.oldProductIdentifier - Only Android, the product identifier of the subscription being replaced."
|
|
184
|
+
},
|
|
185
|
+
{
|
|
186
|
+
"name": "param",
|
|
187
|
+
"text": "options.replacementMode - Only Android, how Google Play replaces the old subscription (see `SubscriptionReplacementMode`).\n Google recommends `CHARGE_PRORATED_PRICE` for upgrades and `DEFERRED` for downgrades between different subscription products.\n When `oldProductIdentifier` equals `productIdentifier` (a base plan change within the same subscription),\n use `CHARGE_FULL_PRICE` or `WITHOUT_PRORATION` for auto-renewing base plans.\n For prepaid destination base plans, use `CHARGE_FULL_PRICE` only; `WITHOUT_PRORATION` and other modes fail on Play.\n Play rejects an installment base plan changing to a non-installment base plan within the same product regardless of mode."
|
|
176
188
|
}
|
|
177
189
|
],
|
|
178
|
-
"docs": "Started purchase process for the given product.\n\nOn Android, `offerToken` selects which offer is charged. If the token is\nmissing from the product details returned by the plugin's query, the plugin\nrejects the purchase instead of selecting another offer. Other failures can\nalso reject the purchase. Google Play may still show a different checkout,\nfor example if the offer stops being eligible after the query, so the final\nprice is not guaranteed.\nOffer tokens come from a specific product query and go stale, so read\none from the same `getProducts()` / `getProduct()` call you purchase\nfrom.\n\nFor a **subscription** (`productType: 'subs'`) the order is: an explicit\n`offerToken`, then the first offer whose base plan matches\n`planIdentifier`, then the first offer the store returned.\n`planIdentifier` is the **base plan id**, which `getProducts()` reports\nas `Product.identifier`, not `Product.planIdentifier`, which holds the\nPlay product id. It is required unless an `offerToken` is given, since\na token already identifies one offer on its own.\n\nFor a **one-time product** (`productType: 'inapp'`) there is no base\nplan, so `planIdentifier` plays no part, and an `offerToken` selects one\nof the product's purchase offers. Without a token no offer token is set\nat all whenever the product still has a backward-compatible purchase\noption, which leaves the choice to Play: it charges whichever buy\npurchase option is marked backward-compatible, which is the first\n*created* one by default and another only if one was marked\n`legacyCompatible`. Either way it need not be the first offer\n`getProducts()` returned. Only for a product with no backward-compatible\noption does the first offer in the list get used. So pass the token\nwhenever a specific one-time offer matters.",
|
|
190
|
+
"docs": "Started purchase process for the given product.\n\n**Upgrade / downgrade a subscription (Android):** pass `oldPurchaseToken`, `oldProductIdentifier` and\n`replacementMode` together, with `productType` set to PURCHASE_TYPE.SUBS. Partial replacement options are rejected,\nand a `planIdentifier` that matches no base plan is rejected too (no first-offer fallback).\nOn iOS, purchase the other product of the same subscription group instead (StoreKit handles the change).\n\nOn Android, `offerToken` selects which offer is charged. If the token is\nmissing from the product details returned by the plugin's query, the plugin\nrejects the purchase instead of selecting another offer. Other failures can\nalso reject the purchase. Google Play may still show a different checkout,\nfor example if the offer stops being eligible after the query, so the final\nprice is not guaranteed.\nOffer tokens come from a specific product query and go stale, so read\none from the same `getProducts()` / `getProduct()` call you purchase\nfrom.\n\nFor a **subscription** (`productType: 'subs'`) the order is: an explicit\n`offerToken`, then the first offer whose base plan matches\n`planIdentifier`, then the first offer the store returned.\n`planIdentifier` is the **base plan id**, which `getProducts()` reports\nas `Product.identifier`, not `Product.planIdentifier`, which holds the\nPlay product id. It is required unless an `offerToken` is given, since\na token already identifies one offer on its own.\n\nFor a **one-time product** (`productType: 'inapp'`) there is no base\nplan, so `planIdentifier` plays no part, and an `offerToken` selects one\nof the product's purchase offers. Without a token no offer token is set\nat all whenever the product still has a backward-compatible purchase\noption, which leaves the choice to Play: it charges whichever buy\npurchase option is marked backward-compatible, which is the first\n*created* one by default and another only if one was marked\n`legacyCompatible`. Either way it need not be the first offer\n`getProducts()` returned. Only for a product with no backward-compatible\noption does the first offer in the list get used. So pass the token\nwhenever a specific one-time offer matters.",
|
|
179
191
|
"complexTypes": [
|
|
180
192
|
"Transaction",
|
|
181
|
-
"PURCHASE_TYPE"
|
|
193
|
+
"PURCHASE_TYPE",
|
|
194
|
+
"SubscriptionReplacementMode"
|
|
182
195
|
],
|
|
183
196
|
"slug": "purchaseproduct"
|
|
184
197
|
},
|
|
198
|
+
{
|
|
199
|
+
"name": "isSubscriptionReplacementSupported",
|
|
200
|
+
"signature": "() => Promise<{ supported: boolean; }>",
|
|
201
|
+
"parameters": [],
|
|
202
|
+
"returns": "Promise<{ supported: boolean; }>",
|
|
203
|
+
"tags": [
|
|
204
|
+
{
|
|
205
|
+
"name": "returns",
|
|
206
|
+
"text": "`supported: true` on Android builds that support replacement; `false` on iOS (StoreKit replaces\nwithin a subscription group automatically) and on web."
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
"name": "since",
|
|
210
|
+
"text": "8.10.0"
|
|
211
|
+
},
|
|
212
|
+
{
|
|
213
|
+
"name": "platform",
|
|
214
|
+
"text": "android Returns true"
|
|
215
|
+
},
|
|
216
|
+
{
|
|
217
|
+
"name": "platform",
|
|
218
|
+
"text": "ios Returns false (not needed)"
|
|
219
|
+
},
|
|
220
|
+
{
|
|
221
|
+
"name": "example",
|
|
222
|
+
"text": "```typescript\n// Android. On iOS, purchase the other product of the same subscription group instead.\nlet supported = false;\ntry {\n ({ supported } = await NativePurchases.isSubscriptionReplacementSupported());\n} catch {\n // The native build predates this method: treat it as not supported.\n}\nconst { purchases } = await NativePurchases.getPurchases({ productType: PURCHASE_TYPE.SUBS });\nconst current = purchases.find((p) => p.productIdentifier === 'basic');\nif (supported && current?.purchaseToken) {\n await NativePurchases.purchaseProduct({\n productIdentifier: 'premium',\n planIdentifier: 'monthly',\n productType: PURCHASE_TYPE.SUBS,\n oldPurchaseToken: current.purchaseToken,\n oldProductIdentifier: current.productIdentifier,\n replacementMode: 'CHARGE_PRORATED_PRICE',\n });\n}\n```"
|
|
223
|
+
}
|
|
224
|
+
],
|
|
225
|
+
"docs": "Whether this native build can replace a subscription (`oldPurchaseToken` / `replacementMode` in `purchaseProduct()`).\n\nUse it before an upgrade / downgrade: a native build without this feature ignores the replacement options,\nso the purchase would become a second subscription instead of replacing the current one.\nOn native builds that predate this method the call rejects (not implemented): treat a rejection as not supported.",
|
|
226
|
+
"complexTypes": [],
|
|
227
|
+
"slug": "issubscriptionreplacementsupported"
|
|
228
|
+
},
|
|
185
229
|
{
|
|
186
230
|
"name": "getProducts",
|
|
187
231
|
"signature": "(options: { productIdentifiers: string[]; productType?: PURCHASE_TYPE; }) => Promise<{ products: Product[]; }>",
|
|
@@ -2270,6 +2314,33 @@
|
|
|
2270
2314
|
"complexTypes": []
|
|
2271
2315
|
}
|
|
2272
2316
|
]
|
|
2317
|
+
},
|
|
2318
|
+
{
|
|
2319
|
+
"name": "SubscriptionReplacementMode",
|
|
2320
|
+
"slug": "subscriptionreplacementmode",
|
|
2321
|
+
"docs": "How Google Play replaces an active subscription when `purchaseProduct()` is called with `oldPurchaseToken`\n(Android only). Passed by name and mapped natively to Play Billing's item-level `ReplacementMode` constants.\nDo not pass numeric `PRORATION_MODE` values; use these names.\n\n- `WITH_TIME_PRORATION`: replace now; the remaining time is credited by moving the next billing date.\n- `CHARGE_PRORATED_PRICE`: replace now and charge the price difference for the rest of the current period\n (upgrades only, where the price per unit of time increases).\n- `WITHOUT_PRORATION`: replace now; the new price is charged at the next renewal.\n- `CHARGE_FULL_PRICE`: replace now and charge the full price of the new plan.\n- `DEFERRED`: replace at the next renewal.",
|
|
2322
|
+
"types": [
|
|
2323
|
+
{
|
|
2324
|
+
"text": "'WITH_TIME_PRORATION'",
|
|
2325
|
+
"complexTypes": []
|
|
2326
|
+
},
|
|
2327
|
+
{
|
|
2328
|
+
"text": "'CHARGE_PRORATED_PRICE'",
|
|
2329
|
+
"complexTypes": []
|
|
2330
|
+
},
|
|
2331
|
+
{
|
|
2332
|
+
"text": "'WITHOUT_PRORATION'",
|
|
2333
|
+
"complexTypes": []
|
|
2334
|
+
},
|
|
2335
|
+
{
|
|
2336
|
+
"text": "'CHARGE_FULL_PRICE'",
|
|
2337
|
+
"complexTypes": []
|
|
2338
|
+
},
|
|
2339
|
+
{
|
|
2340
|
+
"text": "'DEFERRED'",
|
|
2341
|
+
"complexTypes": []
|
|
2342
|
+
}
|
|
2343
|
+
]
|
|
2273
2344
|
}
|
|
2274
2345
|
],
|
|
2275
2346
|
"pluginConfigs": []
|