@capgo/native-purchases 8.9.7 → 8.9.8

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
@@ -183,19 +183,22 @@ There are two types of purchases with different requirements:
183
183
  | Purchase Type | productType | planIdentifier | Use Case |
184
184
  |---------------|-------------|----------------|----------|
185
185
  | **In-App Purchase** | `PURCHASE_TYPE.INAPP` | ❌ Not needed | One-time purchases (premium features, remove ads, etc.) |
186
- | **Subscription** | `PURCHASE_TYPE.SUBS` | ✅ **REQUIRED (Android only)** | Recurring purchases (monthly/yearly subscriptions) |
186
+ | **Subscription** | `PURCHASE_TYPE.SUBS` | ✅ **REQUIRED (Android only, unless you pass `offerToken`)** | Recurring purchases (monthly/yearly subscriptions) |
187
187
 
188
188
  **Key Rules:**
189
189
  - ✅ **In-App Products**: Use `productType: PURCHASE_TYPE.INAPP`, no `planIdentifier` needed on any platform
190
- - ✅ **Subscriptions on Android**: Must use `productType: PURCHASE_TYPE.SUBS` AND `planIdentifier: "your-plan-id"` (the Base Plan ID from Google Play Console)
190
+ - ✅ **Subscriptions on Android**: Use `productType: PURCHASE_TYPE.SUBS` AND either `planIdentifier: "your-plan-id"` (the Base Plan ID from Google Play Console) or `offerToken` (one exact offer, read from `getProducts()`)
191
191
  - ✅ **Subscriptions on iOS**: Use `productType: PURCHASE_TYPE.SUBS`, `planIdentifier` is optional and ignored
192
- - ❌ **Missing planIdentifier** for Android subscriptions will cause purchase failures
192
+ - ❌ **Missing both `planIdentifier` and `offerToken`** for Android subscriptions will cause purchase failures
193
193
 
194
194
  **About planIdentifier (Android-specific):**
195
- The `planIdentifier` parameter is **only required for Android subscriptions**. It should be set to the Base Plan ID that you configure in the Google Play Console when creating your subscription product. For example, if you create a monthly subscription with base plan ID "monthly-plan" in Google Play Console, you would use `planIdentifier: "monthly-plan"` when purchasing that subscription.
195
+ The `planIdentifier` parameter is **only used for Android subscriptions**. It should be set to the Base Plan ID that you configure in the Google Play Console when creating your subscription product. For example, if you create a monthly subscription with base plan ID "monthly-plan" in Google Play Console, you would use `planIdentifier: "monthly-plan"` when purchasing that subscription. `getProducts()` reports that value as `Product.identifier`, not as `Product.planIdentifier`, which holds the Play product id.
196
196
 
197
197
  iOS does not use this parameter - subscriptions on iOS only require the product identifier.
198
198
 
199
+ **About offerToken (Android-specific):**
200
+ A base plan can carry several offers (a free trial, an introductory price), and `planIdentifier` names only the plan. The plugin then purchases the **first offer Play returned for that plan** and sets that offer's token, so which offer applies is decided by the order of the list rather than by your app, and the store does not pick one at purchase time. `offerToken` names one exact offer instead, which is why it makes `planIdentifier` unnecessary; when both are given, the token wins. Read it from the `offerToken` of the same `getProducts()` entry you purchase, because tokens belong to one product query and go stale, and note that a token matching no current offer is **rejected** rather than quietly charging a different price. Pass `offerToken` whenever a specific offer you displayed must be the one charged. [`purchaseProduct`](#purchaseproduct) documents the full order of precedence.
201
+
199
202
  ### Complete Example: Get Product Info and Purchase
200
203
 
201
204
  Here's a complete example showing how to get product information and make purchases for both in-app products and subscriptions:
@@ -207,7 +210,7 @@ class PurchaseManager {
207
210
  // In-app product (one-time purchase)
208
211
  private premiumProductId = 'com.yourapp.premium_features';
209
212
 
210
- // Subscription products (require planIdentifier on Android)
213
+ // Subscription products (Android: planIdentifier, or the separate offerToken option)
211
214
  private monthlySubId = 'com.yourapp.premium.monthly';
212
215
  private monthlyPlanId = 'monthly-plan'; // Base plan ID from Google Play Console (Android only)
213
216
 
@@ -299,14 +302,14 @@ class PurchaseManager {
299
302
  }
300
303
  }
301
304
 
302
- // Purchase subscription (planIdentifier REQUIRED for Android)
305
+ // Purchase subscription (Android: planIdentifier, or the separate offerToken option)
303
306
  async purchaseMonthlySubscription() {
304
307
  try {
305
308
  console.log('Starting subscription purchase...');
306
309
 
307
310
  const result = await NativePurchases.purchaseProduct({
308
311
  productIdentifier: this.monthlySubId,
309
- planIdentifier: this.monthlyPlanId, // REQUIRED for Android subscriptions, ignored on iOS
312
+ planIdentifier: this.monthlyPlanId, // Android base plan id, not an offerToken; ignored on iOS
310
313
  productType: PURCHASE_TYPE.SUBS, // REQUIRED for subscriptions
311
314
  quantity: 1
312
315
  });
@@ -320,14 +323,14 @@ class PurchaseManager {
320
323
  }
321
324
  }
322
325
 
323
- // Purchase yearly subscription (planIdentifier REQUIRED for Android)
326
+ // Purchase yearly subscription (Android: planIdentifier, or the separate offerToken option)
324
327
  async purchaseYearlySubscription() {
325
328
  try {
326
329
  console.log('Starting yearly subscription purchase...');
327
330
 
328
331
  const result = await NativePurchases.purchaseProduct({
329
332
  productIdentifier: this.yearlySubId,
330
- planIdentifier: this.yearlyPlanId, // REQUIRED for Android subscriptions, ignored on iOS
333
+ planIdentifier: this.yearlyPlanId, // Android base plan id, not an offerToken; ignored on iOS
331
334
  productType: PURCHASE_TYPE.SUBS, // REQUIRED for subscriptions
332
335
  quantity: 1
333
336
  });
@@ -489,6 +492,75 @@ const getSubscriptions = async () => {
489
492
  ```typescript
490
493
  import { NativePurchases, PURCHASE_TYPE } from '@capgo/native-purchases';
491
494
 
495
+ // Android subscription offers: priceString is the recurring phase; introductoryPrice is the first phase on base offers.
496
+ const formatIntroPhaseDuration = (intro: {
497
+ numberOfPeriods: number;
498
+ subscriptionPeriod?: { numberOfUnits: number; unitString?: string };
499
+ }) => {
500
+ const units = intro.subscriptionPeriod?.numberOfUnits ?? 1;
501
+ const count = intro.numberOfPeriods * units;
502
+ const unit = intro.subscriptionPeriod?.unitString ?? 'period';
503
+ const label = count === 1 ? unit : `${unit}s`;
504
+ return `${count} ${label}`;
505
+ };
506
+
507
+ const formatRecurringInterval = (period?: {
508
+ numberOfUnits: number;
509
+ unitString?: string;
510
+ }): string | null => {
511
+ if (!period?.numberOfUnits || !period.unitString || period.unitString === 'unknown') {
512
+ return null;
513
+ }
514
+ const { numberOfUnits, unitString } = period;
515
+ if (numberOfUnits === 1) {
516
+ return `per ${unitString}`;
517
+ }
518
+ const label = `${unitString}s`;
519
+ return `every ${numberOfUnits} ${label}`;
520
+ };
521
+
522
+ const formatRecurringPrice = (
523
+ priceString: string,
524
+ period?: { numberOfUnits: number; unitString?: string },
525
+ ): string | null => {
526
+ const interval = formatRecurringInterval(period);
527
+ if (!interval) {
528
+ return null;
529
+ }
530
+ return `${priceString} ${interval}`;
531
+ };
532
+
533
+ const subscriptionOfferPriceSummary = (product: {
534
+ priceString: string;
535
+ offerId?: string | null;
536
+ subscriptionPeriod?: { numberOfUnits: number; unitString?: string };
537
+ subscriptionBillingCycles?: number;
538
+ introductoryPrice: {
539
+ priceString: string;
540
+ numberOfPeriods: number;
541
+ subscriptionPeriod?: { numberOfUnits: number; unitString?: string };
542
+ } | null;
543
+ }): string | null => {
544
+ const intro = product.introductoryPrice;
545
+ const cycles = product.subscriptionBillingCycles;
546
+ // Installment subsequent terms are not on Product, so do not imply charges stop after the commitment.
547
+ if (cycles !== undefined && cycles > 0) {
548
+ return null;
549
+ }
550
+ if (intro?.priceString && intro.priceString !== product.priceString) {
551
+ const recurring = formatRecurringPrice(product.priceString, product.subscriptionPeriod);
552
+ if (!recurring) {
553
+ return null;
554
+ }
555
+ return `${intro.priceString} for ${formatIntroPhaseDuration(intro)}, then ${recurring}`;
556
+ }
557
+ // Promotional offer lines omit introductoryPrice; do not show recurring price alone as the full offer.
558
+ if (product.offerId) {
559
+ return null;
560
+ }
561
+ return formatRecurringPrice(product.priceString, product.subscriptionPeriod);
562
+ };
563
+
492
564
  // Simple one-time purchase (in-app product)
493
565
  const buyInAppProduct = async () => {
494
566
  try {
@@ -546,7 +618,7 @@ const buyInAppProduct = async () => {
546
618
  }
547
619
  };
548
620
 
549
- // Simple subscription purchase (requires planIdentifier)
621
+ // Simple subscription purchase (Android: planIdentifier, or the separate offerToken option)
550
622
  const buySubscription = async () => {
551
623
  try {
552
624
  // Check billing support
@@ -562,14 +634,18 @@ const buySubscription = async () => {
562
634
  productType: PURCHASE_TYPE.SUBS
563
635
  });
564
636
 
565
- // Confirm with user (showing real price from store)
566
- const confirmed = confirm(`Subscribe to ${product.title} for ${product.priceString}?`);
637
+ // Confirm with user: show intro and recurring terms when mapped; otherwise Play checkout shows the price.
638
+ const offerSummary = subscriptionOfferPriceSummary(product);
639
+ const confirmed = offerSummary
640
+ ? confirm(`Subscribe to ${product.title} for ${offerSummary}?`)
641
+ : confirm(`Subscribe to ${product.title}? Google Play will show the offer price at checkout.`);
567
642
  if (!confirmed) return;
568
643
 
569
- // Make subscription purchase (planIdentifier REQUIRED for Android, ignored on iOS)
644
+ // Purchase the same offer you displayed: reuse identifier and offerToken from getProduct()
570
645
  const result = await NativePurchases.purchaseProduct({
571
646
  productIdentifier: 'com.yourapp.premium.monthly',
572
- planIdentifier: 'monthly-plan', // REQUIRED for Android subscriptions, ignored on iOS
647
+ planIdentifier: product.identifier, // Android base plan id for this offer; ignored on iOS
648
+ offerToken: product.offerToken, // Android: same offer as the price above; ignored on iOS
573
649
  productType: PURCHASE_TYPE.SUBS, // REQUIRED for subscriptions
574
650
  quantity: 1,
575
651
  appAccountToken: uuidToken // Optional: User identifier in UUID format
@@ -1406,12 +1482,12 @@ class Store {
1406
1482
  }
1407
1483
  }
1408
1484
 
1409
- // Purchase subscription (requires planIdentifier)
1485
+ // Purchase subscription (Android: planIdentifier, or the separate offerToken option)
1410
1486
  async purchaseSubscription(productId: string, planId: string) {
1411
1487
  try {
1412
1488
  const transaction = await NativePurchases.purchaseProduct({
1413
1489
  productIdentifier: productId,
1414
- planIdentifier: planId, // REQUIRED for subscriptions
1490
+ planIdentifier: planId, // Android base plan id; offerToken is separate
1415
1491
  productType: PURCHASE_TYPE.SUBS // REQUIRED for subscriptions
1416
1492
  });
1417
1493
  console.log('Subscription purchase successful:', transaction);
@@ -1484,7 +1560,7 @@ try {
1484
1560
  await store.purchaseProduct('premium_features');
1485
1561
  console.log('In-app purchase completed successfully');
1486
1562
 
1487
- // Purchase subscription (requires planIdentifier)
1563
+ // Purchase subscription (Android: planIdentifier, or the separate offerToken option)
1488
1564
  await store.purchaseSubscription('premium_monthly', 'monthly-plan');
1489
1565
  console.log('Subscription completed successfully');
1490
1566
  } catch (error) {
@@ -1746,6 +1822,10 @@ StoreKit re-delivers an unverified transaction on every launch until it is finis
1746
1822
 
1747
1823
  After validation when automatic acknowledgment is off (for example `configure({ autoFinishTransactions: false })` or `purchaseProduct({ autoAcknowledgePurchases: false })`), call `consumePurchase({ purchaseToken })` for consumable in-app products (acknowledges and consumes), or `acknowledgePurchase({ purchaseToken })` for non-consumables and subscriptions. `finishTransaction({ transactionId })` also acknowledges on Android, where `transactionId` is the purchase token. With `autoFinishTransactions: false`, `restorePurchases()` does not auto-acknowledge; use `getUnfinishedTransactions()` to list unacknowledged purchases in the `PURCHASED` state (`isAcknowledged === false`).
1748
1824
 
1825
+ ## Breaking (TypeScript typings)
1826
+
1827
+ `Product.subscriptionPeriod` is now optional. Android omits it on prepaid (non-recurring) offers, which have price only. The period is present for infinite recurring phases, or for finite recurring phases on installment offers. Reading `product.subscriptionPeriod.unit` without a check is a TypeScript error. Use optional chaining, for example `product.subscriptionPeriod?.unit`. See [`Product`](#product).
1828
+
1749
1829
  ## API
1750
1830
 
1751
1831
  <docgen-index>
@@ -1892,6 +1972,36 @@ purchaseProduct(options: { productIdentifier: string; planIdentifier?: string; o
1892
1972
 
1893
1973
  Started purchase process for the given product.
1894
1974
 
1975
+ On Android, `offerToken` selects which offer is charged. If the token is
1976
+ missing from the product details returned by the plugin's query, the plugin
1977
+ rejects the purchase instead of selecting another offer. Other failures can
1978
+ also reject the purchase. Google Play may still show a different checkout,
1979
+ for example if the offer stops being eligible after the query, so the final
1980
+ price is not guaranteed.
1981
+ Offer tokens come from a specific product query and go stale, so read
1982
+ one from the same `getProducts()` / `getProduct()` call you purchase
1983
+ from.
1984
+
1985
+ For a **subscription** (`productType: 'subs'`) the order is: an explicit
1986
+ `offerToken`, then the first offer whose base plan matches
1987
+ `planIdentifier`, then the first offer the store returned.
1988
+ `planIdentifier` is the **base plan id**, which `getProducts()` reports
1989
+ as <a href="#product">`Product.identifier`</a>, not <a href="#product">`Product.planIdentifier`</a>, which holds the
1990
+ Play product id. It is required unless an `offerToken` is given, since
1991
+ a token already identifies one offer on its own.
1992
+
1993
+ For a **one-time product** (`productType: 'inapp'`) there is no base
1994
+ plan, so `planIdentifier` plays no part, and an `offerToken` selects one
1995
+ of the product's purchase offers. Without a token no offer token is set
1996
+ at all whenever the product still has a backward-compatible purchase
1997
+ option, which leaves the choice to Play: it charges whichever buy
1998
+ purchase option is marked backward-compatible, which is the first
1999
+ *created* one by default and another only if one was marked
2000
+ `legacyCompatible`. Either way it need not be the first offer
2001
+ `getProducts()` returned. Only for a product with no backward-compatible
2002
+ option does the first offer in the list get used. So pass the token
2003
+ whenever a specific one-time offer matters.
2004
+
1895
2005
  | Param | Type | Description |
1896
2006
  | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------- |
1897
2007
  | **`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 |
@@ -2341,28 +2451,29 @@ which is useful for determining if users are entitled to features from earlier b
2341
2451
 
2342
2452
  #### Product
2343
2453
 
2344
- | Prop | Type | Description | Since |
2345
- | --------------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
2346
- | **`identifier`** | <code>string</code> | <a href="#product">Product</a> Id. Android subscriptions note: - `identifier` is the base plan ID (`offerDetails.getBasePlanId()`). - `planIdentifier` is the subscription product ID (`productDetails.getProductId()`). Android one-time products note: - `identifier` is the Google Play product ID (`productDetails.getProductId()`). - When multiple offers exist, `getProducts()` returns one entry per eligible offer. If you group/filter Android subscription results by `identifier`, you are grouping by base plan. | |
2347
- | **`description`** | <code>string</code> | Description of the product. | |
2348
- | **`title`** | <code>string</code> | Title of the product. | |
2349
- | **`price`** | <code>number</code> | Price of the product in the local currency. | |
2350
- | **`priceString`** | <code>string</code> | Formatted price of the item, including its currency sign, such as €3.99. | |
2351
- | **`currencyCode`** | <code>string</code> | Currency code for price and original price. | |
2352
- | **`currencySymbol`** | <code>string</code> | Currency symbol for price and original price. | |
2353
- | **`isFamilyShareable`** | <code>boolean</code> | Boolean indicating if the product is sharable with family | |
2354
- | **`subscriptionGroupIdentifier`** | <code>string</code> | Group identifier for the product. | |
2355
- | **`planIdentifier`** | <code>string</code> | Android subscriptions only: Google Play product identifier tied to the offer/base plan set. | |
2356
- | **`offerToken`** | <code>string</code> | Android: offer token required when purchasing a specific subscription or one-time offer. | |
2357
- | **`offerId`** | <code>string \| null</code> | Android: offer identifier (null/undefined for base offers). | |
2358
- | **`purchaseOptionId`** | <code>string</code> | Android one-time products only: purchase option identifier (for example `buy-option`). | |
2359
- | **`fullPrice`** | <code>number</code> | Android one-time products only: full price before discount, in the local currency. | |
2360
- | **`discountDisplayInfo`** | <code><a href="#onetimepurchaseofferdiscount">OneTimePurchaseOfferDiscount</a></code> | Android one-time products only: discount metadata for discounted offers. | |
2361
- | **`pricingTerms`** | <code>SubscriptionPricingTerms[]</code> | iOS subscriptions only: StoreKit pricing terms by billing plan. For subscriptions with a monthly billing plan and 12-month commitment, this includes both the standard up-front plan and the monthly commitment plan. Display both `billingDisplayPrice` and `commitmentInfo.priceString` before starting a monthly commitment purchase. | 8.3.8 |
2362
- | **`subscriptionPeriod`** | <code><a href="#subscriptionperiod">SubscriptionPeriod</a></code> | The <a href="#product">Product</a> subscription group identifier. | |
2363
- | **`introductoryPrice`** | <code><a href="#skproductdiscount">SKProductDiscount</a> \| null</code> | The <a href="#product">Product</a> introductory Price. | |
2364
- | **`introEligibility`** | <code><a href="#intro_eligibility_status">INTRO_ELIGIBILITY_STATUS</a></code> | Whether the current store account is eligible for an introductory offer on this subscription. | 8.8.3 |
2365
- | **`discounts`** | <code>SKProductDiscount[]</code> | The <a href="#product">Product</a> discounts list. | |
2454
+ | Prop | Type | Description | Since |
2455
+ | --------------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
2456
+ | **`identifier`** | <code>string</code> | <a href="#product">Product</a> Id. Android subscriptions note: - `identifier` is the base plan ID (`offerDetails.getBasePlanId()`). - `planIdentifier` is the subscription product ID (`productDetails.getProductId()`). Android one-time products note: - `identifier` is the Google Play product ID (`productDetails.getProductId()`). - When multiple offers exist, `getProducts()` returns one entry per eligible offer. If you group/filter Android subscription results by `identifier`, you are grouping by base plan. | |
2457
+ | **`description`** | <code>string</code> | Description of the product. | |
2458
+ | **`title`** | <code>string</code> | Title of the product. | |
2459
+ | **`price`** | <code>number</code> | Price of the product in the local currency. | |
2460
+ | **`priceString`** | <code>string</code> | Formatted price of the item, including its currency sign, such as €3.99. Android subscriptions: set from the standard recurring pricing phase (see `ProductPayloadMapper`). When the offer has an introductory phase, `introductoryPrice` describes that phase, so a pre purchase message should include both or defer confirmation to the store sheet. | |
2461
+ | **`currencyCode`** | <code>string</code> | Currency code for price and original price. | |
2462
+ | **`currencySymbol`** | <code>string</code> | Currency symbol for price and original price. | |
2463
+ | **`isFamilyShareable`** | <code>boolean</code> | Boolean indicating if the product is sharable with family | |
2464
+ | **`subscriptionGroupIdentifier`** | <code>string</code> | Group identifier for the product. | |
2465
+ | **`planIdentifier`** | <code>string</code> | Android subscriptions only: Google Play product identifier tied to the offer/base plan set. | |
2466
+ | **`offerToken`** | <code>string</code> | Android: offer token required when purchasing a specific subscription or one-time offer. Pass it to `purchaseProduct({ offerToken })` to buy this exact offer. It belongs to the query that returned it and goes stale, so read it from the same `getProducts()` / `getProduct()` call you purchase from. | |
2467
+ | **`offerId`** | <code>string \| null</code> | Android: offer identifier (null/undefined for base offers). | |
2468
+ | **`purchaseOptionId`** | <code>string</code> | Android one-time products only: purchase option identifier (for example `buy-option`). | |
2469
+ | **`fullPrice`** | <code>number</code> | Android one-time products only: full price before discount, in the local currency. | |
2470
+ | **`discountDisplayInfo`** | <code><a href="#onetimepurchaseofferdiscount">OneTimePurchaseOfferDiscount</a></code> | Android one-time products only: discount metadata for discounted offers. | |
2471
+ | **`pricingTerms`** | <code>SubscriptionPricingTerms[]</code> | iOS subscriptions only: StoreKit pricing terms by billing plan. For subscriptions with a monthly billing plan and 12-month commitment, this includes both the standard up-front plan and the monthly commitment plan. Display both `billingDisplayPrice` and `commitmentInfo.priceString` before starting a monthly commitment purchase. | 8.3.8 |
2472
+ | **`subscriptionPeriod`** | <code><a href="#subscriptionperiod">SubscriptionPeriod</a></code> | Recurring billing period for subscription products. | |
2473
+ | **`subscriptionBillingCycles`** | <code>number</code> | Android subscriptions only: committed payment count for installment base plans when Play exposes it on the offer. | |
2474
+ | **`introductoryPrice`** | <code><a href="#skproductdiscount">SKProductDiscount</a> \| null</code> | Introductory price for this product line when the store exposes it. Pair with `priceString` for full subscription offer wording before purchase. iOS: from StoreKit introductory offers when available. Android base subscription offers (`offerId` null): from the first pricing phase when multiple phases exist (intro then recurring). Android promotional offer lines (`offerId` set): null; phase pricing is not exposed on <a href="#product">`Product`</a>, so defer price confirmation to Play checkout instead of using `priceString` alone. Mapping matches `ProductPayloadMapper`. | |
2475
+ | **`introEligibility`** | <code><a href="#intro_eligibility_status">INTRO_ELIGIBILITY_STATUS</a></code> | Whether the current store account is eligible for an introductory offer on this subscription. | 8.8.3 |
2476
+ | **`discounts`** | <code>SKProductDiscount[]</code> | The <a href="#product">Product</a> discounts list. | |
2366
2477
 
2367
2478
 
2368
2479
  #### OneTimePurchaseOfferDiscount
@@ -58,6 +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.14.2'
61
62
  androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
62
63
  androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
63
64
  }
@@ -43,7 +43,67 @@ import org.json.JSONArray;
43
43
  @CapacitorPlugin(name = "NativePurchases")
44
44
  public class NativePurchasesPlugin extends Plugin {
45
45
 
46
- private final String pluginVersion = "8.9.7";
46
+ /** Outcome of choosing a subscription offer token before launching the billing flow. */
47
+ enum SubscriptionOfferPurchaseOutcome {
48
+ /** An offer was selected; {@link SubscriptionOfferPurchaseResult#offerToken} is set. */
49
+ OK,
50
+ /** The product details contained no subscription offers. */
51
+ NO_OFFERS,
52
+ /** An explicit offer token matched nothing in the query result. */
53
+ OFFER_TOKEN_NOT_FOUND
54
+ }
55
+
56
+ /** Result of {@link #resolveSubscriptionOfferForPurchase}. */
57
+ static final class SubscriptionOfferPurchaseResult {
58
+
59
+ final SubscriptionOfferPurchaseOutcome outcome;
60
+ final String offerToken;
61
+ final String basePlanId;
62
+
63
+ private SubscriptionOfferPurchaseResult(SubscriptionOfferPurchaseOutcome outcome, String offerToken, String basePlanId) {
64
+ this.outcome = outcome;
65
+ this.offerToken = offerToken;
66
+ this.basePlanId = basePlanId;
67
+ }
68
+
69
+ static SubscriptionOfferPurchaseResult ok(String offerToken, String basePlanId) {
70
+ return new SubscriptionOfferPurchaseResult(SubscriptionOfferPurchaseOutcome.OK, offerToken, basePlanId);
71
+ }
72
+
73
+ static SubscriptionOfferPurchaseResult noOffers() {
74
+ return new SubscriptionOfferPurchaseResult(SubscriptionOfferPurchaseOutcome.NO_OFFERS, null, null);
75
+ }
76
+
77
+ static SubscriptionOfferPurchaseResult offerTokenNotFound() {
78
+ return new SubscriptionOfferPurchaseResult(SubscriptionOfferPurchaseOutcome.OFFER_TOKEN_NOT_FOUND, null, null);
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Selects the subscription offer token for {@link #purchaseProduct}, using the same rules
84
+ * as {@link SubscriptionOfferSelector}.
85
+ */
86
+ static SubscriptionOfferPurchaseResult resolveSubscriptionOfferForPurchase(
87
+ List<ProductDetails.SubscriptionOfferDetails> subscriptionOffers,
88
+ String planIdentifier,
89
+ String offerToken
90
+ ) {
91
+ if (subscriptionOffers == null || subscriptionOffers.isEmpty()) {
92
+ return SubscriptionOfferPurchaseResult.noOffers();
93
+ }
94
+ int selectedIndex = SubscriptionOfferSelector.selectIndex(
95
+ SubscriptionOfferSelector.adapt(subscriptionOffers),
96
+ planIdentifier,
97
+ offerToken
98
+ );
99
+ if (selectedIndex == SubscriptionOfferSelector.NOT_FOUND) {
100
+ return SubscriptionOfferPurchaseResult.offerTokenNotFound();
101
+ }
102
+ ProductDetails.SubscriptionOfferDetails selected = subscriptionOffers.get(selectedIndex);
103
+ return SubscriptionOfferPurchaseResult.ok(selected.getOfferToken(), selected.getBasePlanId());
104
+ }
105
+
106
+ private final String pluginVersion = "8.9.8";
47
107
  public static final String TAG = "NativePurchases";
48
108
  private static final int BILLING_CONNECTION_MAX_ATTEMPTS = 2;
49
109
  private static final long BILLING_SETUP_TIMEOUT_SECONDS = 5;
@@ -307,6 +367,19 @@ public class NativePurchasesPlugin extends Plugin {
307
367
  }
308
368
  }
309
369
 
370
+ /**
371
+ * Reject a purchase whose {@code offerToken} matched no current offer.
372
+ *
373
+ * Shared by the subscription and one-time paths because `definitions.ts`
374
+ * documents that rejection as one rule covering both product types, so
375
+ * the two must not drift apart in wording.
376
+ */
377
+ private void rejectOfferTokenNotFound(PluginCall call, String productIdentifier) {
378
+ NativePurchasesLog.d(TAG, "Offer token not found for product: " + productIdentifier);
379
+ closeBillingClient();
380
+ call.reject("Offer token not found for product: " + productIdentifier);
381
+ }
382
+
310
383
  private void closeBillingClientLocked() {
311
384
  NativePurchasesLog.d(TAG, "closeBillingClient() called");
312
385
  if (billingClient != null) {
@@ -755,10 +828,13 @@ public class NativePurchasesPlugin extends Plugin {
755
828
  call.reject("productType is empty");
756
829
  return;
757
830
  }
758
- if (productType.equals("subs") && (planIdentifier == null || planIdentifier.isEmpty())) {
759
- // Handle error: no planIdentifier with productType subs
831
+ boolean hasOfferToken = offerToken != null && !offerToken.isEmpty();
832
+ if (productType.equals("subs") && !SubscriptionOfferSelector.canSelect(planIdentifier, offerToken)) {
833
+ // The caller named no offer at all. SubscriptionOfferSelector owns
834
+ // this rule: see canSelect for why either value alone is enough,
835
+ // and for what it deliberately does not catch.
760
836
  NativePurchasesLog.d(TAG, "Error: planIdentifier cannot be empty if productType is subs");
761
- call.reject("planIdentifier cannot be empty if productType is subs");
837
+ call.reject("planIdentifier cannot be empty if productType is subs unless offerToken is provided");
762
838
  return;
763
839
  }
764
840
  assert quantity != null;
@@ -820,35 +896,42 @@ public class NativePurchasesPlugin extends Plugin {
820
896
  BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(productDetailsItem);
821
897
  if (productType.equals("subs")) {
822
898
  NativePurchasesLog.d(TAG, "Processing subscription product");
823
- // list the SubscriptionOfferDetails and find the one who match the planIdentifier if not found get the first one
824
- ProductDetails.SubscriptionOfferDetails selectedOfferDetails = null;
825
- assert productDetailsItem.getSubscriptionOfferDetails() != null;
899
+ // Prefer an explicit offerToken, then the planIdentifier's base
900
+ // plan, then the first offer. See SubscriptionOfferSelector.
901
+ List<ProductDetails.SubscriptionOfferDetails> subscriptionOffers =
902
+ productDetailsItem.getSubscriptionOfferDetails();
826
903
  NativePurchasesLog.d(
827
904
  TAG,
828
- "Available offer details count: " + productDetailsItem.getSubscriptionOfferDetails().size()
905
+ "Available offer details count: " + (subscriptionOffers == null ? 0 : subscriptionOffers.size())
829
906
  );
830
- for (ProductDetails.SubscriptionOfferDetails offerDetails : productDetailsItem.getSubscriptionOfferDetails()) {
831
- NativePurchasesLog.d(TAG, "Checking offer: " + offerDetails.getBasePlanId());
832
- if (offerDetails.getBasePlanId().equals(planIdentifier)) {
833
- selectedOfferDetails = offerDetails;
834
- NativePurchasesLog.d(TAG, "Found matching plan: " + planIdentifier);
835
- break;
836
- }
907
+
908
+ SubscriptionOfferPurchaseResult subscriptionSelection = resolveSubscriptionOfferForPurchase(
909
+ subscriptionOffers,
910
+ planIdentifier,
911
+ offerToken
912
+ );
913
+ if (subscriptionSelection.outcome == SubscriptionOfferPurchaseOutcome.NO_OFFERS) {
914
+ NativePurchasesLog.w(TAG, "No subscription offer details found for product: " + productIdentifier);
915
+ closeBillingClient();
916
+ call.reject("No subscription offer details found for product: " + productIdentifier);
917
+ return;
837
918
  }
838
- if (selectedOfferDetails == null) {
839
- selectedOfferDetails = productDetailsItem.getSubscriptionOfferDetails().get(0);
840
- NativePurchasesLog.d(TAG, "Using first available offer: " + selectedOfferDetails.getBasePlanId());
919
+ if (subscriptionSelection.outcome == SubscriptionOfferPurchaseOutcome.OFFER_TOKEN_NOT_FOUND) {
920
+ rejectOfferTokenNotFound(call, productIdentifier);
921
+ return;
841
922
  }
842
- productDetailsParams.setOfferToken(selectedOfferDetails.getOfferToken());
923
+
924
+ NativePurchasesLog.d(TAG, "Selected base plan: " + subscriptionSelection.basePlanId);
925
+ productDetailsParams.setOfferToken(subscriptionSelection.offerToken);
843
926
  NativePurchasesLog.d(
844
927
  TAG,
845
- "Set offer token: " + NativePurchasesLog.redactSensitive(selectedOfferDetails.getOfferToken())
928
+ "Set offer token: " + NativePurchasesLog.redactSensitive(subscriptionSelection.offerToken)
846
929
  );
847
930
  } else if (productType.equals("inapp")) {
848
931
  NativePurchasesLog.d(TAG, "Processing in-app product");
849
932
  List<ProductDetails.OneTimePurchaseOfferDetails> oneTimeOffers =
850
933
  ProductPayloadMapper.resolveOneTimePurchaseOffers(productDetailsItem);
851
- if (offerToken != null && !offerToken.isEmpty()) {
934
+ if (hasOfferToken) {
852
935
  ProductDetails.OneTimePurchaseOfferDetails selectedOffer = null;
853
936
  for (ProductDetails.OneTimePurchaseOfferDetails offerDetails : oneTimeOffers) {
854
937
  if (offerToken.equals(offerDetails.getOfferToken())) {
@@ -857,9 +940,7 @@ public class NativePurchasesPlugin extends Plugin {
857
940
  }
858
941
  }
859
942
  if (selectedOffer == null) {
860
- NativePurchasesLog.d(TAG, "Offer token not found for product: " + productIdentifier);
861
- closeBillingClient();
862
- call.reject("Offer token not found for product: " + productIdentifier);
943
+ rejectOfferTokenNotFound(call, productIdentifier);
863
944
  return;
864
945
  }
865
946
  productDetailsParams.setOfferToken(selectedOffer.getOfferToken());
@@ -87,6 +87,14 @@ final class ProductPayloadMapper {
87
87
  List<ProductDetails.PricingPhase> phases =
88
88
  offerDetails.getPricingPhases() == null ? List.of() : offerDetails.getPricingPhases().getPricingPhaseList();
89
89
 
90
+ ProductDetails.InstallmentPlanDetails installmentPlanDetails = offerDetails.getInstallmentPlanDetails();
91
+ if (installmentPlanDetails != null) {
92
+ int commitmentPayments = installmentPlanDetails.getInstallmentPlanCommitmentPaymentsCount();
93
+ if (commitmentPayments > 0) {
94
+ product.put("subscriptionBillingCycles", commitmentPayments);
95
+ }
96
+ }
97
+
90
98
  ProductDetails.PricingPhase standardPhase = findStandardPricingPhase(phases);
91
99
  if (standardPhase != null) {
92
100
  double price = standardPhase.getPriceAmountMicros() / 1_000_000.0;
@@ -94,6 +102,12 @@ final class ProductPayloadMapper {
94
102
  product.put("priceString", standardPhase.getFormattedPrice());
95
103
  product.put("currencyCode", standardPhase.getPriceCurrencyCode());
96
104
  product.put("currencySymbol", currencySymbol(standardPhase.getPriceCurrencyCode()));
105
+ int recurrenceMode = standardPhase.getRecurrenceMode();
106
+ if (recurrenceMode == RECURRENCE_MODE_INFINITE_RECURRING) {
107
+ product.put("subscriptionPeriod", subscriptionPeriodFromBillingPeriod(standardPhase.getBillingPeriod()));
108
+ } else if (recurrenceMode == RECURRENCE_MODE_FINITE_RECURRING && installmentPlanDetails != null) {
109
+ product.put("subscriptionPeriod", subscriptionPeriodFromBillingPeriod(standardPhase.getBillingPeriod()));
110
+ }
97
111
  }
98
112
 
99
113
  String currencyCode = standardPhase != null ? standardPhase.getPriceCurrencyCode() : product.getString("currencyCode", "");