@capgo/native-purchases 8.9.7 → 8.9.9
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 +151 -40
- package/android/build.gradle +1 -0
- package/android/src/main/java/ee/forgr/nativepurchases/NativePurchasesPlugin.java +114 -34
- package/android/src/main/java/ee/forgr/nativepurchases/ProductPayloadMapper.java +14 -0
- package/android/src/main/java/ee/forgr/nativepurchases/SubscriptionOfferSelector.java +136 -0
- package/dist/docs.json +32 -16
- package/dist/esm/definitions.d.ts +68 -12
- package/dist/esm/definitions.js.map +1 -1
- package/dist/plugin.cjs.js.map +1 -1
- package/dist/plugin.js.map +1 -1
- package/ios/Sources/NativePurchasesPlugin/NativePurchasesPlugin+TransactionFinishing.swift +1 -1
- package/ios/Sources/NativePurchasesPlugin/NativePurchasesPlugin.swift +1 -1
- package/package.json +1 -1
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**:
|
|
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
|
|
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
|
|
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 (
|
|
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
|
|
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, //
|
|
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
|
|
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, //
|
|
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 (
|
|
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
|
|
566
|
-
const
|
|
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
|
-
//
|
|
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:
|
|
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 (
|
|
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, //
|
|
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 (
|
|
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 |
|
|
@@ -2302,7 +2412,7 @@ which is useful for determining if users are entitled to features from earlier b
|
|
|
2302
2412
|
| **`isInIntroPricePeriod`** | <code>boolean</code> | Whether the transaction is in an introductory price period. Introductory pricing is a discounted rate, different from a free trial. - `true`: Currently using introductory pricing - `false`: Not in intro period | | 1.0.0 |
|
|
2303
2413
|
| **`isInGracePeriod`** | <code>boolean</code> | Whether the transaction is in a grace period. Grace period allows users to fix payment issues while maintaining access. You typically want to continue providing access during this time. - `true`: Subscription payment failed but user still has access - `false`: Not in grace period | | 1.0.0 |
|
|
2304
2414
|
| **`needsFinish`** | <code>boolean</code> | Whether the StoreKit transaction still needs to be finished with `finishTransaction()`. Present when the transaction is returned from `getUnfinishedTransactions()` or from `transactionUpdated` while `autoFinishTransactions` is `false`. | | 8.9.0 |
|
|
2305
|
-
| **`verificationError`** | <code>string</code> | Why StoreKit could not verify this transaction. Treat the transaction as untrusted and do not grant entitlements from it. Present only on unverified entries returned by `getUnfinishedTransactions({ includeUnverified: true })`. | | 8.
|
|
2415
|
+
| **`verificationError`** | <code>string</code> | Why StoreKit could not verify this transaction. Treat the transaction as untrusted and do not grant entitlements from it. Present only on unverified entries returned by `getUnfinishedTransactions({ includeUnverified: true })`. | | 8.9.7 |
|
|
2306
2416
|
|
|
2307
2417
|
|
|
2308
2418
|
#### TransactionCommitmentInfo
|
|
@@ -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
|
|
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.
|
|
2362
|
-
| **`subscriptionPeriod`** | <code><a href="#subscriptionperiod">SubscriptionPeriod</a></code> |
|
|
2363
|
-
| **`
|
|
2364
|
-
| **`
|
|
2365
|
-
| **`
|
|
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
|
package/android/build.gradle
CHANGED
|
@@ -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
|
-
|
|
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.9";
|
|
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;
|
|
@@ -154,6 +214,14 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
154
214
|
}
|
|
155
215
|
}
|
|
156
216
|
|
|
217
|
+
/**
|
|
218
|
+
* Maps the {@code productType} passed to purchaseProduct to the value it was bought as.
|
|
219
|
+
* Matches purchaseProduct, which defaults to inapp and treats anything else as a subscription.
|
|
220
|
+
*/
|
|
221
|
+
static String responseProductType(String requestedProductType) {
|
|
222
|
+
return requestedProductType == null || requestedProductType.equals("inapp") ? "inapp" : "subs";
|
|
223
|
+
}
|
|
224
|
+
|
|
157
225
|
private static String formatUtcIso8601(long timeMillis) {
|
|
158
226
|
java.text.SimpleDateFormat purchaseDateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", java.util.Locale.US);
|
|
159
227
|
purchaseDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
|
|
@@ -307,6 +375,19 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
307
375
|
}
|
|
308
376
|
}
|
|
309
377
|
|
|
378
|
+
/**
|
|
379
|
+
* Reject a purchase whose {@code offerToken} matched no current offer.
|
|
380
|
+
*
|
|
381
|
+
* Shared by the subscription and one-time paths because `definitions.ts`
|
|
382
|
+
* documents that rejection as one rule covering both product types, so
|
|
383
|
+
* the two must not drift apart in wording.
|
|
384
|
+
*/
|
|
385
|
+
private void rejectOfferTokenNotFound(PluginCall call, String productIdentifier) {
|
|
386
|
+
NativePurchasesLog.d(TAG, "Offer token not found for product: " + productIdentifier);
|
|
387
|
+
closeBillingClient();
|
|
388
|
+
call.reject("Offer token not found for product: " + productIdentifier);
|
|
389
|
+
}
|
|
390
|
+
|
|
310
391
|
private void closeBillingClientLocked() {
|
|
311
392
|
NativePurchasesLog.d(TAG, "closeBillingClient() called");
|
|
312
393
|
if (billingClient != null) {
|
|
@@ -438,7 +519,7 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
438
519
|
ret.put("productIdentifier", purchase.getProducts().get(0));
|
|
439
520
|
ret.put("purchaseDate", formatUtcIso8601(purchase.getPurchaseTime()));
|
|
440
521
|
ret.put("quantity", purchase.getQuantity());
|
|
441
|
-
ret.put("productType",
|
|
522
|
+
ret.put("productType", responseProductType(purchaseCall != null ? purchaseCall.getString("productType") : null));
|
|
442
523
|
ret.put("orderId", purchase.getOrderId());
|
|
443
524
|
ret.put("purchaseToken", purchase.getPurchaseToken());
|
|
444
525
|
ret.put("isAcknowledged", purchase.isAcknowledged());
|
|
@@ -450,15 +531,6 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
450
531
|
// This would require additional Google Play API calls to get detailed subscription status
|
|
451
532
|
ret.put("willCancel", null); // Default to null, would need API call to determine actual cancellation date
|
|
452
533
|
|
|
453
|
-
// For subscriptions, try to get additional information
|
|
454
|
-
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED && purchase.getProducts().get(0).contains("sub")) {
|
|
455
|
-
// Note: Android doesn't provide direct expiration date in Purchase object
|
|
456
|
-
// This would need to be calculated based on subscription period or fetched from Google Play API
|
|
457
|
-
ret.put("productType", "subs");
|
|
458
|
-
// For subscriptions, we can't get expiration date directly from Purchase object
|
|
459
|
-
// This would require additional Google Play API calls to get subscription details
|
|
460
|
-
}
|
|
461
|
-
|
|
462
534
|
NativePurchasesLog.d(TAG, "Resolving purchase call for product: " + purchase.getProducts().get(0));
|
|
463
535
|
if (purchaseCall != null) {
|
|
464
536
|
purchaseCall.resolve(ret);
|
|
@@ -755,10 +827,13 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
755
827
|
call.reject("productType is empty");
|
|
756
828
|
return;
|
|
757
829
|
}
|
|
758
|
-
|
|
759
|
-
|
|
830
|
+
boolean hasOfferToken = offerToken != null && !offerToken.isEmpty();
|
|
831
|
+
if (productType.equals("subs") && !SubscriptionOfferSelector.canSelect(planIdentifier, offerToken)) {
|
|
832
|
+
// The caller named no offer at all. SubscriptionOfferSelector owns
|
|
833
|
+
// this rule: see canSelect for why either value alone is enough,
|
|
834
|
+
// and for what it deliberately does not catch.
|
|
760
835
|
NativePurchasesLog.d(TAG, "Error: planIdentifier cannot be empty if productType is subs");
|
|
761
|
-
call.reject("planIdentifier cannot be empty if productType is subs");
|
|
836
|
+
call.reject("planIdentifier cannot be empty if productType is subs unless offerToken is provided");
|
|
762
837
|
return;
|
|
763
838
|
}
|
|
764
839
|
assert quantity != null;
|
|
@@ -820,35 +895,42 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
820
895
|
BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(productDetailsItem);
|
|
821
896
|
if (productType.equals("subs")) {
|
|
822
897
|
NativePurchasesLog.d(TAG, "Processing subscription product");
|
|
823
|
-
//
|
|
824
|
-
|
|
825
|
-
|
|
898
|
+
// Prefer an explicit offerToken, then the planIdentifier's base
|
|
899
|
+
// plan, then the first offer. See SubscriptionOfferSelector.
|
|
900
|
+
List<ProductDetails.SubscriptionOfferDetails> subscriptionOffers =
|
|
901
|
+
productDetailsItem.getSubscriptionOfferDetails();
|
|
826
902
|
NativePurchasesLog.d(
|
|
827
903
|
TAG,
|
|
828
|
-
"Available offer details count: " +
|
|
904
|
+
"Available offer details count: " + (subscriptionOffers == null ? 0 : subscriptionOffers.size())
|
|
829
905
|
);
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
906
|
+
|
|
907
|
+
SubscriptionOfferPurchaseResult subscriptionSelection = resolveSubscriptionOfferForPurchase(
|
|
908
|
+
subscriptionOffers,
|
|
909
|
+
planIdentifier,
|
|
910
|
+
offerToken
|
|
911
|
+
);
|
|
912
|
+
if (subscriptionSelection.outcome == SubscriptionOfferPurchaseOutcome.NO_OFFERS) {
|
|
913
|
+
NativePurchasesLog.w(TAG, "No subscription offer details found for product: " + productIdentifier);
|
|
914
|
+
closeBillingClient();
|
|
915
|
+
call.reject("No subscription offer details found for product: " + productIdentifier);
|
|
916
|
+
return;
|
|
837
917
|
}
|
|
838
|
-
if (
|
|
839
|
-
|
|
840
|
-
|
|
918
|
+
if (subscriptionSelection.outcome == SubscriptionOfferPurchaseOutcome.OFFER_TOKEN_NOT_FOUND) {
|
|
919
|
+
rejectOfferTokenNotFound(call, productIdentifier);
|
|
920
|
+
return;
|
|
841
921
|
}
|
|
842
|
-
|
|
922
|
+
|
|
923
|
+
NativePurchasesLog.d(TAG, "Selected base plan: " + subscriptionSelection.basePlanId);
|
|
924
|
+
productDetailsParams.setOfferToken(subscriptionSelection.offerToken);
|
|
843
925
|
NativePurchasesLog.d(
|
|
844
926
|
TAG,
|
|
845
|
-
"Set offer token: " + NativePurchasesLog.redactSensitive(
|
|
927
|
+
"Set offer token: " + NativePurchasesLog.redactSensitive(subscriptionSelection.offerToken)
|
|
846
928
|
);
|
|
847
929
|
} else if (productType.equals("inapp")) {
|
|
848
930
|
NativePurchasesLog.d(TAG, "Processing in-app product");
|
|
849
931
|
List<ProductDetails.OneTimePurchaseOfferDetails> oneTimeOffers =
|
|
850
932
|
ProductPayloadMapper.resolveOneTimePurchaseOffers(productDetailsItem);
|
|
851
|
-
if (
|
|
933
|
+
if (hasOfferToken) {
|
|
852
934
|
ProductDetails.OneTimePurchaseOfferDetails selectedOffer = null;
|
|
853
935
|
for (ProductDetails.OneTimePurchaseOfferDetails offerDetails : oneTimeOffers) {
|
|
854
936
|
if (offerToken.equals(offerDetails.getOfferToken())) {
|
|
@@ -857,9 +939,7 @@ public class NativePurchasesPlugin extends Plugin {
|
|
|
857
939
|
}
|
|
858
940
|
}
|
|
859
941
|
if (selectedOffer == null) {
|
|
860
|
-
|
|
861
|
-
closeBillingClient();
|
|
862
|
-
call.reject("Offer token not found for product: " + productIdentifier);
|
|
942
|
+
rejectOfferTokenNotFound(call, productIdentifier);
|
|
863
943
|
return;
|
|
864
944
|
}
|
|
865
945
|
productDetailsParams.setOfferToken(selectedOffer.getOfferToken());
|