@capgo/native-purchases 8.0.12 → 8.0.14
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/Package.swift +1 -1
- package/README.md +263 -34
- package/android/src/main/java/ee/forgr/nativepurchases/NativePurchasesPlugin.java +1 -1
- package/dist/docs.json +15 -3
- package/dist/esm/definitions.d.ts +58 -0
- package/dist/esm/definitions.js.map +1 -1
- package/ios/Sources/NativePurchasesPlugin/NativePurchasesPlugin.swift +1 -1
- package/package.json +1 -1
package/Package.swift
CHANGED
|
@@ -10,7 +10,7 @@ let package = Package(
|
|
|
10
10
|
targets: ["NativePurchasesPlugin"])
|
|
11
11
|
],
|
|
12
12
|
dependencies: [
|
|
13
|
-
.package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.
|
|
13
|
+
.package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.1")
|
|
14
14
|
],
|
|
15
15
|
targets: [
|
|
16
16
|
.target(
|
package/README.md
CHANGED
|
@@ -447,12 +447,24 @@ const buyInAppProduct = async () => {
|
|
|
447
447
|
|
|
448
448
|
alert('Purchase successful! Transaction ID: ' + result.transactionId);
|
|
449
449
|
|
|
450
|
-
//
|
|
450
|
+
// Access the full receipt data for backend validation
|
|
451
451
|
if (result.receipt) {
|
|
452
|
-
//
|
|
452
|
+
// iOS: Base64-encoded StoreKit receipt - send this to your backend
|
|
453
|
+
console.log('iOS Receipt (base64):', result.receipt);
|
|
453
454
|
await validateReceipt(result.receipt);
|
|
454
455
|
}
|
|
455
456
|
|
|
457
|
+
if (result.jwsRepresentation) {
|
|
458
|
+
// iOS: StoreKit 2 JWS representation - alternative to receipt
|
|
459
|
+
console.log('iOS JWS:', result.jwsRepresentation);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
if (result.purchaseToken) {
|
|
463
|
+
// Android: Purchase token - send this to your backend
|
|
464
|
+
console.log('Android Purchase Token:', result.purchaseToken);
|
|
465
|
+
await validatePurchaseToken(result.purchaseToken, result.productIdentifier);
|
|
466
|
+
}
|
|
467
|
+
|
|
456
468
|
} catch (error) {
|
|
457
469
|
alert('Purchase failed: ' + error.message);
|
|
458
470
|
}
|
|
@@ -493,12 +505,24 @@ const buySubscription = async () => {
|
|
|
493
505
|
|
|
494
506
|
alert('Subscription successful! Transaction ID: ' + result.transactionId);
|
|
495
507
|
|
|
496
|
-
//
|
|
508
|
+
// Access the full receipt data for backend validation
|
|
497
509
|
if (result.receipt) {
|
|
498
|
-
//
|
|
510
|
+
// iOS: Base64-encoded StoreKit receipt - send this to your backend
|
|
511
|
+
console.log('iOS Receipt (base64):', result.receipt);
|
|
499
512
|
await validateReceipt(result.receipt);
|
|
500
513
|
}
|
|
501
514
|
|
|
515
|
+
if (result.jwsRepresentation) {
|
|
516
|
+
// iOS: StoreKit 2 JWS representation - alternative to receipt
|
|
517
|
+
console.log('iOS JWS:', result.jwsRepresentation);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
if (result.purchaseToken) {
|
|
521
|
+
// Android: Purchase token - send this to your backend
|
|
522
|
+
console.log('Android Purchase Token:', result.purchaseToken);
|
|
523
|
+
await validatePurchaseToken(result.purchaseToken, result.productIdentifier);
|
|
524
|
+
}
|
|
525
|
+
|
|
502
526
|
} catch (error) {
|
|
503
527
|
alert('Subscription failed: ' + error.message);
|
|
504
528
|
}
|
|
@@ -1216,12 +1240,65 @@ await NativePurchases.getPluginVersion();
|
|
|
1216
1240
|
|
|
1217
1241
|
## Backend Validation
|
|
1218
1242
|
|
|
1219
|
-
|
|
1243
|
+
### ✅ Full Receipt Data Access
|
|
1244
|
+
|
|
1245
|
+
**This plugin provides complete access to verified receipt data for server-side validation.** You get all the information needed to validate purchases with Apple and Google servers.
|
|
1246
|
+
|
|
1247
|
+
**For iOS:**
|
|
1248
|
+
- ✅ `transaction.receipt` - Complete base64-encoded StoreKit receipt (for Apple's receipt verification API)
|
|
1249
|
+
- ✅ `transaction.jwsRepresentation` - StoreKit 2 JSON Web Signature (for App Store Server API v2)
|
|
1250
|
+
|
|
1251
|
+
**For Android:**
|
|
1252
|
+
- ✅ `transaction.purchaseToken` - Google Play purchase token (for Google Play Developer API)
|
|
1253
|
+
- ✅ `transaction.orderId` - Google Play order identifier
|
|
1254
|
+
|
|
1255
|
+
These fields contain the **full verified receipt payload** that you can send directly to your backend for validation with Apple's and Google's servers.
|
|
1256
|
+
|
|
1257
|
+
#### Migrating from cordova-plugin-purchase?
|
|
1258
|
+
|
|
1259
|
+
If you're coming from cordova-plugin-purchase, here's the mapping:
|
|
1260
|
+
|
|
1261
|
+
| cordova-plugin-purchase | @capgo/native-purchases | Platform | Notes |
|
|
1262
|
+
|-------------------------|-------------------------|----------|-------|
|
|
1263
|
+
| `transaction.transactionReceipt` | `transaction.receipt` (base64) | iOS | Legacy StoreKit receipt format (same value as Cordova) |
|
|
1264
|
+
| — | `transaction.jwsRepresentation` (JWS) | iOS | StoreKit 2 JWS format (iOS 15+, additional field with no Cordova equivalent; Apple's recommended modern format for new implementations) |
|
|
1265
|
+
| `transaction.purchaseToken` | `transaction.purchaseToken` | Android | Same field name |
|
|
1266
|
+
|
|
1267
|
+
**This plugin already exposes everything you need for backend verification!** The `receipt` and `purchaseToken` fields contain the complete verified receipt data, and `jwsRepresentation` provides an additional StoreKit 2 representation when available.
|
|
1268
|
+
|
|
1269
|
+
**Note:** On iOS, `jwsRepresentation` is only available for StoreKit 2 transactions (iOS 15+) and is Apple's recommended modern format. For maximum compatibility, use `receipt` which works on all iOS versions; when available, you can also send `jwsRepresentation` to backends that support App Store Server API v2.
|
|
1270
|
+
|
|
1271
|
+
### Why Backend Validation?
|
|
1272
|
+
|
|
1273
|
+
It's crucial to validate receipts on your server to ensure the integrity of purchases. Client-side data can be manipulated, but server-side validation with Apple/Google servers ensures purchases are legitimate.
|
|
1274
|
+
|
|
1275
|
+
### Receipt Data Available for Backend Verification
|
|
1220
1276
|
|
|
1221
|
-
|
|
1277
|
+
The `Transaction` object returned by `purchaseProduct()`, `getPurchases()`, and `restorePurchases()` includes all data needed for server-side validation:
|
|
1278
|
+
|
|
1279
|
+
**iOS Receipt Data:**
|
|
1280
|
+
- **`receipt`** - Base64-encoded StoreKit receipt (legacy format, works with Apple's receipt verification API)
|
|
1281
|
+
- **`jwsRepresentation`** - JSON Web Signature for StoreKit 2 (recommended for new implementations, works with App Store Server API)
|
|
1282
|
+
- **`transactionId`** - Unique transaction identifier
|
|
1283
|
+
|
|
1284
|
+
**Android Receipt Data:**
|
|
1285
|
+
- **`purchaseToken`** - Google Play purchase token (required for server-side validation)
|
|
1286
|
+
- **`orderId`** - Google Play order identifier
|
|
1287
|
+
- **`transactionId`** - Alias for purchaseToken
|
|
1288
|
+
|
|
1289
|
+
**All platforms include:**
|
|
1290
|
+
- `productIdentifier` - The product that was purchased
|
|
1291
|
+
- `purchaseDate` - When the purchase occurred
|
|
1292
|
+
- Additional metadata like `appAccountToken`, `quantity`, etc.
|
|
1293
|
+
|
|
1294
|
+
### Complete Backend Validation Example
|
|
1295
|
+
|
|
1296
|
+
#### Cloudflare Worker Setup
|
|
1222
1297
|
Create a new Cloudflare Worker and follow the instructions in folder (`validator`)[/validator/README.md]
|
|
1223
1298
|
|
|
1224
|
-
|
|
1299
|
+
#### Client-Side Implementation
|
|
1300
|
+
|
|
1301
|
+
Here's how to access the receipt data and send it to your backend for validation:
|
|
1225
1302
|
|
|
1226
1303
|
```typescript
|
|
1227
1304
|
import { Capacitor } from '@capacitor/core';
|
|
@@ -1284,18 +1361,40 @@ class Store {
|
|
|
1284
1361
|
|
|
1285
1362
|
private async validatePurchaseOnServer(transaction: Transaction) {
|
|
1286
1363
|
const serverUrl = 'https://your-server-url.com/validate-purchase';
|
|
1364
|
+
const platform = Capacitor.getPlatform();
|
|
1365
|
+
|
|
1287
1366
|
try {
|
|
1367
|
+
// Prepare receipt data based on platform
|
|
1368
|
+
const receiptData = platform === 'ios'
|
|
1369
|
+
? {
|
|
1370
|
+
// iOS: Send the full receipt (base64 encoded) or JWS representation
|
|
1371
|
+
receipt: transaction.receipt, // StoreKit receipt (base64)
|
|
1372
|
+
jwsRepresentation: transaction.jwsRepresentation, // StoreKit 2 JWS (optional, recommended for new apps)
|
|
1373
|
+
transactionId: transaction.transactionId,
|
|
1374
|
+
platform: 'ios'
|
|
1375
|
+
}
|
|
1376
|
+
: {
|
|
1377
|
+
// Android: Send the purchase token and order ID
|
|
1378
|
+
purchaseToken: transaction.purchaseToken, // Required for Google Play validation
|
|
1379
|
+
orderId: transaction.orderId, // Google Play order ID
|
|
1380
|
+
transactionId: transaction.transactionId,
|
|
1381
|
+
platform: 'android'
|
|
1382
|
+
};
|
|
1383
|
+
|
|
1288
1384
|
const response = await axios.post(serverUrl, {
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1385
|
+
...receiptData,
|
|
1386
|
+
productId: transaction.productIdentifier,
|
|
1387
|
+
purchaseDate: transaction.purchaseDate,
|
|
1388
|
+
// Include user ID or other app-specific data
|
|
1389
|
+
userId: 'your-user-id'
|
|
1292
1390
|
});
|
|
1293
1391
|
|
|
1294
1392
|
console.log('Server validation response:', response.data);
|
|
1295
|
-
|
|
1393
|
+
return response.data;
|
|
1296
1394
|
} catch (error) {
|
|
1297
1395
|
console.error('Error in server-side validation:', error);
|
|
1298
1396
|
// Implement retry logic or notify the user if necessary
|
|
1397
|
+
throw error;
|
|
1299
1398
|
}
|
|
1300
1399
|
}
|
|
1301
1400
|
}
|
|
@@ -1317,7 +1416,7 @@ try {
|
|
|
1317
1416
|
}
|
|
1318
1417
|
```
|
|
1319
1418
|
|
|
1320
|
-
Now, let's look at how the server-side (Node.js) code
|
|
1419
|
+
Now, let's look at how the server-side (Node.js) code handles the validation:
|
|
1321
1420
|
|
|
1322
1421
|
```typescript
|
|
1323
1422
|
import express from 'express';
|
|
@@ -1329,49 +1428,179 @@ app.use(express.json());
|
|
|
1329
1428
|
const CLOUDFLARE_WORKER_URL = 'https://your-cloudflare-worker-url.workers.dev';
|
|
1330
1429
|
|
|
1331
1430
|
app.post('/validate-purchase', async (req, res) => {
|
|
1332
|
-
const {
|
|
1431
|
+
const { platform, receipt, jwsRepresentation, purchaseToken, productId, userId } = req.body;
|
|
1333
1432
|
|
|
1334
1433
|
try {
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1434
|
+
let validationResponse;
|
|
1435
|
+
|
|
1436
|
+
if (platform === 'ios') {
|
|
1437
|
+
// iOS: Validate using receipt or JWS representation
|
|
1438
|
+
if (!receipt && !jwsRepresentation) {
|
|
1439
|
+
return res.status(400).json({
|
|
1440
|
+
success: false,
|
|
1441
|
+
error: 'Missing receipt data: either receipt or jwsRepresentation is required for iOS'
|
|
1442
|
+
});
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
// Option 1: Use legacy receipt validation (recommended for compatibility)
|
|
1446
|
+
if (receipt) {
|
|
1447
|
+
validationResponse = await axios.post(`${CLOUDFLARE_WORKER_URL}/apple`, {
|
|
1448
|
+
receipt: receipt, // Base64-encoded receipt from transaction.receipt
|
|
1449
|
+
password: 'your-app-shared-secret' // App-Specific Shared Secret from App Store Connect (required for auto-renewable subscriptions)
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
// Option 2: Use StoreKit 2 App Store Server API (recommended for new implementations)
|
|
1453
|
+
else if (jwsRepresentation) {
|
|
1454
|
+
// Validate JWS token with App Store Server API
|
|
1455
|
+
// Note: JWS verification requires decoding and validating the signature
|
|
1456
|
+
// Implementation depends on your backend setup - see Apple's documentation:
|
|
1457
|
+
// https://developer.apple.com/documentation/appstoreserverapi/jwstransaction
|
|
1458
|
+
validationResponse = await axios.post(`${CLOUDFLARE_WORKER_URL}/apple-jws`, {
|
|
1459
|
+
jws: jwsRepresentation
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
} else if (platform === 'android') {
|
|
1463
|
+
// Android: Validate using purchase token with Google Play Developer API
|
|
1464
|
+
if (!purchaseToken) {
|
|
1465
|
+
return res.status(400).json({
|
|
1466
|
+
success: false,
|
|
1467
|
+
error: 'Missing purchaseToken for Android validation'
|
|
1468
|
+
});
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
validationResponse = await axios.post(`${CLOUDFLARE_WORKER_URL}/google`, {
|
|
1472
|
+
purchaseToken: purchaseToken, // From transaction.purchaseToken
|
|
1473
|
+
productId: productId,
|
|
1474
|
+
packageName: 'com.yourapp.package'
|
|
1475
|
+
});
|
|
1476
|
+
} else {
|
|
1477
|
+
return res.status(400).json({
|
|
1478
|
+
success: false,
|
|
1479
|
+
error: 'Invalid platform'
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1339
1482
|
|
|
1340
1483
|
const validationResult = validationResponse.data;
|
|
1341
1484
|
|
|
1342
1485
|
// Process the validation result
|
|
1343
1486
|
if (validationResult.isValid) {
|
|
1344
1487
|
// Update user status in the database
|
|
1345
|
-
|
|
1488
|
+
await updateUserPurchase(userId, {
|
|
1489
|
+
productId,
|
|
1490
|
+
platform,
|
|
1491
|
+
transactionId: req.body.transactionId,
|
|
1492
|
+
validated: true,
|
|
1493
|
+
validatedAt: new Date(),
|
|
1494
|
+
receiptData: validationResult
|
|
1495
|
+
});
|
|
1346
1496
|
|
|
1347
|
-
|
|
1348
|
-
console.log(`Purchase validated for transaction ${transactionId}`);
|
|
1497
|
+
console.log(`Purchase validated for user ${userId}, product ${productId}`);
|
|
1349
1498
|
|
|
1350
|
-
|
|
1351
|
-
|
|
1499
|
+
res.json({
|
|
1500
|
+
success: true,
|
|
1501
|
+
validated: true,
|
|
1502
|
+
message: 'Purchase successfully validated'
|
|
1503
|
+
});
|
|
1352
1504
|
} else {
|
|
1353
1505
|
// Handle invalid purchase
|
|
1354
|
-
console.warn(`Invalid purchase detected for
|
|
1355
|
-
|
|
1356
|
-
//
|
|
1506
|
+
console.warn(`Invalid purchase detected for user ${userId}`);
|
|
1507
|
+
|
|
1508
|
+
// Flag for investigation but don't block the user immediately
|
|
1509
|
+
await flagSuspiciousPurchase(userId, req.body);
|
|
1510
|
+
|
|
1511
|
+
res.json({
|
|
1512
|
+
success: true, // Don't block the user
|
|
1513
|
+
validated: false,
|
|
1514
|
+
message: 'Purchase validation pending review'
|
|
1515
|
+
});
|
|
1357
1516
|
}
|
|
1358
1517
|
|
|
1359
|
-
// Always respond with a success to the app
|
|
1360
|
-
// This ensures the app doesn't block the user's access
|
|
1361
|
-
res.json({ success: true });
|
|
1362
1518
|
} catch (error) {
|
|
1363
1519
|
console.error('Error validating purchase:', error);
|
|
1520
|
+
|
|
1521
|
+
// Log the error for investigation
|
|
1522
|
+
await logValidationError(userId, req.body, error);
|
|
1523
|
+
|
|
1364
1524
|
// Still respond with success to the app
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1525
|
+
// This ensures the app doesn't block the user's access
|
|
1526
|
+
res.json({
|
|
1527
|
+
success: true,
|
|
1528
|
+
validated: 'pending',
|
|
1529
|
+
message: 'Validation will be retried'
|
|
1530
|
+
});
|
|
1368
1531
|
}
|
|
1369
1532
|
});
|
|
1370
1533
|
|
|
1534
|
+
// Helper function to update user purchase status
|
|
1535
|
+
async function updateUserPurchase(userId: string, purchaseData: any) {
|
|
1536
|
+
// Implement your database logic here
|
|
1537
|
+
console.log('Updating purchase for user:', userId);
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
// Helper function to flag suspicious purchases
|
|
1541
|
+
async function flagSuspiciousPurchase(userId: string, purchaseData: any) {
|
|
1542
|
+
// Implement your logic to flag and review suspicious purchases
|
|
1543
|
+
console.log('Flagging suspicious purchase:', userId);
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
// Helper function to log validation errors
|
|
1547
|
+
async function logValidationError(userId: string, purchaseData: any, error: any) {
|
|
1548
|
+
// Implement your error logging logic
|
|
1549
|
+
console.log('Logging validation error:', userId, error);
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1371
1552
|
// Start the server
|
|
1372
1553
|
app.listen(3000, () => console.log('Server running on port 3000'));
|
|
1373
1554
|
```
|
|
1374
1555
|
|
|
1556
|
+
### Alternative: Direct Store API Validation
|
|
1557
|
+
|
|
1558
|
+
Instead of using a Cloudflare Worker, you can validate directly with Apple and Google:
|
|
1559
|
+
|
|
1560
|
+
**iOS - Apple Receipt Verification API:**
|
|
1561
|
+
```typescript
|
|
1562
|
+
// Production: https://buy.itunes.apple.com/verifyReceipt
|
|
1563
|
+
// Sandbox: https://sandbox.itunes.apple.com/verifyReceipt
|
|
1564
|
+
|
|
1565
|
+
async function validateAppleReceipt(receiptData: string) {
|
|
1566
|
+
const response = await axios.post('https://buy.itunes.apple.com/verifyReceipt', {
|
|
1567
|
+
'receipt-data': receiptData,
|
|
1568
|
+
'password': 'your-shared-secret', // App-Specific Shared Secret from App Store Connect (required for auto-renewable subscriptions)
|
|
1569
|
+
'exclude-old-transactions': true
|
|
1570
|
+
});
|
|
1571
|
+
|
|
1572
|
+
return response.data;
|
|
1573
|
+
}
|
|
1574
|
+
```
|
|
1575
|
+
|
|
1576
|
+
**Android - Google Play Developer API:**
|
|
1577
|
+
```typescript
|
|
1578
|
+
// Requires Google Play Developer API credentials
|
|
1579
|
+
// See: https://developers.google.com/android-publisher/getting_started
|
|
1580
|
+
|
|
1581
|
+
import { google } from 'googleapis';
|
|
1582
|
+
|
|
1583
|
+
async function validateGooglePurchase(packageName: string, productId: string, purchaseToken: string) {
|
|
1584
|
+
const androidPublisher = google.androidpublisher('v3');
|
|
1585
|
+
|
|
1586
|
+
const auth = new google.auth.GoogleAuth({
|
|
1587
|
+
keyFile: 'path/to/service-account-key.json',
|
|
1588
|
+
scopes: ['https://www.googleapis.com/auth/androidpublisher'],
|
|
1589
|
+
});
|
|
1590
|
+
|
|
1591
|
+
const authClient = await auth.getClient();
|
|
1592
|
+
|
|
1593
|
+
const response = await androidPublisher.purchases.products.get({
|
|
1594
|
+
auth: authClient,
|
|
1595
|
+
packageName: packageName,
|
|
1596
|
+
productId: productId,
|
|
1597
|
+
token: purchaseToken
|
|
1598
|
+
});
|
|
1599
|
+
|
|
1600
|
+
return response.data;
|
|
1601
|
+
}
|
|
1602
|
+
```
|
|
1603
|
+
|
|
1375
1604
|
Key points about this approach:
|
|
1376
1605
|
|
|
1377
1606
|
1. The app immediately grants access after a successful purchase, ensuring a smooth user experience.
|
|
@@ -1746,8 +1975,8 @@ which is useful for determining if users are entitled to features from earlier b
|
|
|
1746
1975
|
| Prop | Type | Description | Default | Since |
|
|
1747
1976
|
| -------------------------- | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | ------ |
|
|
1748
1977
|
| **`transactionId`** | <code>string</code> | Unique identifier for the transaction. | | 1.0.0 |
|
|
1749
|
-
| **`receipt`** | <code>string</code> | Receipt data for validation (base64 encoded StoreKit receipt). Send this to your backend for server-side validation with Apple's receipt verification API. The receipt remains available even after refund - server validation is required to detect refunded transactions.
|
|
1750
|
-
| **`jwsRepresentation`** | <code>string</code> | StoreKit 2 JSON Web Signature (JWS) payload describing the verified transaction. Send this to your backend when using Apple's App Store Server API v2 instead of raw receipts. Only available when the transaction originated from StoreKit 2 APIs (e.g. <a href="#transaction">Transaction</a>.updates).
|
|
1978
|
+
| **`receipt`** | <code>string</code> | Receipt data for validation (base64 encoded StoreKit receipt). **This is the full verified receipt payload from Apple StoreKit.** Send this to your backend for server-side validation with Apple's receipt verification API. The receipt remains available even after refund - server validation is required to detect refunded transactions. **For backend validation:** - Use Apple's receipt verification API: https://buy.itunes.apple.com/verifyReceipt (production) - Or sandbox: https://sandbox.itunes.apple.com/verifyReceipt - This contains all transaction data needed for validation **Note:** Apple recommends migrating to App Store Server API v2 with `jwsRepresentation` for new implementations. The legacy receipt verification API continues to work but may be deprecated in the future. | | 1.0.0 |
|
|
1979
|
+
| **`jwsRepresentation`** | <code>string</code> | StoreKit 2 JSON Web Signature (JWS) payload describing the verified transaction. **This is the full verified receipt in JWS format (StoreKit 2).** Send this to your backend when using Apple's App Store Server API v2 instead of raw receipts. Only available when the transaction originated from StoreKit 2 APIs (e.g. <a href="#transaction">Transaction</a>.updates). **For backend validation:** - Use Apple's App Store Server API v2 to decode and verify the JWS - This is the modern alternative to the legacy receipt format - Contains signed transaction information from Apple | | 7.13.2 |
|
|
1751
1980
|
| **`appAccountToken`** | <code>string \| null</code> | An optional obfuscated identifier that uniquely associates the transaction with a user account in your app. PURPOSE: - Fraud detection: Helps platforms detect irregular activity (e.g., many devices purchasing on the same account) - User linking: Links purchases to in-game characters, avatars, or in-app profiles PLATFORM DIFFERENCES: - iOS: Must be a valid UUID format (e.g., "550e8400-e29b-41d4-a716-446655440000") Apple's StoreKit 2 requires UUID format for the appAccountToken parameter - Android: Can be any obfuscated string (max 64 chars), maps to Google Play's ObfuscatedAccountId Google recommends using encryption or one-way hash SECURITY REQUIREMENTS (especially for Android): - DO NOT store Personally Identifiable Information (PII) like emails in cleartext - Use encryption or a one-way hash to generate an obfuscated identifier - Maximum length: 64 characters (both platforms) - Storing PII in cleartext will result in purchases being blocked by Google Play IMPLEMENTATION EXAMPLE: ```typescript // For iOS: Generate a deterministic UUID from user ID import { v5 as uuidv5 } from 'uuid'; const NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; // Your app's namespace UUID const appAccountToken = uuidv5(userId, NAMESPACE); // For Android: Can also use UUID or any hashed value // The same UUID approach works for both platforms ``` | | |
|
|
1752
1981
|
| **`productIdentifier`** | <code>string</code> | <a href="#product">Product</a> identifier associated with the transaction. | | 1.0.0 |
|
|
1753
1982
|
| **`purchaseDate`** | <code>string</code> | Purchase date of the transaction in ISO 8601 format. | | 1.0.0 |
|
|
@@ -1761,7 +1990,7 @@ which is useful for determining if users are entitled to features from earlier b
|
|
|
1761
1990
|
| **`subscriptionState`** | <code>'unknown' \| 'subscribed' \| 'expired' \| 'revoked' \| 'inGracePeriod' \| 'inBillingRetryPeriod'</code> | Current subscription state reported by StoreKit. Possible values: - `"subscribed"`: Auto-renewing and in good standing - `"expired"`: Lapsed with no access - `"revoked"`: Access removed due to refund or issue - `"inGracePeriod"`: Payment issue but still in grace access window - `"inBillingRetryPeriod"`: StoreKit retrying failed billing - `"unknown"`: StoreKit did not report a state | | 7.13.2 |
|
|
1762
1991
|
| **`purchaseState`** | <code>string</code> | Purchase state of the transaction (numeric string value). **Android Values:** - `"1"`: Purchase completed and valid (PURCHASED state) - `"0"`: Payment pending (PENDING state, e.g., cash payment processing) - Other numeric values: Various other states Always check `purchaseState === "1"` on Android to verify a valid purchase. Refunded purchases typically disappear from getPurchases() rather than showing a different state. | | 1.0.0 |
|
|
1763
1992
|
| **`orderId`** | <code>string</code> | Order ID associated with the transaction. Use this for server-side verification on Android. This is the Google Play order ID. | | 1.0.0 |
|
|
1764
|
-
| **`purchaseToken`** | <code>string</code> | Purchase token associated with the transaction. Send this to your backend for server-side validation with Google Play Developer API. This is the Android equivalent of iOS's receipt field.
|
|
1993
|
+
| **`purchaseToken`** | <code>string</code> | Purchase token associated with the transaction. **This is the full verified purchase token from Google Play.** Send this to your backend for server-side validation with Google Play Developer API. This is the Android equivalent of iOS's receipt field. **For backend validation:** - Use Google Play Developer API v3 to verify the purchase - API endpoint: androidpublisher.purchases.products.get() or purchases.subscriptions.get() - This token contains all data needed for validation with Google servers - Can also be used for subscription status checks and cancellation detection | | 1.0.0 |
|
|
1765
1994
|
| **`isAcknowledged`** | <code>boolean</code> | Whether the purchase has been acknowledged. Purchases must be acknowledged within 3 days or they will be refunded. By default, this plugin automatically acknowledges purchases unless you set `autoAcknowledgePurchases: false` in purchaseProduct(). | | 1.0.0 |
|
|
1766
1995
|
| **`quantity`** | <code>number</code> | Quantity purchased. | <code>1</code> | 1.0.0 |
|
|
1767
1996
|
| **`productType`** | <code>string</code> | <a href="#product">Product</a> type. - `"inapp"`: One-time in-app purchase - `"subs"`: Subscription | | 1.0.0 |
|
|
@@ -42,7 +42,7 @@ import org.json.JSONArray;
|
|
|
42
42
|
@CapacitorPlugin(name = "NativePurchases")
|
|
43
43
|
public class NativePurchasesPlugin extends Plugin {
|
|
44
44
|
|
|
45
|
-
private final String pluginVersion = "8.0.
|
|
45
|
+
private final String pluginVersion = "8.0.14";
|
|
46
46
|
public static final String TAG = "NativePurchases";
|
|
47
47
|
private static final Phaser semaphoreReady = new Phaser(1);
|
|
48
48
|
private BillingClient billingClient;
|
package/dist/docs.json
CHANGED
|
@@ -619,9 +619,13 @@
|
|
|
619
619
|
{
|
|
620
620
|
"text": "android Not available (use purchaseToken instead)",
|
|
621
621
|
"name": "platform"
|
|
622
|
+
},
|
|
623
|
+
{
|
|
624
|
+
"text": "```typescript\nconst transaction = await NativePurchases.purchaseProduct({ ... });\nif (transaction.receipt) {\n // Send to your backend for validation\n await fetch('/api/validate-receipt', {\n method: 'POST',\n body: JSON.stringify({ receipt: transaction.receipt })\n });\n}\n```",
|
|
625
|
+
"name": "example"
|
|
622
626
|
}
|
|
623
627
|
],
|
|
624
|
-
"docs": "Receipt data for validation (base64 encoded StoreKit receipt).\n\nSend this to your backend for server-side validation with Apple's receipt verification API.\nThe receipt remains available even after refund - server validation is required to detect refunded transactions.",
|
|
628
|
+
"docs": "Receipt data for validation (base64 encoded StoreKit receipt).\n\n**This is the full verified receipt payload from Apple StoreKit.**\nSend this to your backend for server-side validation with Apple's receipt verification API.\nThe receipt remains available even after refund - server validation is required to detect refunded transactions.\n\n**For backend validation:**\n- Use Apple's receipt verification API: https://buy.itunes.apple.com/verifyReceipt (production)\n- Or sandbox: https://sandbox.itunes.apple.com/verifyReceipt\n- This contains all transaction data needed for validation\n\n**Note:** Apple recommends migrating to App Store Server API v2 with `jwsRepresentation` for new implementations.\nThe legacy receipt verification API continues to work but may be deprecated in the future.",
|
|
625
629
|
"complexTypes": [],
|
|
626
630
|
"type": "string | undefined"
|
|
627
631
|
},
|
|
@@ -639,9 +643,13 @@
|
|
|
639
643
|
{
|
|
640
644
|
"text": "android Not available",
|
|
641
645
|
"name": "platform"
|
|
646
|
+
},
|
|
647
|
+
{
|
|
648
|
+
"text": "```typescript\nconst transaction = await NativePurchases.purchaseProduct({ ... });\nif (transaction.jwsRepresentation) {\n // Send to your backend for validation with App Store Server API v2\n await fetch('/api/validate-jws', {\n method: 'POST',\n body: JSON.stringify({ jws: transaction.jwsRepresentation })\n });\n}\n```",
|
|
649
|
+
"name": "example"
|
|
642
650
|
}
|
|
643
651
|
],
|
|
644
|
-
"docs": "StoreKit 2 JSON Web Signature (JWS) payload describing the verified transaction.\n\nSend this to your backend when using Apple's App Store Server API v2 instead of raw receipts.\nOnly available when the transaction originated from StoreKit 2 APIs (e.g. Transaction.updates)
|
|
652
|
+
"docs": "StoreKit 2 JSON Web Signature (JWS) payload describing the verified transaction.\n\n**This is the full verified receipt in JWS format (StoreKit 2).**\nSend this to your backend when using Apple's App Store Server API v2 instead of raw receipts.\nOnly available when the transaction originated from StoreKit 2 APIs (e.g. Transaction.updates).\n\n**For backend validation:**\n- Use Apple's App Store Server API v2 to decode and verify the JWS\n- This is the modern alternative to the legacy receipt format\n- Contains signed transaction information from Apple",
|
|
645
653
|
"complexTypes": [],
|
|
646
654
|
"type": "string | undefined"
|
|
647
655
|
},
|
|
@@ -918,9 +926,13 @@
|
|
|
918
926
|
{
|
|
919
927
|
"text": "android Always present",
|
|
920
928
|
"name": "platform"
|
|
929
|
+
},
|
|
930
|
+
{
|
|
931
|
+
"text": "```typescript\nconst transaction = await NativePurchases.purchaseProduct({ ... });\nif (transaction.purchaseToken) {\n // Send to your backend for validation\n await fetch('/api/validate-purchase', {\n method: 'POST',\n body: JSON.stringify({\n purchaseToken: transaction.purchaseToken,\n productId: transaction.productIdentifier\n })\n });\n}\n```",
|
|
932
|
+
"name": "example"
|
|
921
933
|
}
|
|
922
934
|
],
|
|
923
|
-
"docs": "Purchase token associated with the transaction.\n\nSend this to your backend for server-side validation with Google Play Developer API.\nThis is the Android equivalent of iOS's receipt field.",
|
|
935
|
+
"docs": "Purchase token associated with the transaction.\n\n**This is the full verified purchase token from Google Play.**\nSend this to your backend for server-side validation with Google Play Developer API.\nThis is the Android equivalent of iOS's receipt field.\n\n**For backend validation:**\n- Use Google Play Developer API v3 to verify the purchase\n- API endpoint: androidpublisher.purchases.products.get() or purchases.subscriptions.get()\n- This token contains all data needed for validation with Google servers\n- Can also be used for subscription status checks and cancellation detection",
|
|
924
936
|
"complexTypes": [],
|
|
925
937
|
"type": "string | undefined"
|
|
926
938
|
},
|
|
@@ -132,23 +132,60 @@ export interface Transaction {
|
|
|
132
132
|
/**
|
|
133
133
|
* Receipt data for validation (base64 encoded StoreKit receipt).
|
|
134
134
|
*
|
|
135
|
+
* **This is the full verified receipt payload from Apple StoreKit.**
|
|
135
136
|
* Send this to your backend for server-side validation with Apple's receipt verification API.
|
|
136
137
|
* The receipt remains available even after refund - server validation is required to detect refunded transactions.
|
|
137
138
|
*
|
|
139
|
+
* **For backend validation:**
|
|
140
|
+
* - Use Apple's receipt verification API: https://buy.itunes.apple.com/verifyReceipt (production)
|
|
141
|
+
* - Or sandbox: https://sandbox.itunes.apple.com/verifyReceipt
|
|
142
|
+
* - This contains all transaction data needed for validation
|
|
143
|
+
*
|
|
144
|
+
* **Note:** Apple recommends migrating to App Store Server API v2 with `jwsRepresentation` for new implementations.
|
|
145
|
+
* The legacy receipt verification API continues to work but may be deprecated in the future.
|
|
146
|
+
*
|
|
138
147
|
* @since 1.0.0
|
|
139
148
|
* @platform ios Always present
|
|
140
149
|
* @platform android Not available (use purchaseToken instead)
|
|
150
|
+
* @example
|
|
151
|
+
* ```typescript
|
|
152
|
+
* const transaction = await NativePurchases.purchaseProduct({ ... });
|
|
153
|
+
* if (transaction.receipt) {
|
|
154
|
+
* // Send to your backend for validation
|
|
155
|
+
* await fetch('/api/validate-receipt', {
|
|
156
|
+
* method: 'POST',
|
|
157
|
+
* body: JSON.stringify({ receipt: transaction.receipt })
|
|
158
|
+
* });
|
|
159
|
+
* }
|
|
160
|
+
* ```
|
|
141
161
|
*/
|
|
142
162
|
readonly receipt?: string;
|
|
143
163
|
/**
|
|
144
164
|
* StoreKit 2 JSON Web Signature (JWS) payload describing the verified transaction.
|
|
145
165
|
*
|
|
166
|
+
* **This is the full verified receipt in JWS format (StoreKit 2).**
|
|
146
167
|
* Send this to your backend when using Apple's App Store Server API v2 instead of raw receipts.
|
|
147
168
|
* Only available when the transaction originated from StoreKit 2 APIs (e.g. Transaction.updates).
|
|
148
169
|
*
|
|
170
|
+
* **For backend validation:**
|
|
171
|
+
* - Use Apple's App Store Server API v2 to decode and verify the JWS
|
|
172
|
+
* - This is the modern alternative to the legacy receipt format
|
|
173
|
+
* - Contains signed transaction information from Apple
|
|
174
|
+
*
|
|
149
175
|
* @since 7.13.2
|
|
150
176
|
* @platform ios Present for StoreKit 2 transactions (iOS 15+)
|
|
151
177
|
* @platform android Not available
|
|
178
|
+
* @example
|
|
179
|
+
* ```typescript
|
|
180
|
+
* const transaction = await NativePurchases.purchaseProduct({ ... });
|
|
181
|
+
* if (transaction.jwsRepresentation) {
|
|
182
|
+
* // Send to your backend for validation with App Store Server API v2
|
|
183
|
+
* await fetch('/api/validate-jws', {
|
|
184
|
+
* method: 'POST',
|
|
185
|
+
* body: JSON.stringify({ jws: transaction.jwsRepresentation })
|
|
186
|
+
* });
|
|
187
|
+
* }
|
|
188
|
+
* ```
|
|
152
189
|
*/
|
|
153
190
|
readonly jwsRepresentation?: string;
|
|
154
191
|
/**
|
|
@@ -325,12 +362,33 @@ export interface Transaction {
|
|
|
325
362
|
/**
|
|
326
363
|
* Purchase token associated with the transaction.
|
|
327
364
|
*
|
|
365
|
+
* **This is the full verified purchase token from Google Play.**
|
|
328
366
|
* Send this to your backend for server-side validation with Google Play Developer API.
|
|
329
367
|
* This is the Android equivalent of iOS's receipt field.
|
|
330
368
|
*
|
|
369
|
+
* **For backend validation:**
|
|
370
|
+
* - Use Google Play Developer API v3 to verify the purchase
|
|
371
|
+
* - API endpoint: androidpublisher.purchases.products.get() or purchases.subscriptions.get()
|
|
372
|
+
* - This token contains all data needed for validation with Google servers
|
|
373
|
+
* - Can also be used for subscription status checks and cancellation detection
|
|
374
|
+
*
|
|
331
375
|
* @since 1.0.0
|
|
332
376
|
* @platform ios Not available (use receipt instead)
|
|
333
377
|
* @platform android Always present
|
|
378
|
+
* @example
|
|
379
|
+
* ```typescript
|
|
380
|
+
* const transaction = await NativePurchases.purchaseProduct({ ... });
|
|
381
|
+
* if (transaction.purchaseToken) {
|
|
382
|
+
* // Send to your backend for validation
|
|
383
|
+
* await fetch('/api/validate-purchase', {
|
|
384
|
+
* method: 'POST',
|
|
385
|
+
* body: JSON.stringify({
|
|
386
|
+
* purchaseToken: transaction.purchaseToken,
|
|
387
|
+
* productId: transaction.productIdentifier
|
|
388
|
+
* })
|
|
389
|
+
* });
|
|
390
|
+
* }
|
|
391
|
+
* ```
|
|
334
392
|
*/
|
|
335
393
|
readonly purchaseToken?: string;
|
|
336
394
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"AAEA,MAAM,CAAN,IAAY,mBAOX;AAPD,WAAY,mBAAmB;IAC7B,qFAAoB,CAAA;IACpB,iEAAU,CAAA;IACV,uEAAa,CAAA;IACb,iEAAU,CAAA;IACV,iEAAU,CAAA;IACV,qEAAY,CAAA;AACd,CAAC,EAPW,mBAAmB,KAAnB,mBAAmB,QAO9B;AAED,MAAM,CAAN,IAAY,aAUX;AAVD,WAAY,aAAa;IACvB;;OAEG;IACH,gCAAe,CAAA;IAEf;;OAEG;IACH,8BAAa,CAAA;AACf,CAAC,EAVW,aAAa,KAAb,aAAa,QAUxB;AAED;;;;GAIG;AACH,MAAM,CAAN,IAAY,eAyBX;AAzBD,WAAY,eAAe;IACzB;;OAEG;IACH,uEAAa,CAAA;IAEb;;OAEG;IACH,qFAAoB,CAAA;IAEpB;;OAEG;IACH,iFAAkB,CAAA;IAElB;;OAEG;IACH,mFAAmB,CAAA;IAEnB;;OAEG;IACH,+FAAyB,CAAA;AAC3B,CAAC,EAzBW,eAAe,KAAf,eAAe,QAyB1B;AACD,MAAM,CAAN,IAAY,cA2BX;AA3BD,WAAY,cAAc;IACxB,qIAAiD,CAAA;IAEjD;;;OAGG;IACH,qGAAiC,CAAA;IAEjC;;;;OAIG;IACH,iHAAuC,CAAA;IAEvC;;;OAGG;IACH,iGAA+B,CAAA;IAE/B;;;OAGG;IACH,2DAAY,CAAA;AACd,CAAC,EA3BW,cAAc,KAAd,cAAc,QA2BzB;AAED,MAAM,CAAN,IAAY,YA6CX;AA7CD,WAAY,YAAY;IACtB;;OAEG;IACH,mCAAmB,CAAA;IAEnB;;OAEG;IACH,iCAAiB,CAAA;IAEjB;;OAEG;IACH,qCAAqB,CAAA;IAErB;;OAEG;IACH,iCAAiB,CAAA;IAEjB;;OAEG;IACH,uCAAuB,CAAA;IAEvB;;OAEG;IACH,2CAA2B,CAAA;IAE3B;;OAEG;IACH,uCAAuB,CAAA;IAEvB;;OAEG;IACH,mCAAmB,CAAA;IAEnB;;OAEG;IACH,iCAAiB,CAAA;AACnB,CAAC,EA7CW,YAAY,KAAZ,YAAY,QA6CvB;AAED,MAAM,CAAN,IAAY,wBAaX;AAbD,WAAY,wBAAwB;IAClC;;OAEG;IACH,+HAAoC,CAAA;IACpC;;OAEG;IACH,qIAAmC,CAAA;IACnC;;OAEG;IACH,iIAAiC,CAAA;AACnC,CAAC,EAbW,wBAAwB,KAAxB,wBAAwB,QAanC","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\nexport enum ATTRIBUTION_NETWORK {\n APPLE_SEARCH_ADS = 0,\n ADJUST = 1,\n APPSFLYER = 2,\n BRANCH = 3,\n TENJIN = 4,\n FACEBOOK = 5,\n}\n\nexport enum PURCHASE_TYPE {\n /**\n * A type of SKU for in-app products.\n */\n INAPP = 'inapp',\n\n /**\n * A type of SKU for subscriptions.\n */\n SUBS = 'subs',\n}\n\n/**\n * Enum for billing features.\n * Currently, these are only relevant for Google Play Android users:\n * https://developer.android.com/reference/com/android/billingclient/api/BillingClient.FeatureType\n */\nexport enum BILLING_FEATURE {\n /**\n * Purchase/query for subscriptions.\n */\n SUBSCRIPTIONS,\n\n /**\n * Subscriptions update/replace.\n */\n SUBSCRIPTIONS_UPDATE,\n\n /**\n * Purchase/query for in-app items on VR.\n */\n IN_APP_ITEMS_ON_VR,\n\n /**\n * Purchase/query for subscriptions on VR.\n */\n SUBSCRIPTIONS_ON_VR,\n\n /**\n * Launch a price change confirmation flow.\n */\n PRICE_CHANGE_CONFIRMATION,\n}\nexport enum PRORATION_MODE {\n UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY = 0,\n\n /**\n * Replacement takes effect immediately, and the remaining time will be\n * prorated and credited to the user. This is the current default behavior.\n */\n IMMEDIATE_WITH_TIME_PRORATION = 1,\n\n /**\n * Replacement takes effect immediately, and the billing cycle remains the\n * same. The price for the remaining period will be charged. This option is\n * only available for subscription upgrade.\n */\n IMMEDIATE_AND_CHARGE_PRORATED_PRICE = 2,\n\n /**\n * Replacement takes effect immediately, and the new price will be charged on\n * next recurrence time. The billing cycle stays the same.\n */\n IMMEDIATE_WITHOUT_PRORATION = 3,\n\n /**\n * Replacement takes effect when the old plan expires, and the new price will\n * be charged at the same time.\n */\n DEFERRED = 4,\n}\n\nexport enum PACKAGE_TYPE {\n /**\n * A package that was defined with a custom identifier.\n */\n UNKNOWN = 'UNKNOWN',\n\n /**\n * A package that was defined with a custom identifier.\n */\n CUSTOM = 'CUSTOM',\n\n /**\n * A package configured with the predefined lifetime identifier.\n */\n LIFETIME = 'LIFETIME',\n\n /**\n * A package configured with the predefined annual identifier.\n */\n ANNUAL = 'ANNUAL',\n\n /**\n * A package configured with the predefined six month identifier.\n */\n SIX_MONTH = 'SIX_MONTH',\n\n /**\n * A package configured with the predefined three month identifier.\n */\n THREE_MONTH = 'THREE_MONTH',\n\n /**\n * A package configured with the predefined two month identifier.\n */\n TWO_MONTH = 'TWO_MONTH',\n\n /**\n * A package configured with the predefined monthly identifier.\n */\n MONTHLY = 'MONTHLY',\n\n /**\n * A package configured with the predefined weekly identifier.\n */\n WEEKLY = 'WEEKLY',\n}\n\nexport enum INTRO_ELIGIBILITY_STATUS {\n /**\n * doesn't have enough information to determine eligibility.\n */\n INTRO_ELIGIBILITY_STATUS_UNKNOWN = 0,\n /**\n * The user is not eligible for a free trial or intro pricing for this product.\n */\n INTRO_ELIGIBILITY_STATUS_INELIGIBLE,\n /**\n * The user is eligible for a free trial or intro pricing for this product.\n */\n INTRO_ELIGIBILITY_STATUS_ELIGIBLE,\n}\n\nexport interface Transaction {\n /**\n * Unique identifier for the transaction.\n *\n * @since 1.0.0\n * @platform ios Numeric string (e.g., \"2000001043762129\")\n * @platform android Alphanumeric string (e.g., \"GPA.1234-5678-9012-34567\")\n */\n readonly transactionId: string;\n /**\n * Receipt data for validation (base64 encoded StoreKit receipt).\n *\n * Send this to your backend for server-side validation with Apple's receipt verification API.\n * The receipt remains available even after refund - server validation is required to detect refunded transactions.\n *\n * @since 1.0.0\n * @platform ios Always present\n * @platform android Not available (use purchaseToken instead)\n */\n readonly receipt?: string;\n /**\n * StoreKit 2 JSON Web Signature (JWS) payload describing the verified transaction.\n *\n * Send this to your backend when using Apple's App Store Server API v2 instead of raw receipts.\n * Only available when the transaction originated from StoreKit 2 APIs (e.g. Transaction.updates).\n *\n * @since 7.13.2\n * @platform ios Present for StoreKit 2 transactions (iOS 15+)\n * @platform android Not available\n */\n readonly jwsRepresentation?: string;\n /**\n * An optional obfuscated identifier that uniquely associates the transaction with a user account in your app.\n *\n * PURPOSE:\n * - Fraud detection: Helps platforms detect irregular activity (e.g., many devices purchasing on the same account)\n * - User linking: Links purchases to in-game characters, avatars, or in-app profiles\n *\n * PLATFORM DIFFERENCES:\n * - iOS: Must be a valid UUID format (e.g., \"550e8400-e29b-41d4-a716-446655440000\")\n * Apple's StoreKit 2 requires UUID format for the appAccountToken parameter\n * - Android: Can be any obfuscated string (max 64 chars), maps to Google Play's ObfuscatedAccountId\n * Google recommends using encryption or one-way hash\n *\n * SECURITY REQUIREMENTS (especially for Android):\n * - DO NOT store Personally Identifiable Information (PII) like emails in cleartext\n * - Use encryption or a one-way hash to generate an obfuscated identifier\n * - Maximum length: 64 characters (both platforms)\n * - Storing PII in cleartext will result in purchases being blocked by Google Play\n *\n * IMPLEMENTATION EXAMPLE:\n * ```typescript\n * // For iOS: Generate a deterministic UUID from user ID\n * import { v5 as uuidv5 } from 'uuid';\n * const NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; // Your app's namespace UUID\n * const appAccountToken = uuidv5(userId, NAMESPACE);\n *\n * // For Android: Can also use UUID or any hashed value\n * // The same UUID approach works for both platforms\n * ```\n */\n readonly appAccountToken?: string | null;\n /**\n * Product identifier associated with the transaction.\n *\n * @since 1.0.0\n * @platform ios Always present\n * @platform android Always present\n */\n readonly productIdentifier: string;\n /**\n * Purchase date of the transaction in ISO 8601 format.\n *\n * @since 1.0.0\n * @example \"2025-10-28T06:03:19Z\"\n * @platform ios Always present\n * @platform android Always present\n */\n readonly purchaseDate: string;\n /**\n * Indicates whether this transaction is the result of a subscription upgrade.\n *\n * Useful for understanding when StoreKit generated the transaction because\n * the customer moved from a lower tier to a higher tier plan.\n *\n * @since 7.13.2\n * @platform ios Present for auto-renewable subscriptions (iOS 15+)\n * @platform android Not available\n */\n readonly isUpgraded?: boolean;\n /**\n * Original purchase date of the transaction in ISO 8601 format.\n *\n * For subscription renewals, this shows the date of the original subscription purchase,\n * while purchaseDate shows the date of the current renewal.\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions only\n * @platform android Not available\n */\n readonly originalPurchaseDate?: string;\n /**\n * Expiration date of the transaction in ISO 8601 format.\n *\n * Check this date to determine if a subscription is still valid.\n * Compare with current date: if expirationDate > now, subscription is active.\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions only\n * @platform android Not available (query Google Play Developer API instead)\n */\n readonly expirationDate?: string;\n /**\n * Whether the subscription is still active/valid.\n *\n * For iOS subscriptions, check if isActive === true to verify an active subscription.\n * For expired or refunded iOS subscriptions, this will be false.\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions only (true if expiration date is in the future)\n * @platform android Not available (check purchaseState === \"1\" instead)\n */\n readonly isActive?: boolean;\n /**\n * Date the transaction was revoked/refunded, in ISO 8601 format.\n *\n * Present when Apple revokes access due to an issue (e.g., refund or developer issue).\n *\n * @since 7.13.2\n * @platform ios Present for revoked transactions (iOS 15+)\n * @platform android Not available\n */\n readonly revocationDate?: string;\n /**\n * Reason why Apple revoked the transaction.\n *\n * Possible values:\n * - `\"developerIssue\"`: Developer-initiated refund or issue\n * - `\"other\"`: Apple-initiated (customer refund, billing problem, etc.)\n * - `\"unknown\"`: StoreKit didn't report a specific reason\n *\n * @since 7.13.2\n * @platform ios Present for revoked transactions (iOS 15+)\n * @platform android Not available\n */\n readonly revocationReason?: 'developerIssue' | 'other' | 'unknown';\n /**\n * Whether the subscription will be cancelled at the end of the billing cycle.\n *\n * - `true`: User has cancelled but subscription remains active until expiration\n * - `false`: Subscription will auto-renew\n * - `null`: Status unknown or not available\n *\n * @since 1.0.0\n * @default null\n * @platform ios Present for subscriptions only (boolean or null)\n * @platform android Always null (use Google Play Developer API for cancellation status)\n */\n readonly willCancel: boolean | null;\n /**\n * Current subscription state reported by StoreKit.\n *\n * Possible values:\n * - `\"subscribed\"`: Auto-renewing and in good standing\n * - `\"expired\"`: Lapsed with no access\n * - `\"revoked\"`: Access removed due to refund or issue\n * - `\"inGracePeriod\"`: Payment issue but still in grace access window\n * - `\"inBillingRetryPeriod\"`: StoreKit retrying failed billing\n * - `\"unknown\"`: StoreKit did not report a state\n *\n * @since 7.13.2\n * @platform ios Present for auto-renewable subscriptions (iOS 15+)\n * @platform android Not available\n */\n readonly subscriptionState?:\n | 'subscribed'\n | 'expired'\n | 'revoked'\n | 'inGracePeriod'\n | 'inBillingRetryPeriod'\n | 'unknown';\n /**\n * Purchase state of the transaction (numeric string value).\n *\n * **Android Values:**\n * - `\"1\"`: Purchase completed and valid (PURCHASED state)\n * - `\"0\"`: Payment pending (PENDING state, e.g., cash payment processing)\n * - Other numeric values: Various other states\n *\n * Always check `purchaseState === \"1\"` on Android to verify a valid purchase.\n * Refunded purchases typically disappear from getPurchases() rather than showing a different state.\n *\n * @since 1.0.0\n * @platform ios Not available (use isActive for subscriptions or receipt validation for IAP)\n * @platform android Always present\n */\n readonly purchaseState?: string;\n /**\n * Order ID associated with the transaction.\n *\n * Use this for server-side verification on Android. This is the Google Play order ID.\n *\n * @since 1.0.0\n * @example \"GPA.1234-5678-9012-34567\"\n * @platform ios Not available\n * @platform android Always present\n */\n readonly orderId?: string;\n /**\n * Purchase token associated with the transaction.\n *\n * Send this to your backend for server-side validation with Google Play Developer API.\n * This is the Android equivalent of iOS's receipt field.\n *\n * @since 1.0.0\n * @platform ios Not available (use receipt instead)\n * @platform android Always present\n */\n readonly purchaseToken?: string;\n /**\n * Whether the purchase has been acknowledged.\n *\n * Purchases must be acknowledged within 3 days or they will be refunded.\n * By default, this plugin automatically acknowledges purchases unless you set\n * `autoAcknowledgePurchases: false` in purchaseProduct().\n *\n * @since 1.0.0\n * @platform ios Not available\n * @platform android Always present (should be true after successful purchase or manual acknowledgment)\n */\n readonly isAcknowledged?: boolean;\n /**\n * Quantity purchased.\n *\n * @since 1.0.0\n * @default 1\n * @platform ios 1 or higher (as specified in purchaseProduct call)\n * @platform android Always 1 (Google Play doesn't support quantity > 1)\n */\n readonly quantity?: number;\n /**\n * Product type.\n *\n * - `\"inapp\"`: One-time in-app purchase\n * - `\"subs\"`: Subscription\n *\n * @since 1.0.0\n * @platform ios Always present\n * @platform android Always present\n */\n readonly productType?: string;\n /**\n * Indicates how the user obtained access to the product.\n *\n * - `\"purchased\"`: The user purchased the product directly\n * - `\"familyShared\"`: The user has access through Family Sharing (another family member purchased it)\n *\n * This property is useful for:\n * - Detecting family sharing usage for analytics\n * - Implementing different features/limits for family-shared vs. directly purchased products\n * - Understanding your user acquisition channels\n *\n * @since 7.12.8\n * @platform ios Always present (iOS 15.0+, StoreKit 2)\n * @platform android Not available\n */\n readonly ownershipType?: 'purchased' | 'familyShared';\n /**\n * Indicates the server environment where the transaction was processed.\n *\n * - `\"Sandbox\"`: Transaction belongs to testing in the sandbox environment\n * - `\"Production\"`: Transaction belongs to a customer in the production environment\n * - `\"Xcode\"`: Transaction from StoreKit Testing in Xcode\n *\n * This property is useful for:\n * - Debugging and identifying test vs. production purchases\n * - Analytics and reporting (filtering out sandbox transactions)\n * - Server-side validation (knowing which Apple endpoint to use)\n * - Preventing test purchases from affecting production metrics\n *\n * @since 7.12.8\n * @platform ios Present on iOS 16.0+ only (not available on iOS 15)\n * @platform android Not available\n */\n readonly environment?: 'Sandbox' | 'Production' | 'Xcode';\n /**\n * Reason StoreKit generated the transaction.\n *\n * - `\"purchase\"`: Initial purchase that user made manually\n * - `\"renewal\"`: Automatically generated renewal for an auto-renewable subscription\n * - `\"unknown\"`: StoreKit did not return a reason\n *\n * @since 7.13.2\n * @platform ios Present on iOS 17.0+ (StoreKit 2 transactions)\n * @platform android Not available\n */\n readonly transactionReason?: 'purchase' | 'renewal' | 'unknown';\n /**\n * Whether the transaction is in a trial period.\n *\n * - `true`: Currently in free trial period\n * - `false`: Not in trial period\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions with trial offers\n * @platform android Present for subscriptions with trial offers\n */\n readonly isTrialPeriod?: boolean;\n /**\n * Whether the transaction is in an introductory price period.\n *\n * Introductory pricing is a discounted rate, different from a free trial.\n *\n * - `true`: Currently using introductory pricing\n * - `false`: Not in intro period\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions with intro pricing\n * @platform android Present for subscriptions with intro pricing\n */\n readonly isInIntroPricePeriod?: boolean;\n /**\n * Whether the transaction is in a grace period.\n *\n * Grace period allows users to fix payment issues while maintaining access.\n * You typically want to continue providing access during this time.\n *\n * - `true`: Subscription payment failed but user still has access\n * - `false`: Not in grace period\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions in grace period\n * @platform android Present for subscriptions in grace period\n */\n readonly isInGracePeriod?: boolean;\n}\n\nexport interface TransactionVerificationFailedEvent {\n /**\n * Identifier of the transaction that failed verification.\n *\n * @since 7.13.2\n * @platform ios Present when StoreKit reports an unverified transaction\n * @platform android Not available\n */\n readonly transactionId: string;\n /**\n * Localized error message describing why verification failed.\n *\n * @since 7.13.2\n * @platform ios Always present\n * @platform android Not available\n */\n readonly error: string;\n}\n\n/**\n * Represents the App Transaction information from StoreKit 2.\n * This provides details about when the user originally downloaded or purchased the app,\n * which is useful for determining if users are entitled to features from earlier business models.\n *\n * @see https://developer.apple.com/documentation/storekit/supporting-business-model-changes-by-using-the-app-transaction\n * @since 7.16.0\n */\nexport interface AppTransaction {\n /**\n * The app version that the user originally purchased or downloaded.\n *\n * Use this to determine if users who originally downloaded an earlier version\n * should be entitled to features that were previously free or included.\n *\n * For iOS: This is the `CFBundleShortVersionString` (e.g., \"1.0.0\")\n * For Android: This is the `versionName` from Google Play (e.g., \"1.0.0\")\n *\n * @example \"1.0.0\"\n * @since 7.16.0\n * @platform ios Always present (iOS 16+)\n * @platform android Always present\n */\n readonly originalAppVersion: string;\n\n /**\n * The date when the user originally purchased or downloaded the app.\n * ISO 8601 format.\n *\n * @example \"2023-06-15T10:30:00Z\"\n * @since 7.16.0\n * @platform ios Always present (iOS 16+)\n * @platform android Always present\n */\n readonly originalPurchaseDate: string;\n\n /**\n * The bundle identifier of the app.\n *\n * @example \"com.example.myapp\"\n * @since 7.16.0\n * @platform ios Always present (iOS 16+)\n * @platform android Always present (package name)\n */\n readonly bundleId: string;\n\n /**\n * The current app version installed on the device.\n *\n * @example \"2.0.0\"\n * @since 7.16.0\n * @platform ios Always present\n * @platform android Always present\n */\n readonly appVersion: string;\n\n /**\n * The server environment where the app was originally purchased.\n *\n * @since 7.16.0\n * @platform ios Present (iOS 16+)\n * @platform android Not available (always null)\n */\n readonly environment?: 'Sandbox' | 'Production' | 'Xcode' | null;\n\n /**\n * The JWS (JSON Web Signature) representation of the app transaction.\n * Can be sent to your backend for server-side verification.\n *\n * @since 7.16.0\n * @platform ios Present (iOS 16+)\n * @platform android Not available\n */\n readonly jwsRepresentation?: string;\n}\n\nexport interface SubscriptionPeriod {\n /**\n * The Subscription Period number of unit.\n */\n readonly numberOfUnits: number;\n /**\n * The Subscription Period unit.\n */\n readonly unit: number;\n}\nexport interface SKProductDiscount {\n /**\n * The Product discount identifier.\n */\n readonly identifier: string;\n /**\n * The Product discount type.\n */\n readonly type: number;\n /**\n * The Product discount price.\n */\n readonly price: number;\n /**\n * Formatted price of the item, including its currency sign, such as €3.99.\n */\n readonly priceString: string;\n /**\n * The Product discount currency symbol.\n */\n readonly currencySymbol: string;\n /**\n * The Product discount currency code.\n */\n readonly currencyCode: string;\n /**\n * The Product discount paymentMode.\n */\n readonly paymentMode: number;\n /**\n * The Product discount number Of Periods.\n */\n readonly numberOfPeriods: number;\n /**\n * The Product discount subscription period.\n */\n readonly subscriptionPeriod: SubscriptionPeriod;\n}\nexport interface Product {\n /**\n * Product Id.\n */\n readonly identifier: string;\n /**\n * Description of the product.\n */\n readonly description: string;\n /**\n * Title of the product.\n */\n readonly title: string;\n /**\n * Price of the product in the local currency.\n */\n readonly price: number;\n /**\n * Formatted price of the item, including its currency sign, such as €3.99.\n */\n readonly priceString: string;\n /**\n * Currency code for price and original price.\n */\n readonly currencyCode: string;\n /**\n * Currency symbol for price and original price.\n */\n readonly currencySymbol: string;\n /**\n * Boolean indicating if the product is sharable with family\n */\n readonly isFamilyShareable: boolean;\n /**\n * Group identifier for the product.\n */\n readonly subscriptionGroupIdentifier: string;\n /**\n * The Product subscription group identifier.\n */\n readonly subscriptionPeriod: SubscriptionPeriod;\n /**\n * The Product introductory Price.\n */\n readonly introductoryPrice: SKProductDiscount | null;\n /**\n * The Product discounts list.\n */\n readonly discounts: SKProductDiscount[];\n}\n\nexport interface NativePurchasesPlugin {\n /**\n * Restores a user's previous and links their appUserIDs to any user's also using those .\n */\n restorePurchases(): Promise<void>;\n\n /**\n * Gets the App Transaction information, which provides details about when the user\n * originally downloaded or purchased the app.\n *\n * This is useful for implementing business model changes where you want to\n * grandfather users who originally downloaded an earlier version of the app.\n *\n * **Use Case Example:**\n * If your app was originally free but you're adding a subscription, you can use\n * `originalAppVersion` to check if users downloaded before the subscription was added\n * and give them free access.\n *\n * **Platform Notes:**\n * - **iOS**: Requires iOS 16.0+. Uses StoreKit 2's `AppTransaction.shared`.\n * - **Android**: Uses Google Play's install referrer data when available.\n *\n * @returns {Promise<{ appTransaction: AppTransaction }>} The app transaction info\n * @throws An error if the app transaction cannot be retrieved (iOS 15 or earlier)\n * @since 7.16.0\n *\n * @example\n * ```typescript\n * const { appTransaction } = await NativePurchases.getAppTransaction();\n *\n * // Check if user downloaded before version 2.0.0 (when subscription was added)\n * if (compareVersions(appTransaction.originalAppVersion, '2.0.0') < 0) {\n * // User gets free access - they downloaded before subscriptions\n * grantFreeAccess();\n * }\n * ```\n *\n * @see https://developer.apple.com/documentation/storekit/supporting-business-model-changes-by-using-the-app-transaction\n */\n getAppTransaction(): Promise<{ appTransaction: AppTransaction }>;\n\n /**\n * Compares the original app version from the App Transaction against a target version\n * to determine if the user is entitled to features from an earlier business model.\n *\n * This is a utility method that performs the version comparison natively, which can be\n * more reliable than JavaScript-based comparison for semantic versioning.\n *\n * **Use Case:**\n * Check if the user's original download version is older than a specific version\n * to determine if they should be grandfathered into free features.\n *\n * **Platform Differences:**\n * - iOS: Uses build number (CFBundleVersion) from AppTransaction. Requires iOS 16+.\n * - Android: Uses version name from PackageInfo (current installed version, not original).\n *\n * @param options - The comparison options\n * @param options.targetVersion - The Android version name to compare against (e.g., \"2.0.0\"). Used on Android only.\n * @param options.targetBuildNumber - The iOS build number to compare against (e.g., \"42\"). Used on iOS only.\n * @returns {Promise<{ isOlderVersion: boolean; originalAppVersion: string }>}\n * - `isOlderVersion`: true if the user's original version is older than target\n * - `originalAppVersion`: The user's original app version/build number for reference\n * @throws An error if the app transaction cannot be retrieved\n * @since 7.16.0\n *\n * @example\n * ```typescript\n * // Check if user downloaded before version 2.0.0/build 42 (when subscription was added)\n * const result = await NativePurchases.isEntitledToOldBusinessModel({\n * targetVersion: '2.0.0',\n * targetBuildNumber: '42'\n * });\n *\n * if (result.isOlderVersion) {\n * console.log(`User downloaded v${result.originalAppVersion}, granting free access`);\n * grantFreeAccess();\n * }\n * ```\n */\n isEntitledToOldBusinessModel(options: {\n targetVersion?: string;\n targetBuildNumber?: string;\n }): Promise<{ isOlderVersion: boolean; originalAppVersion: string }>;\n\n /**\n * Started purchase process for the given product.\n *\n * @param options - The product to purchase\n * @param options.productIdentifier - The product identifier of the product you want to purchase.\n * @param options.productType - Only Android, the type of product, can be inapp or subs. Will use inapp by default.\n * @param options.planIdentifier - Only Android, the identifier of the base plan you want to purchase from Google Play Console. REQUIRED for Android subscriptions, ignored on iOS.\n * @param options.quantity - Only iOS, the number of items you wish to purchase. Will use 1 by default.\n * @param options.appAccountToken - Optional identifier uniquely associated with the user's account in your app.\n * PLATFORM REQUIREMENTS:\n * - iOS: Must be a valid UUID format (StoreKit 2 requirement)\n * - Android: Can be any obfuscated string (max 64 chars), maps to ObfuscatedAccountId\n * SECURITY: DO NOT use PII like emails in cleartext - use UUID or hashed value.\n * RECOMMENDED: Use UUID v5 with deterministic generation for cross-platform compatibility.\n * @param options.isConsumable - Only Android, when true the purchase token is consumed after granting entitlement (for consumable in-app items). Defaults to false.\n * @param options.autoAcknowledgePurchases - When false, the purchase/transaction will NOT be automatically acknowledged/finished. You must manually call acknowledgePurchase() or the purchase may be refunded. Defaults to true.\n * - **Android**: Must acknowledge within 3 days or Google Play will refund\n * - **iOS**: Unfinished transactions remain in the queue and may block future purchases\n */\n purchaseProduct(options: {\n productIdentifier: string;\n planIdentifier?: string;\n productType?: PURCHASE_TYPE;\n quantity?: number;\n appAccountToken?: string;\n isConsumable?: boolean;\n autoAcknowledgePurchases?: boolean;\n }): Promise<Transaction>;\n\n /**\n * Gets the product info associated with a list of product identifiers.\n *\n * @param options - The product identifiers you wish to retrieve information for\n * @param options.productIdentifiers - Array of product identifiers\n * @param options.productType - Only Android, the type of product, can be inapp or subs. Will use inapp by default.\n * @returns - The requested product info\n */\n getProducts(options: { productIdentifiers: string[]; productType?: PURCHASE_TYPE }): Promise<{ products: Product[] }>;\n\n /**\n * Gets the product info for a single product identifier.\n *\n * @param options - The product identifier you wish to retrieve information for\n * @param options.productIdentifier - The product identifier\n * @param options.productType - Only Android, the type of product, can be inapp or subs. Will use inapp by default.\n * @returns - The requested product info\n */\n getProduct(options: { productIdentifier: string; productType?: PURCHASE_TYPE }): Promise<{ product: Product }>;\n\n /**\n * Check if billing is supported for the current device.\n *\n *\n */\n isBillingSupported(): Promise<{ isBillingSupported: boolean }>;\n /**\n * Get the native Capacitor plugin version\n *\n * @returns {Promise<{ id: string }>} an Promise with version for this device\n * @throws An error if the something went wrong\n */\n getPluginVersion(): Promise<{ version: string }>;\n\n /**\n * Gets all the user's purchases (both in-app purchases and subscriptions).\n * This method queries the platform's purchase history for the current user.\n *\n * @param options - Optional parameters for filtering purchases\n * @param options.productType - Only Android, filter by product type (inapp or subs). If not specified, returns both types.\n * @param options.appAccountToken - Optional filter to restrict results to purchases that used the provided account token.\n * Must be the same identifier used during purchase (UUID format for iOS, any obfuscated string for Android).\n * iOS: UUID format required. Android: Maps to ObfuscatedAccountId.\n * @returns {Promise<{ purchases: Transaction[] }>} Promise that resolves with array of user's purchases\n * @throws An error if the purchase query fails\n * @since 7.2.0\n */\n getPurchases(options?: {\n productType?: PURCHASE_TYPE;\n appAccountToken?: string;\n }): Promise<{ purchases: Transaction[] }>;\n\n /**\n * Opens the platform's native subscription management page.\n * This allows users to view, modify, or cancel their subscriptions.\n *\n * - iOS: Opens the App Store subscription management page for the current app\n * - Android: Opens the Google Play subscription management page\n *\n * @returns {Promise<void>} Promise that resolves when the management page is opened\n * @throws An error if the subscription management page cannot be opened\n * @since 7.10.0\n */\n manageSubscriptions(): Promise<void>;\n\n /**\n * Manually acknowledge/finish a purchase transaction.\n *\n * This method is only needed when you set `autoAcknowledgePurchases: false` in purchaseProduct().\n *\n * **Platform Behavior:**\n * - **Android**: Acknowledges the purchase with Google Play. Must be called within 3 days or the purchase will be refunded.\n * - **iOS**: Finishes the transaction with StoreKit 2. Unfinished transactions remain in the queue and may block future purchases.\n *\n * **Acknowledgment Options:**\n *\n * **1. Client-side (this method)**: Call from your app after validation\n * ```typescript\n * await NativePurchases.acknowledgePurchase({\n * purchaseToken: transaction.purchaseToken // Android: purchaseToken, iOS: transactionId\n * });\n * ```\n *\n * **2. Server-side (Android only, recommended for security)**: Use Google Play Developer API v3\n * - Endpoint: `POST https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{packageName}/purchases/products/{productId}/tokens/{token}:acknowledge`\n * - Requires OAuth 2.0 authentication with appropriate scopes\n * - See: https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.products/acknowledge\n * - For subscriptions: Use `/purchases/subscriptions/{subscriptionId}/tokens/{token}:acknowledge` instead\n * - Note: iOS has no server-side finish API\n *\n * **When to use manual acknowledgment:**\n * - Server-side validation: Verify the purchase with your backend before acknowledging\n * - Entitlement delivery: Ensure user receives content/features before acknowledging\n * - Multi-step workflows: Complete all steps before final acknowledgment\n * - Security: Prevent client-side manipulation by handling acknowledgment server-side (Android only)\n *\n * @param options - The purchase to acknowledge\n * @param options.purchaseToken - The purchase token (Android) or transaction ID as string (iOS) from the Transaction object\n * @returns {Promise<void>} Promise that resolves when the purchase is acknowledged/finished\n * @throws An error if acknowledgment/finishing fails or transaction not found\n * @platform android Acknowledges the purchase with Google Play\n * @platform ios Finishes the transaction with StoreKit 2\n * @since 7.14.0\n *\n * @example\n * ```typescript\n * // Client-side acknowledgment\n * const transaction = await NativePurchases.purchaseProduct({\n * productIdentifier: 'premium_feature',\n * autoAcknowledgePurchases: false\n * });\n *\n * // Validate with your backend\n * const isValid = await fetch('/api/validate-purchase', {\n * method: 'POST',\n * body: JSON.stringify({ purchaseToken: transaction.purchaseToken })\n * });\n *\n * if (isValid) {\n * // Option 1: Acknowledge from client\n * await NativePurchases.acknowledgePurchase({\n * purchaseToken: transaction.purchaseToken\n * });\n *\n * // Option 2: Or let your backend acknowledge via Google Play API\n * // Your backend calls Google Play Developer API\n * }\n * ```\n */\n acknowledgePurchase(options: { purchaseToken: string }): Promise<void>;\n\n /**\n * Listen for StoreKit transaction updates delivered by Apple's Transaction.updates.\n * Fires on app launch if there are unfinished transactions, and for any updates afterward.\n * iOS only.\n */\n addListener(\n eventName: 'transactionUpdated',\n listenerFunc: (transaction: Transaction) => void,\n ): Promise<PluginListenerHandle>;\n /**\n * Listen for StoreKit transaction verification failures delivered by Apple's Transaction.updates.\n * Fires when the verification result is unverified.\n * iOS only.\n */\n addListener(\n eventName: 'transactionVerificationFailed',\n listenerFunc: (payload: TransactionVerificationFailedEvent) => void,\n ): Promise<PluginListenerHandle>;\n\n /** Remove all registered listeners */\n removeAllListeners(): Promise<void>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"AAEA,MAAM,CAAN,IAAY,mBAOX;AAPD,WAAY,mBAAmB;IAC7B,qFAAoB,CAAA;IACpB,iEAAU,CAAA;IACV,uEAAa,CAAA;IACb,iEAAU,CAAA;IACV,iEAAU,CAAA;IACV,qEAAY,CAAA;AACd,CAAC,EAPW,mBAAmB,KAAnB,mBAAmB,QAO9B;AAED,MAAM,CAAN,IAAY,aAUX;AAVD,WAAY,aAAa;IACvB;;OAEG;IACH,gCAAe,CAAA;IAEf;;OAEG;IACH,8BAAa,CAAA;AACf,CAAC,EAVW,aAAa,KAAb,aAAa,QAUxB;AAED;;;;GAIG;AACH,MAAM,CAAN,IAAY,eAyBX;AAzBD,WAAY,eAAe;IACzB;;OAEG;IACH,uEAAa,CAAA;IAEb;;OAEG;IACH,qFAAoB,CAAA;IAEpB;;OAEG;IACH,iFAAkB,CAAA;IAElB;;OAEG;IACH,mFAAmB,CAAA;IAEnB;;OAEG;IACH,+FAAyB,CAAA;AAC3B,CAAC,EAzBW,eAAe,KAAf,eAAe,QAyB1B;AACD,MAAM,CAAN,IAAY,cA2BX;AA3BD,WAAY,cAAc;IACxB,qIAAiD,CAAA;IAEjD;;;OAGG;IACH,qGAAiC,CAAA;IAEjC;;;;OAIG;IACH,iHAAuC,CAAA;IAEvC;;;OAGG;IACH,iGAA+B,CAAA;IAE/B;;;OAGG;IACH,2DAAY,CAAA;AACd,CAAC,EA3BW,cAAc,KAAd,cAAc,QA2BzB;AAED,MAAM,CAAN,IAAY,YA6CX;AA7CD,WAAY,YAAY;IACtB;;OAEG;IACH,mCAAmB,CAAA;IAEnB;;OAEG;IACH,iCAAiB,CAAA;IAEjB;;OAEG;IACH,qCAAqB,CAAA;IAErB;;OAEG;IACH,iCAAiB,CAAA;IAEjB;;OAEG;IACH,uCAAuB,CAAA;IAEvB;;OAEG;IACH,2CAA2B,CAAA;IAE3B;;OAEG;IACH,uCAAuB,CAAA;IAEvB;;OAEG;IACH,mCAAmB,CAAA;IAEnB;;OAEG;IACH,iCAAiB,CAAA;AACnB,CAAC,EA7CW,YAAY,KAAZ,YAAY,QA6CvB;AAED,MAAM,CAAN,IAAY,wBAaX;AAbD,WAAY,wBAAwB;IAClC;;OAEG;IACH,+HAAoC,CAAA;IACpC;;OAEG;IACH,qIAAmC,CAAA;IACnC;;OAEG;IACH,iIAAiC,CAAA;AACnC,CAAC,EAbW,wBAAwB,KAAxB,wBAAwB,QAanC","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\nexport enum ATTRIBUTION_NETWORK {\n APPLE_SEARCH_ADS = 0,\n ADJUST = 1,\n APPSFLYER = 2,\n BRANCH = 3,\n TENJIN = 4,\n FACEBOOK = 5,\n}\n\nexport enum PURCHASE_TYPE {\n /**\n * A type of SKU for in-app products.\n */\n INAPP = 'inapp',\n\n /**\n * A type of SKU for subscriptions.\n */\n SUBS = 'subs',\n}\n\n/**\n * Enum for billing features.\n * Currently, these are only relevant for Google Play Android users:\n * https://developer.android.com/reference/com/android/billingclient/api/BillingClient.FeatureType\n */\nexport enum BILLING_FEATURE {\n /**\n * Purchase/query for subscriptions.\n */\n SUBSCRIPTIONS,\n\n /**\n * Subscriptions update/replace.\n */\n SUBSCRIPTIONS_UPDATE,\n\n /**\n * Purchase/query for in-app items on VR.\n */\n IN_APP_ITEMS_ON_VR,\n\n /**\n * Purchase/query for subscriptions on VR.\n */\n SUBSCRIPTIONS_ON_VR,\n\n /**\n * Launch a price change confirmation flow.\n */\n PRICE_CHANGE_CONFIRMATION,\n}\nexport enum PRORATION_MODE {\n UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY = 0,\n\n /**\n * Replacement takes effect immediately, and the remaining time will be\n * prorated and credited to the user. This is the current default behavior.\n */\n IMMEDIATE_WITH_TIME_PRORATION = 1,\n\n /**\n * Replacement takes effect immediately, and the billing cycle remains the\n * same. The price for the remaining period will be charged. This option is\n * only available for subscription upgrade.\n */\n IMMEDIATE_AND_CHARGE_PRORATED_PRICE = 2,\n\n /**\n * Replacement takes effect immediately, and the new price will be charged on\n * next recurrence time. The billing cycle stays the same.\n */\n IMMEDIATE_WITHOUT_PRORATION = 3,\n\n /**\n * Replacement takes effect when the old plan expires, and the new price will\n * be charged at the same time.\n */\n DEFERRED = 4,\n}\n\nexport enum PACKAGE_TYPE {\n /**\n * A package that was defined with a custom identifier.\n */\n UNKNOWN = 'UNKNOWN',\n\n /**\n * A package that was defined with a custom identifier.\n */\n CUSTOM = 'CUSTOM',\n\n /**\n * A package configured with the predefined lifetime identifier.\n */\n LIFETIME = 'LIFETIME',\n\n /**\n * A package configured with the predefined annual identifier.\n */\n ANNUAL = 'ANNUAL',\n\n /**\n * A package configured with the predefined six month identifier.\n */\n SIX_MONTH = 'SIX_MONTH',\n\n /**\n * A package configured with the predefined three month identifier.\n */\n THREE_MONTH = 'THREE_MONTH',\n\n /**\n * A package configured with the predefined two month identifier.\n */\n TWO_MONTH = 'TWO_MONTH',\n\n /**\n * A package configured with the predefined monthly identifier.\n */\n MONTHLY = 'MONTHLY',\n\n /**\n * A package configured with the predefined weekly identifier.\n */\n WEEKLY = 'WEEKLY',\n}\n\nexport enum INTRO_ELIGIBILITY_STATUS {\n /**\n * doesn't have enough information to determine eligibility.\n */\n INTRO_ELIGIBILITY_STATUS_UNKNOWN = 0,\n /**\n * The user is not eligible for a free trial or intro pricing for this product.\n */\n INTRO_ELIGIBILITY_STATUS_INELIGIBLE,\n /**\n * The user is eligible for a free trial or intro pricing for this product.\n */\n INTRO_ELIGIBILITY_STATUS_ELIGIBLE,\n}\n\nexport interface Transaction {\n /**\n * Unique identifier for the transaction.\n *\n * @since 1.0.0\n * @platform ios Numeric string (e.g., \"2000001043762129\")\n * @platform android Alphanumeric string (e.g., \"GPA.1234-5678-9012-34567\")\n */\n readonly transactionId: string;\n /**\n * Receipt data for validation (base64 encoded StoreKit receipt).\n *\n * **This is the full verified receipt payload from Apple StoreKit.**\n * Send this to your backend for server-side validation with Apple's receipt verification API.\n * The receipt remains available even after refund - server validation is required to detect refunded transactions.\n *\n * **For backend validation:**\n * - Use Apple's receipt verification API: https://buy.itunes.apple.com/verifyReceipt (production)\n * - Or sandbox: https://sandbox.itunes.apple.com/verifyReceipt\n * - This contains all transaction data needed for validation\n *\n * **Note:** Apple recommends migrating to App Store Server API v2 with `jwsRepresentation` for new implementations.\n * The legacy receipt verification API continues to work but may be deprecated in the future.\n *\n * @since 1.0.0\n * @platform ios Always present\n * @platform android Not available (use purchaseToken instead)\n * @example\n * ```typescript\n * const transaction = await NativePurchases.purchaseProduct({ ... });\n * if (transaction.receipt) {\n * // Send to your backend for validation\n * await fetch('/api/validate-receipt', {\n * method: 'POST',\n * body: JSON.stringify({ receipt: transaction.receipt })\n * });\n * }\n * ```\n */\n readonly receipt?: string;\n /**\n * StoreKit 2 JSON Web Signature (JWS) payload describing the verified transaction.\n *\n * **This is the full verified receipt in JWS format (StoreKit 2).**\n * Send this to your backend when using Apple's App Store Server API v2 instead of raw receipts.\n * Only available when the transaction originated from StoreKit 2 APIs (e.g. Transaction.updates).\n *\n * **For backend validation:**\n * - Use Apple's App Store Server API v2 to decode and verify the JWS\n * - This is the modern alternative to the legacy receipt format\n * - Contains signed transaction information from Apple\n *\n * @since 7.13.2\n * @platform ios Present for StoreKit 2 transactions (iOS 15+)\n * @platform android Not available\n * @example\n * ```typescript\n * const transaction = await NativePurchases.purchaseProduct({ ... });\n * if (transaction.jwsRepresentation) {\n * // Send to your backend for validation with App Store Server API v2\n * await fetch('/api/validate-jws', {\n * method: 'POST',\n * body: JSON.stringify({ jws: transaction.jwsRepresentation })\n * });\n * }\n * ```\n */\n readonly jwsRepresentation?: string;\n /**\n * An optional obfuscated identifier that uniquely associates the transaction with a user account in your app.\n *\n * PURPOSE:\n * - Fraud detection: Helps platforms detect irregular activity (e.g., many devices purchasing on the same account)\n * - User linking: Links purchases to in-game characters, avatars, or in-app profiles\n *\n * PLATFORM DIFFERENCES:\n * - iOS: Must be a valid UUID format (e.g., \"550e8400-e29b-41d4-a716-446655440000\")\n * Apple's StoreKit 2 requires UUID format for the appAccountToken parameter\n * - Android: Can be any obfuscated string (max 64 chars), maps to Google Play's ObfuscatedAccountId\n * Google recommends using encryption or one-way hash\n *\n * SECURITY REQUIREMENTS (especially for Android):\n * - DO NOT store Personally Identifiable Information (PII) like emails in cleartext\n * - Use encryption or a one-way hash to generate an obfuscated identifier\n * - Maximum length: 64 characters (both platforms)\n * - Storing PII in cleartext will result in purchases being blocked by Google Play\n *\n * IMPLEMENTATION EXAMPLE:\n * ```typescript\n * // For iOS: Generate a deterministic UUID from user ID\n * import { v5 as uuidv5 } from 'uuid';\n * const NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; // Your app's namespace UUID\n * const appAccountToken = uuidv5(userId, NAMESPACE);\n *\n * // For Android: Can also use UUID or any hashed value\n * // The same UUID approach works for both platforms\n * ```\n */\n readonly appAccountToken?: string | null;\n /**\n * Product identifier associated with the transaction.\n *\n * @since 1.0.0\n * @platform ios Always present\n * @platform android Always present\n */\n readonly productIdentifier: string;\n /**\n * Purchase date of the transaction in ISO 8601 format.\n *\n * @since 1.0.0\n * @example \"2025-10-28T06:03:19Z\"\n * @platform ios Always present\n * @platform android Always present\n */\n readonly purchaseDate: string;\n /**\n * Indicates whether this transaction is the result of a subscription upgrade.\n *\n * Useful for understanding when StoreKit generated the transaction because\n * the customer moved from a lower tier to a higher tier plan.\n *\n * @since 7.13.2\n * @platform ios Present for auto-renewable subscriptions (iOS 15+)\n * @platform android Not available\n */\n readonly isUpgraded?: boolean;\n /**\n * Original purchase date of the transaction in ISO 8601 format.\n *\n * For subscription renewals, this shows the date of the original subscription purchase,\n * while purchaseDate shows the date of the current renewal.\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions only\n * @platform android Not available\n */\n readonly originalPurchaseDate?: string;\n /**\n * Expiration date of the transaction in ISO 8601 format.\n *\n * Check this date to determine if a subscription is still valid.\n * Compare with current date: if expirationDate > now, subscription is active.\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions only\n * @platform android Not available (query Google Play Developer API instead)\n */\n readonly expirationDate?: string;\n /**\n * Whether the subscription is still active/valid.\n *\n * For iOS subscriptions, check if isActive === true to verify an active subscription.\n * For expired or refunded iOS subscriptions, this will be false.\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions only (true if expiration date is in the future)\n * @platform android Not available (check purchaseState === \"1\" instead)\n */\n readonly isActive?: boolean;\n /**\n * Date the transaction was revoked/refunded, in ISO 8601 format.\n *\n * Present when Apple revokes access due to an issue (e.g., refund or developer issue).\n *\n * @since 7.13.2\n * @platform ios Present for revoked transactions (iOS 15+)\n * @platform android Not available\n */\n readonly revocationDate?: string;\n /**\n * Reason why Apple revoked the transaction.\n *\n * Possible values:\n * - `\"developerIssue\"`: Developer-initiated refund or issue\n * - `\"other\"`: Apple-initiated (customer refund, billing problem, etc.)\n * - `\"unknown\"`: StoreKit didn't report a specific reason\n *\n * @since 7.13.2\n * @platform ios Present for revoked transactions (iOS 15+)\n * @platform android Not available\n */\n readonly revocationReason?: 'developerIssue' | 'other' | 'unknown';\n /**\n * Whether the subscription will be cancelled at the end of the billing cycle.\n *\n * - `true`: User has cancelled but subscription remains active until expiration\n * - `false`: Subscription will auto-renew\n * - `null`: Status unknown or not available\n *\n * @since 1.0.0\n * @default null\n * @platform ios Present for subscriptions only (boolean or null)\n * @platform android Always null (use Google Play Developer API for cancellation status)\n */\n readonly willCancel: boolean | null;\n /**\n * Current subscription state reported by StoreKit.\n *\n * Possible values:\n * - `\"subscribed\"`: Auto-renewing and in good standing\n * - `\"expired\"`: Lapsed with no access\n * - `\"revoked\"`: Access removed due to refund or issue\n * - `\"inGracePeriod\"`: Payment issue but still in grace access window\n * - `\"inBillingRetryPeriod\"`: StoreKit retrying failed billing\n * - `\"unknown\"`: StoreKit did not report a state\n *\n * @since 7.13.2\n * @platform ios Present for auto-renewable subscriptions (iOS 15+)\n * @platform android Not available\n */\n readonly subscriptionState?:\n | 'subscribed'\n | 'expired'\n | 'revoked'\n | 'inGracePeriod'\n | 'inBillingRetryPeriod'\n | 'unknown';\n /**\n * Purchase state of the transaction (numeric string value).\n *\n * **Android Values:**\n * - `\"1\"`: Purchase completed and valid (PURCHASED state)\n * - `\"0\"`: Payment pending (PENDING state, e.g., cash payment processing)\n * - Other numeric values: Various other states\n *\n * Always check `purchaseState === \"1\"` on Android to verify a valid purchase.\n * Refunded purchases typically disappear from getPurchases() rather than showing a different state.\n *\n * @since 1.0.0\n * @platform ios Not available (use isActive for subscriptions or receipt validation for IAP)\n * @platform android Always present\n */\n readonly purchaseState?: string;\n /**\n * Order ID associated with the transaction.\n *\n * Use this for server-side verification on Android. This is the Google Play order ID.\n *\n * @since 1.0.0\n * @example \"GPA.1234-5678-9012-34567\"\n * @platform ios Not available\n * @platform android Always present\n */\n readonly orderId?: string;\n /**\n * Purchase token associated with the transaction.\n *\n * **This is the full verified purchase token from Google Play.**\n * Send this to your backend for server-side validation with Google Play Developer API.\n * This is the Android equivalent of iOS's receipt field.\n *\n * **For backend validation:**\n * - Use Google Play Developer API v3 to verify the purchase\n * - API endpoint: androidpublisher.purchases.products.get() or purchases.subscriptions.get()\n * - This token contains all data needed for validation with Google servers\n * - Can also be used for subscription status checks and cancellation detection\n *\n * @since 1.0.0\n * @platform ios Not available (use receipt instead)\n * @platform android Always present\n * @example\n * ```typescript\n * const transaction = await NativePurchases.purchaseProduct({ ... });\n * if (transaction.purchaseToken) {\n * // Send to your backend for validation\n * await fetch('/api/validate-purchase', {\n * method: 'POST',\n * body: JSON.stringify({\n * purchaseToken: transaction.purchaseToken,\n * productId: transaction.productIdentifier\n * })\n * });\n * }\n * ```\n */\n readonly purchaseToken?: string;\n /**\n * Whether the purchase has been acknowledged.\n *\n * Purchases must be acknowledged within 3 days or they will be refunded.\n * By default, this plugin automatically acknowledges purchases unless you set\n * `autoAcknowledgePurchases: false` in purchaseProduct().\n *\n * @since 1.0.0\n * @platform ios Not available\n * @platform android Always present (should be true after successful purchase or manual acknowledgment)\n */\n readonly isAcknowledged?: boolean;\n /**\n * Quantity purchased.\n *\n * @since 1.0.0\n * @default 1\n * @platform ios 1 or higher (as specified in purchaseProduct call)\n * @platform android Always 1 (Google Play doesn't support quantity > 1)\n */\n readonly quantity?: number;\n /**\n * Product type.\n *\n * - `\"inapp\"`: One-time in-app purchase\n * - `\"subs\"`: Subscription\n *\n * @since 1.0.0\n * @platform ios Always present\n * @platform android Always present\n */\n readonly productType?: string;\n /**\n * Indicates how the user obtained access to the product.\n *\n * - `\"purchased\"`: The user purchased the product directly\n * - `\"familyShared\"`: The user has access through Family Sharing (another family member purchased it)\n *\n * This property is useful for:\n * - Detecting family sharing usage for analytics\n * - Implementing different features/limits for family-shared vs. directly purchased products\n * - Understanding your user acquisition channels\n *\n * @since 7.12.8\n * @platform ios Always present (iOS 15.0+, StoreKit 2)\n * @platform android Not available\n */\n readonly ownershipType?: 'purchased' | 'familyShared';\n /**\n * Indicates the server environment where the transaction was processed.\n *\n * - `\"Sandbox\"`: Transaction belongs to testing in the sandbox environment\n * - `\"Production\"`: Transaction belongs to a customer in the production environment\n * - `\"Xcode\"`: Transaction from StoreKit Testing in Xcode\n *\n * This property is useful for:\n * - Debugging and identifying test vs. production purchases\n * - Analytics and reporting (filtering out sandbox transactions)\n * - Server-side validation (knowing which Apple endpoint to use)\n * - Preventing test purchases from affecting production metrics\n *\n * @since 7.12.8\n * @platform ios Present on iOS 16.0+ only (not available on iOS 15)\n * @platform android Not available\n */\n readonly environment?: 'Sandbox' | 'Production' | 'Xcode';\n /**\n * Reason StoreKit generated the transaction.\n *\n * - `\"purchase\"`: Initial purchase that user made manually\n * - `\"renewal\"`: Automatically generated renewal for an auto-renewable subscription\n * - `\"unknown\"`: StoreKit did not return a reason\n *\n * @since 7.13.2\n * @platform ios Present on iOS 17.0+ (StoreKit 2 transactions)\n * @platform android Not available\n */\n readonly transactionReason?: 'purchase' | 'renewal' | 'unknown';\n /**\n * Whether the transaction is in a trial period.\n *\n * - `true`: Currently in free trial period\n * - `false`: Not in trial period\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions with trial offers\n * @platform android Present for subscriptions with trial offers\n */\n readonly isTrialPeriod?: boolean;\n /**\n * Whether the transaction is in an introductory price period.\n *\n * Introductory pricing is a discounted rate, different from a free trial.\n *\n * - `true`: Currently using introductory pricing\n * - `false`: Not in intro period\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions with intro pricing\n * @platform android Present for subscriptions with intro pricing\n */\n readonly isInIntroPricePeriod?: boolean;\n /**\n * Whether the transaction is in a grace period.\n *\n * Grace period allows users to fix payment issues while maintaining access.\n * You typically want to continue providing access during this time.\n *\n * - `true`: Subscription payment failed but user still has access\n * - `false`: Not in grace period\n *\n * @since 1.0.0\n * @platform ios Present for subscriptions in grace period\n * @platform android Present for subscriptions in grace period\n */\n readonly isInGracePeriod?: boolean;\n}\n\nexport interface TransactionVerificationFailedEvent {\n /**\n * Identifier of the transaction that failed verification.\n *\n * @since 7.13.2\n * @platform ios Present when StoreKit reports an unverified transaction\n * @platform android Not available\n */\n readonly transactionId: string;\n /**\n * Localized error message describing why verification failed.\n *\n * @since 7.13.2\n * @platform ios Always present\n * @platform android Not available\n */\n readonly error: string;\n}\n\n/**\n * Represents the App Transaction information from StoreKit 2.\n * This provides details about when the user originally downloaded or purchased the app,\n * which is useful for determining if users are entitled to features from earlier business models.\n *\n * @see https://developer.apple.com/documentation/storekit/supporting-business-model-changes-by-using-the-app-transaction\n * @since 7.16.0\n */\nexport interface AppTransaction {\n /**\n * The app version that the user originally purchased or downloaded.\n *\n * Use this to determine if users who originally downloaded an earlier version\n * should be entitled to features that were previously free or included.\n *\n * For iOS: This is the `CFBundleShortVersionString` (e.g., \"1.0.0\")\n * For Android: This is the `versionName` from Google Play (e.g., \"1.0.0\")\n *\n * @example \"1.0.0\"\n * @since 7.16.0\n * @platform ios Always present (iOS 16+)\n * @platform android Always present\n */\n readonly originalAppVersion: string;\n\n /**\n * The date when the user originally purchased or downloaded the app.\n * ISO 8601 format.\n *\n * @example \"2023-06-15T10:30:00Z\"\n * @since 7.16.0\n * @platform ios Always present (iOS 16+)\n * @platform android Always present\n */\n readonly originalPurchaseDate: string;\n\n /**\n * The bundle identifier of the app.\n *\n * @example \"com.example.myapp\"\n * @since 7.16.0\n * @platform ios Always present (iOS 16+)\n * @platform android Always present (package name)\n */\n readonly bundleId: string;\n\n /**\n * The current app version installed on the device.\n *\n * @example \"2.0.0\"\n * @since 7.16.0\n * @platform ios Always present\n * @platform android Always present\n */\n readonly appVersion: string;\n\n /**\n * The server environment where the app was originally purchased.\n *\n * @since 7.16.0\n * @platform ios Present (iOS 16+)\n * @platform android Not available (always null)\n */\n readonly environment?: 'Sandbox' | 'Production' | 'Xcode' | null;\n\n /**\n * The JWS (JSON Web Signature) representation of the app transaction.\n * Can be sent to your backend for server-side verification.\n *\n * @since 7.16.0\n * @platform ios Present (iOS 16+)\n * @platform android Not available\n */\n readonly jwsRepresentation?: string;\n}\n\nexport interface SubscriptionPeriod {\n /**\n * The Subscription Period number of unit.\n */\n readonly numberOfUnits: number;\n /**\n * The Subscription Period unit.\n */\n readonly unit: number;\n}\nexport interface SKProductDiscount {\n /**\n * The Product discount identifier.\n */\n readonly identifier: string;\n /**\n * The Product discount type.\n */\n readonly type: number;\n /**\n * The Product discount price.\n */\n readonly price: number;\n /**\n * Formatted price of the item, including its currency sign, such as €3.99.\n */\n readonly priceString: string;\n /**\n * The Product discount currency symbol.\n */\n readonly currencySymbol: string;\n /**\n * The Product discount currency code.\n */\n readonly currencyCode: string;\n /**\n * The Product discount paymentMode.\n */\n readonly paymentMode: number;\n /**\n * The Product discount number Of Periods.\n */\n readonly numberOfPeriods: number;\n /**\n * The Product discount subscription period.\n */\n readonly subscriptionPeriod: SubscriptionPeriod;\n}\nexport interface Product {\n /**\n * Product Id.\n */\n readonly identifier: string;\n /**\n * Description of the product.\n */\n readonly description: string;\n /**\n * Title of the product.\n */\n readonly title: string;\n /**\n * Price of the product in the local currency.\n */\n readonly price: number;\n /**\n * Formatted price of the item, including its currency sign, such as €3.99.\n */\n readonly priceString: string;\n /**\n * Currency code for price and original price.\n */\n readonly currencyCode: string;\n /**\n * Currency symbol for price and original price.\n */\n readonly currencySymbol: string;\n /**\n * Boolean indicating if the product is sharable with family\n */\n readonly isFamilyShareable: boolean;\n /**\n * Group identifier for the product.\n */\n readonly subscriptionGroupIdentifier: string;\n /**\n * The Product subscription group identifier.\n */\n readonly subscriptionPeriod: SubscriptionPeriod;\n /**\n * The Product introductory Price.\n */\n readonly introductoryPrice: SKProductDiscount | null;\n /**\n * The Product discounts list.\n */\n readonly discounts: SKProductDiscount[];\n}\n\nexport interface NativePurchasesPlugin {\n /**\n * Restores a user's previous and links their appUserIDs to any user's also using those .\n */\n restorePurchases(): Promise<void>;\n\n /**\n * Gets the App Transaction information, which provides details about when the user\n * originally downloaded or purchased the app.\n *\n * This is useful for implementing business model changes where you want to\n * grandfather users who originally downloaded an earlier version of the app.\n *\n * **Use Case Example:**\n * If your app was originally free but you're adding a subscription, you can use\n * `originalAppVersion` to check if users downloaded before the subscription was added\n * and give them free access.\n *\n * **Platform Notes:**\n * - **iOS**: Requires iOS 16.0+. Uses StoreKit 2's `AppTransaction.shared`.\n * - **Android**: Uses Google Play's install referrer data when available.\n *\n * @returns {Promise<{ appTransaction: AppTransaction }>} The app transaction info\n * @throws An error if the app transaction cannot be retrieved (iOS 15 or earlier)\n * @since 7.16.0\n *\n * @example\n * ```typescript\n * const { appTransaction } = await NativePurchases.getAppTransaction();\n *\n * // Check if user downloaded before version 2.0.0 (when subscription was added)\n * if (compareVersions(appTransaction.originalAppVersion, '2.0.0') < 0) {\n * // User gets free access - they downloaded before subscriptions\n * grantFreeAccess();\n * }\n * ```\n *\n * @see https://developer.apple.com/documentation/storekit/supporting-business-model-changes-by-using-the-app-transaction\n */\n getAppTransaction(): Promise<{ appTransaction: AppTransaction }>;\n\n /**\n * Compares the original app version from the App Transaction against a target version\n * to determine if the user is entitled to features from an earlier business model.\n *\n * This is a utility method that performs the version comparison natively, which can be\n * more reliable than JavaScript-based comparison for semantic versioning.\n *\n * **Use Case:**\n * Check if the user's original download version is older than a specific version\n * to determine if they should be grandfathered into free features.\n *\n * **Platform Differences:**\n * - iOS: Uses build number (CFBundleVersion) from AppTransaction. Requires iOS 16+.\n * - Android: Uses version name from PackageInfo (current installed version, not original).\n *\n * @param options - The comparison options\n * @param options.targetVersion - The Android version name to compare against (e.g., \"2.0.0\"). Used on Android only.\n * @param options.targetBuildNumber - The iOS build number to compare against (e.g., \"42\"). Used on iOS only.\n * @returns {Promise<{ isOlderVersion: boolean; originalAppVersion: string }>}\n * - `isOlderVersion`: true if the user's original version is older than target\n * - `originalAppVersion`: The user's original app version/build number for reference\n * @throws An error if the app transaction cannot be retrieved\n * @since 7.16.0\n *\n * @example\n * ```typescript\n * // Check if user downloaded before version 2.0.0/build 42 (when subscription was added)\n * const result = await NativePurchases.isEntitledToOldBusinessModel({\n * targetVersion: '2.0.0',\n * targetBuildNumber: '42'\n * });\n *\n * if (result.isOlderVersion) {\n * console.log(`User downloaded v${result.originalAppVersion}, granting free access`);\n * grantFreeAccess();\n * }\n * ```\n */\n isEntitledToOldBusinessModel(options: {\n targetVersion?: string;\n targetBuildNumber?: string;\n }): Promise<{ isOlderVersion: boolean; originalAppVersion: string }>;\n\n /**\n * Started purchase process for the given product.\n *\n * @param options - The product to purchase\n * @param options.productIdentifier - The product identifier of the product you want to purchase.\n * @param options.productType - Only Android, the type of product, can be inapp or subs. Will use inapp by default.\n * @param options.planIdentifier - Only Android, the identifier of the base plan you want to purchase from Google Play Console. REQUIRED for Android subscriptions, ignored on iOS.\n * @param options.quantity - Only iOS, the number of items you wish to purchase. Will use 1 by default.\n * @param options.appAccountToken - Optional identifier uniquely associated with the user's account in your app.\n * PLATFORM REQUIREMENTS:\n * - iOS: Must be a valid UUID format (StoreKit 2 requirement)\n * - Android: Can be any obfuscated string (max 64 chars), maps to ObfuscatedAccountId\n * SECURITY: DO NOT use PII like emails in cleartext - use UUID or hashed value.\n * RECOMMENDED: Use UUID v5 with deterministic generation for cross-platform compatibility.\n * @param options.isConsumable - Only Android, when true the purchase token is consumed after granting entitlement (for consumable in-app items). Defaults to false.\n * @param options.autoAcknowledgePurchases - When false, the purchase/transaction will NOT be automatically acknowledged/finished. You must manually call acknowledgePurchase() or the purchase may be refunded. Defaults to true.\n * - **Android**: Must acknowledge within 3 days or Google Play will refund\n * - **iOS**: Unfinished transactions remain in the queue and may block future purchases\n */\n purchaseProduct(options: {\n productIdentifier: string;\n planIdentifier?: string;\n productType?: PURCHASE_TYPE;\n quantity?: number;\n appAccountToken?: string;\n isConsumable?: boolean;\n autoAcknowledgePurchases?: boolean;\n }): Promise<Transaction>;\n\n /**\n * Gets the product info associated with a list of product identifiers.\n *\n * @param options - The product identifiers you wish to retrieve information for\n * @param options.productIdentifiers - Array of product identifiers\n * @param options.productType - Only Android, the type of product, can be inapp or subs. Will use inapp by default.\n * @returns - The requested product info\n */\n getProducts(options: { productIdentifiers: string[]; productType?: PURCHASE_TYPE }): Promise<{ products: Product[] }>;\n\n /**\n * Gets the product info for a single product identifier.\n *\n * @param options - The product identifier you wish to retrieve information for\n * @param options.productIdentifier - The product identifier\n * @param options.productType - Only Android, the type of product, can be inapp or subs. Will use inapp by default.\n * @returns - The requested product info\n */\n getProduct(options: { productIdentifier: string; productType?: PURCHASE_TYPE }): Promise<{ product: Product }>;\n\n /**\n * Check if billing is supported for the current device.\n *\n *\n */\n isBillingSupported(): Promise<{ isBillingSupported: boolean }>;\n /**\n * Get the native Capacitor plugin version\n *\n * @returns {Promise<{ id: string }>} an Promise with version for this device\n * @throws An error if the something went wrong\n */\n getPluginVersion(): Promise<{ version: string }>;\n\n /**\n * Gets all the user's purchases (both in-app purchases and subscriptions).\n * This method queries the platform's purchase history for the current user.\n *\n * @param options - Optional parameters for filtering purchases\n * @param options.productType - Only Android, filter by product type (inapp or subs). If not specified, returns both types.\n * @param options.appAccountToken - Optional filter to restrict results to purchases that used the provided account token.\n * Must be the same identifier used during purchase (UUID format for iOS, any obfuscated string for Android).\n * iOS: UUID format required. Android: Maps to ObfuscatedAccountId.\n * @returns {Promise<{ purchases: Transaction[] }>} Promise that resolves with array of user's purchases\n * @throws An error if the purchase query fails\n * @since 7.2.0\n */\n getPurchases(options?: {\n productType?: PURCHASE_TYPE;\n appAccountToken?: string;\n }): Promise<{ purchases: Transaction[] }>;\n\n /**\n * Opens the platform's native subscription management page.\n * This allows users to view, modify, or cancel their subscriptions.\n *\n * - iOS: Opens the App Store subscription management page for the current app\n * - Android: Opens the Google Play subscription management page\n *\n * @returns {Promise<void>} Promise that resolves when the management page is opened\n * @throws An error if the subscription management page cannot be opened\n * @since 7.10.0\n */\n manageSubscriptions(): Promise<void>;\n\n /**\n * Manually acknowledge/finish a purchase transaction.\n *\n * This method is only needed when you set `autoAcknowledgePurchases: false` in purchaseProduct().\n *\n * **Platform Behavior:**\n * - **Android**: Acknowledges the purchase with Google Play. Must be called within 3 days or the purchase will be refunded.\n * - **iOS**: Finishes the transaction with StoreKit 2. Unfinished transactions remain in the queue and may block future purchases.\n *\n * **Acknowledgment Options:**\n *\n * **1. Client-side (this method)**: Call from your app after validation\n * ```typescript\n * await NativePurchases.acknowledgePurchase({\n * purchaseToken: transaction.purchaseToken // Android: purchaseToken, iOS: transactionId\n * });\n * ```\n *\n * **2. Server-side (Android only, recommended for security)**: Use Google Play Developer API v3\n * - Endpoint: `POST https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{packageName}/purchases/products/{productId}/tokens/{token}:acknowledge`\n * - Requires OAuth 2.0 authentication with appropriate scopes\n * - See: https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.products/acknowledge\n * - For subscriptions: Use `/purchases/subscriptions/{subscriptionId}/tokens/{token}:acknowledge` instead\n * - Note: iOS has no server-side finish API\n *\n * **When to use manual acknowledgment:**\n * - Server-side validation: Verify the purchase with your backend before acknowledging\n * - Entitlement delivery: Ensure user receives content/features before acknowledging\n * - Multi-step workflows: Complete all steps before final acknowledgment\n * - Security: Prevent client-side manipulation by handling acknowledgment server-side (Android only)\n *\n * @param options - The purchase to acknowledge\n * @param options.purchaseToken - The purchase token (Android) or transaction ID as string (iOS) from the Transaction object\n * @returns {Promise<void>} Promise that resolves when the purchase is acknowledged/finished\n * @throws An error if acknowledgment/finishing fails or transaction not found\n * @platform android Acknowledges the purchase with Google Play\n * @platform ios Finishes the transaction with StoreKit 2\n * @since 7.14.0\n *\n * @example\n * ```typescript\n * // Client-side acknowledgment\n * const transaction = await NativePurchases.purchaseProduct({\n * productIdentifier: 'premium_feature',\n * autoAcknowledgePurchases: false\n * });\n *\n * // Validate with your backend\n * const isValid = await fetch('/api/validate-purchase', {\n * method: 'POST',\n * body: JSON.stringify({ purchaseToken: transaction.purchaseToken })\n * });\n *\n * if (isValid) {\n * // Option 1: Acknowledge from client\n * await NativePurchases.acknowledgePurchase({\n * purchaseToken: transaction.purchaseToken\n * });\n *\n * // Option 2: Or let your backend acknowledge via Google Play API\n * // Your backend calls Google Play Developer API\n * }\n * ```\n */\n acknowledgePurchase(options: { purchaseToken: string }): Promise<void>;\n\n /**\n * Listen for StoreKit transaction updates delivered by Apple's Transaction.updates.\n * Fires on app launch if there are unfinished transactions, and for any updates afterward.\n * iOS only.\n */\n addListener(\n eventName: 'transactionUpdated',\n listenerFunc: (transaction: Transaction) => void,\n ): Promise<PluginListenerHandle>;\n /**\n * Listen for StoreKit transaction verification failures delivered by Apple's Transaction.updates.\n * Fires when the verification result is unverified.\n * iOS only.\n */\n addListener(\n eventName: 'transactionVerificationFailed',\n listenerFunc: (payload: TransactionVerificationFailedEvent) => void,\n ): Promise<PluginListenerHandle>;\n\n /** Remove all registered listeners */\n removeAllListeners(): Promise<void>;\n}\n"]}
|
|
@@ -20,7 +20,7 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
|
|
|
20
20
|
CAPPluginMethod(name: "isEntitledToOldBusinessModel", returnType: CAPPluginReturnPromise)
|
|
21
21
|
]
|
|
22
22
|
|
|
23
|
-
private let pluginVersion: String = "8.0.
|
|
23
|
+
private let pluginVersion: String = "8.0.14"
|
|
24
24
|
private var transactionUpdatesTask: Task<Void, Never>?
|
|
25
25
|
|
|
26
26
|
@objc func getPluginVersion(_ call: CAPPluginCall) {
|