@capgo/native-purchases 8.9.17 → 8.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,8 +33,8 @@ 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()`.
37
- - **Server validation**: receipt data and the `transactionUpdated` and `transactionVerificationFailed` events on iOS, purchase tokens on Android.
36
+ - **Subscription tools**: `manageSubscriptions()`, `presentOfferCodeRedeemSheet()` and `getStorefront()`, plus Android subscription upgrade/downgrade via `purchaseProduct({ oldPurchaseToken, oldProductIdentifier, replacementMode })`.
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
 
40
40
  ## In-app Purchases Made Easy
@@ -111,6 +111,10 @@ Add this to manifest
111
111
  <uses-permission android:name="com.android.vending.BILLING" />
112
112
  ```
113
113
 
114
+ ### Android rejection codes
115
+
116
+ Mapped Android billing and operation failures expose a stable `error.code` (see `NativePurchasesAndroidErrorCode` in `definitions.ts`). Branch on `error.code` instead of message text to tell user cancel (`USER_CANCELED`), pending purchase (`PURCHASE_PENDING`), and Play billing failures (`SERVICE_TIMEOUT`, `NETWORK_ERROR`, and the other mapped codes). For missing products, handle both `PRODUCT_NOT_FOUND` (the product-details query succeeded but returned no details) and `ITEM_UNAVAILABLE` (Play reported the SKU as unavailable).
117
+
114
118
  ### Testing with Google Play Console
115
119
 
116
120
  > 📖 **[Complete Android Testing Guide](./docs/ANDROID_TESTING_GUIDE.md)** - Comprehensive guide covering Internal Testing, License Testing, and Internal App Sharing methods with step-by-step instructions, troubleshooting, and best practices.
@@ -713,6 +717,10 @@ const checkBillingSupport = async () => {
713
717
  };
714
718
  ```
715
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
+
716
724
  ### Manage Subscriptions
717
725
 
718
726
  Allow users to manage their subscriptions directly from your app. This opens the platform's native subscription management page:
@@ -1815,8 +1823,8 @@ By default the plugin finishes StoreKit 2 transactions and acknowledges Google P
1815
1823
 
1816
1824
  | Setting | Scope |
1817
1825
  | -------- | ----- |
1818
- | `autoFinishTransactions` (default `true`) | Plugin-wide: iOS `transactionUpdated` and `purchaseProduct` when combined with `autoAcknowledgePurchases`. Android `restorePurchases` recovery and `purchaseProduct` when combined with `autoAcknowledgePurchases`. |
1819
- | `autoAcknowledgePurchases` on `purchaseProduct()` (default `true`) | Per purchase call. Effective auto finish/ack requires both flags to be true. Does not change the iOS `transactionUpdated` listener by itself. |
1826
+ | `autoFinishTransactions` (default `true`) | Plugin-wide: iOS and Android `transactionUpdated`, and `purchaseProduct` when combined with `autoAcknowledgePurchases`. Android `restorePurchases` recovery. |
1827
+ | `autoAcknowledgePurchases` on `purchaseProduct()` (default `true`) | Per purchase call. Effective auto finish/ack requires both flags to be true. Does not change the `transactionUpdated` listener by itself. |
1820
1828
 
1821
1829
  Set `autoFinishTransactions: false` in `capacitor.config` under `plugins.NativePurchases` so iOS applies it before the native update listener starts, or call `NativePurchases.configure({ autoFinishTransactions: false })` at startup.
1822
1830
 
@@ -1838,7 +1846,7 @@ After validation when automatic acknowledgment is off (for example `configure({
1838
1846
 
1839
1847
  An acknowledge or consume can be lost before Google Play answers, for example when the app is killed mid-finish. Plugin teardown (when Capacitor destroys the plugin with its activity) also closes the current billing client even while a finish is still in flight, and Play drops any work that client had queued. The purchase then stays unacknowledged, and Google Play refunds purchases that are not acknowledged within three days.
1840
1848
 
1841
- With `autoFinishTransactions: true` (the default), call `restorePurchases()` at app launch. It acknowledges any `PURCHASED` purchase that is still unacknowledged, so a purchase interrupted by a lost finish is completed on the next start. With `autoFinishTransactions: false`, use `getUnfinishedTransactions()` at launch instead and finish each purchase after validation.
1849
+ With `autoFinishTransactions: true` (the default), call `restorePurchases()` at app launch. It acknowledges any `PURCHASED` purchase that is still unacknowledged, so a purchase interrupted by a lost finish is completed on the next start. With `autoFinishTransactions: false`, use `getUnfinishedTransactions()` at launch, or listen for `transactionUpdated`, and finish each purchase after validation.
1842
1850
 
1843
1851
  ## Breaking (TypeScript typings)
1844
1852
 
@@ -1853,6 +1861,7 @@ With `autoFinishTransactions: true` (the default), call `restorePurchases()` at
1853
1861
  * [`getAppTransaction()`](#getapptransaction)
1854
1862
  * [`isEntitledToOldBusinessModel(...)`](#isentitledtooldbusinessmodel)
1855
1863
  * [`purchaseProduct(...)`](#purchaseproduct)
1864
+ * [`isSubscriptionReplacementSupported()`](#issubscriptionreplacementsupported)
1856
1865
  * [`getProducts(...)`](#getproducts)
1857
1866
  * [`getProduct(...)`](#getproduct)
1858
1867
  * [`isBillingSupported()`](#isbillingsupported)
@@ -1985,11 +1994,16 @@ to determine if they should be grandfathered into free features.
1985
1994
  ### purchaseProduct(...)
1986
1995
 
1987
1996
  ```typescript
1988
- 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>
1989
1998
  ```
1990
1999
 
1991
2000
  Started purchase process for the given product.
1992
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
+
1993
2007
  On Android, `offerToken` selects which offer is charged. If the token is
1994
2008
  missing from the product details returned by the plugin's query, the plugin
1995
2009
  rejects the purchase instead of selecting another offer. Other failures can
@@ -2020,15 +2034,34 @@ purchase option is marked backward-compatible, which is the first
2020
2034
  option does the first offer in the list get used. So pass the token
2021
2035
  whenever a specific one-time offer matters.
2022
2036
 
2023
- | Param | Type | Description |
2024
- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------- |
2025
- | **`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 |
2026
2040
 
2027
2041
  **Returns:** <code>Promise&lt;<a href="#transaction">Transaction</a>&gt;</code>
2028
2042
 
2029
2043
  --------------------
2030
2044
 
2031
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&lt;{ supported: boolean; }&gt;</code>
2059
+
2060
+ **Since:** 8.10.0
2061
+
2062
+ --------------------
2063
+
2064
+
2032
2065
  ### getProducts(...)
2033
2066
 
2034
2067
  ```typescript
@@ -2326,14 +2359,19 @@ can change their store region.
2326
2359
  addListener(eventName: 'transactionUpdated', listenerFunc: (transaction: Transaction) => void) => Promise<PluginListenerHandle>
2327
2360
  ```
2328
2361
 
2329
- Listen for StoreKit transaction updates delivered by Apple's <a href="#transaction">Transaction</a>.updates.
2330
- Fires on app launch if there are unfinished transactions, and for any updates afterward.
2362
+ Listen for purchase transaction updates outside an in-flight `purchaseProduct()` call.
2331
2363
 
2332
- When `autoFinishTransactions` is `true` (default), the plugin finishes each verified transaction
2333
- before emitting the event. When `false`, the event includes `needsFinish: true` and you must call
2334
- `finishTransaction()` after backend validation.
2364
+ **iOS:** StoreKit <a href="#transaction">Transaction</a>.updates. Fires on app launch for unfinished transactions.
2335
2365
 
2336
- iOS only.
2366
+ **Android:** Google Play PurchasesUpdatedListener on a persistent billing connection while this
2367
+ listener is registered, plus queryPurchasesAsync when the first listener is added and when the
2368
+ app returns to the foreground. Pending purchases that complete later are reported here.
2369
+
2370
+ When `autoFinishTransactions` is `true` (default), iOS finishes each verified transaction before
2371
+ emitting; Android attempts to acknowledge each PURCHASED purchase before emitting (pending
2372
+ purchases and failed acknowledgements are still emitted without acknowledgement). When `false`,
2373
+ purchased `transactionUpdated` events include `needsFinish: true` when not yet acknowledged; call
2374
+ `finishTransaction()` or `acknowledgePurchase()` after backend validation.
2337
2375
 
2338
2376
  | Param | Type |
2339
2377
  | ------------------ | ----------------------------------------------------------------------------- |
@@ -2585,6 +2623,22 @@ Android one-time product discount display metadata.
2585
2623
  <code>'upFront' | 'monthly' | 'unknown'</code>
2586
2624
 
2587
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
+
2588
2642
  ### Enums
2589
2643
 
2590
2644
 
@@ -0,0 +1,53 @@
1
+ package ee.forgr.nativepurchases;
2
+
3
+ import com.android.billingclient.api.BillingClient;
4
+
5
+ /**
6
+ * Stable rejection {@code code} strings for Android {@link com.getcapacitor.PluginCall#reject}.
7
+ * Play {@link BillingClient.BillingResponseCode} values are mapped in {@link #name(int)}.
8
+ */
9
+ public final class BillingResponseCodes {
10
+
11
+ public static final String PURCHASE_PENDING = "PURCHASE_PENDING";
12
+ public static final String PRODUCT_NOT_FOUND = "PRODUCT_NOT_FOUND";
13
+ public static final String BILLING_CLIENT_CLOSED = "BILLING_CLIENT_CLOSED";
14
+ public static final String PURCHASE_NOT_FOUND = "PURCHASE_NOT_FOUND";
15
+
16
+ private BillingResponseCodes() {}
17
+
18
+ /**
19
+ * Maps a Play billing response code to a stable plugin error code.
20
+ */
21
+ public static String name(int code) {
22
+ switch (code) {
23
+ case BillingClient.BillingResponseCode.OK:
24
+ return "OK";
25
+ case BillingClient.BillingResponseCode.USER_CANCELED:
26
+ return "USER_CANCELED";
27
+ case BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED:
28
+ return "ITEM_ALREADY_OWNED";
29
+ case BillingClient.BillingResponseCode.ITEM_NOT_OWNED:
30
+ return "ITEM_NOT_OWNED";
31
+ case BillingClient.BillingResponseCode.ITEM_UNAVAILABLE:
32
+ return "ITEM_UNAVAILABLE";
33
+ case BillingClient.BillingResponseCode.BILLING_UNAVAILABLE:
34
+ return "BILLING_UNAVAILABLE";
35
+ case BillingClient.BillingResponseCode.SERVICE_DISCONNECTED:
36
+ return "SERVICE_DISCONNECTED";
37
+ case BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE:
38
+ return "SERVICE_UNAVAILABLE";
39
+ case BillingClient.BillingResponseCode.SERVICE_TIMEOUT:
40
+ return "SERVICE_TIMEOUT";
41
+ case BillingClient.BillingResponseCode.DEVELOPER_ERROR:
42
+ return "DEVELOPER_ERROR";
43
+ case BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED:
44
+ return "FEATURE_NOT_SUPPORTED";
45
+ case BillingClient.BillingResponseCode.NETWORK_ERROR:
46
+ return "NETWORK_ERROR";
47
+ case BillingClient.BillingResponseCode.ERROR:
48
+ return "ERROR";
49
+ default:
50
+ return "UNKNOWN_" + code;
51
+ }
52
+ }
53
+ }