-
-
Notifications
You must be signed in to change notification settings - Fork 648
/
iap.ts
929 lines (817 loc) · 26.9 KB
/
iap.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
import {NativeModules, Platform} from 'react-native';
import * as IapAmazon from './modules/amazon';
import * as IapAndroid from './modules/android';
import * as IapIos from './modules/ios';
import * as IapIosSk2 from './modules/iosSk2';
import {singleProductAndroidMap} from './types/android';
import {offerToRecord} from './types/apple';
import {
offerSk2Map,
ProductSk2,
productSk2Map,
subscriptionSk2Map,
transactionSk2ToPurchaseMap,
} from './types/appleSk2';
import {
fillProductsWithAdditionalData,
getAndroidModule,
getAndroidModuleType,
getIosModule,
getNativeModule,
isAmazon,
isIosStorekit2,
storekit1Mode,
storekit2Mode,
storekitHybridMode,
} from './internal';
import {
Product,
ProductPurchase,
ProductType,
Purchase,
PurchaseResult,
PurchaseStateAndroid,
RequestPurchase,
RequestSubscription,
Subscription,
SubscriptionAmazon,
SubscriptionAndroid,
SubscriptionIOS,
SubscriptionPlatform,
SubscriptionPurchase,
} from './types';
export {IapAndroid, IapAmazon, IapIos, IapIosSk2, isIosStorekit2};
const {RNIapIos, RNIapIosSk2, RNIapModule, RNIapAmazonModule} = NativeModules;
const ANDROID_ITEM_TYPE_SUBSCRIPTION = ProductType.subs;
const ANDROID_ITEM_TYPE_IAP = ProductType.inapp;
/**
* STOREKIT1_MODE: Will not enable Storekit 2 even if the device supports it. Thigs will work as before,
* minimum changes required in the migration guide (default)
* HYBRID_MODE: Will enable Storekit 2 for iOS devices > 15.0 but will fallback to Sk1 on older devices
* There are some edge cases that you need to handle in this case (described in migration guide). This mode
* is for developers that are migrating to Storekit 2 but want to keep supporting older versions.
* STOREKIT2_MODE: Will *only* enable Storekit 2. This disables Storekit 1. This is for apps that
* have already targeted a min version of 15 for their app.
*/
export type STOREKIT_OPTIONS =
| 'STOREKIT1_MODE'
| 'STOREKIT_HYBRID_MODE'
| 'STOREKIT2_MODE';
export const setup = ({
storekitMode = 'STOREKIT1_MODE',
}: {
storekitMode?: STOREKIT_OPTIONS;
} = {}) => {
switch (storekitMode) {
case 'STOREKIT1_MODE':
storekit1Mode();
break;
case 'STOREKIT2_MODE':
storekit2Mode();
break;
case 'STOREKIT_HYBRID_MODE':
storekitHybridMode();
break;
default:
break;
}
};
/**
* Init module for purchase flow. Required on Android. In ios it will check whether user canMakePayment.
* ## Usage
```tsx
import React, {useEffect} from 'react';
import {View} from 'react-native';
import {initConnection} from 'react-native-iap';
const App = () => {
useEffect(() => {
void initConnection();
}, []);
return <View />;
};
```
*/
export const initConnection = (): Promise<boolean> =>
getNativeModule().initConnection();
/**
* Disconnects from native SDK
* Usage
* ```tsx
import React, {useEffect} from 'react';
import {View} from 'react-native';
import {endConnection} from 'react-native-iap';
const App = () => {
useEffect(() => {
return () => {
void endConnection();
};
}, []);
return <View />;
};
```
* @returns {Promise<void>}
*/
export const endConnection = (): Promise<boolean> =>
getNativeModule().endConnection();
/**
* Consume all 'ghost' purchases (that is, pending payment that already failed but is still marked as pending in Play Store cache). Android only.
* @returns {Promise<boolean>}
*/
export const flushFailedPurchasesCachedAsPendingAndroid =
(): Promise<boolean> =>
getAndroidModule().flushFailedPurchasesCachedAsPending();
/**
* Get a list of products (consumable and non-consumable items, but not subscriptions)
## Usage
```ts
import React, {useState} from 'react';
import {Platform} from 'react-native';
import {getProducts, Product} from 'react-native-iap';
const skus = Platform.select({
ios: ['com.example.consumableIos'],
android: ['com.example.consumableAndroid'],
});
const App = () => {
const [products, setProducts] = useState<Product[]>([]);
const handleProducts = async () => {
const items = await getProducts({skus});
setProducts(items);
};
useEffect(() => {
void handleProducts();
}, []);
return (
<>
{products.map((product) => (
<Text key={product.productId}>{product.productId}</Text>
))}
</>
);
};
```
Just a few things to keep in mind:
- You can get your products in `componentDidMount`, `useEffect` or another appropriate area of your app.
- Since a user may start your app with a bad or no internet connection, preparing/getting the items more than once may be a good idea.
- If the user has no IAPs available when the app starts first, you may want to check again when the user enters your IAP store.
*/
export const getProducts = ({
skus,
}: {
skus: string[];
}): Promise<Array<Product>> => {
if (!skus?.length) {
return Promise.reject('"skus" is required');
}
return (
Platform.select({
ios: async () => {
let items: Product[];
if (isIosStorekit2()) {
items = ((await RNIapIosSk2.getItems(skus)) as ProductSk2[]).map(
productSk2Map,
);
} else {
items = (await RNIapIos.getItems(skus)) as Product[];
}
return items.filter((item: Product) => skus.includes(item.productId));
},
android: async () => {
const products = (
await getAndroidModule().getItemsByType(ANDROID_ITEM_TYPE_IAP, skus)
).map(singleProductAndroidMap);
return fillProductsWithAdditionalData(products);
},
}) || (() => Promise.reject(new Error('Unsupported Platform')))
)();
};
/**
* Get a list of subscriptions
* ## Usage
```tsx
import React, {useCallback} from 'react';
import {View} from 'react-native';
import {getSubscriptions} from 'react-native-iap';
const App = () => {
const subscriptions = useCallback(
async () =>
await getSubscriptions({skus:['com.example.product1', 'com.example.product2']}),
[],
);
return <View />;
};
```
*/
export const getSubscriptions = ({
skus,
}: {
skus: string[];
}): Promise<Subscription[]> => {
if (!skus?.length) {
return Promise.reject('"skus" is required');
}
return (
Platform.select({
ios: async (): Promise<SubscriptionIOS[]> => {
let items: SubscriptionIOS[];
if (isIosStorekit2()) {
items = ((await RNIapIosSk2.getItems(skus)) as ProductSk2[]).map(
subscriptionSk2Map,
);
} else {
items = (await RNIapIos.getItems(skus)) as SubscriptionIOS[];
}
items = items.filter((item: SubscriptionIOS) =>
skus.includes(item.productId),
);
return addSubscriptionPlatform(items, SubscriptionPlatform.ios);
},
android: async (): Promise<Subscription[]> => {
const androidPlatform = getAndroidModuleType();
let subscriptions = (await getAndroidModule().getItemsByType(
ANDROID_ITEM_TYPE_SUBSCRIPTION,
skus,
)) as SubscriptionAndroid[] | SubscriptionAmazon[];
switch (androidPlatform) {
case 'android': {
const castSubscriptions = subscriptions as SubscriptionAndroid[];
return addSubscriptionPlatform(
castSubscriptions,
SubscriptionPlatform.android,
);
}
case 'amazon':
let castSubscriptions = subscriptions as SubscriptionAmazon[];
castSubscriptions = await fillProductsWithAdditionalData(
castSubscriptions,
);
return addSubscriptionPlatform(
castSubscriptions,
SubscriptionPlatform.amazon,
);
case null:
default:
throw new Error(
`getSubscriptions received unknown platform ${androidPlatform}. Verify the logic in getAndroidModuleType`,
);
}
},
}) || (() => Promise.reject(new Error('Unsupported Platform')))
)();
};
/**
* Adds an extra property to subscriptions so we can distinguish the platform
* we retrieved them on.
*/
const addSubscriptionPlatform = <T>(
subscriptions: T[],
platform: SubscriptionPlatform,
): T[] => {
return subscriptions.map((subscription) => ({...subscription, platform}));
};
/**
* Gets an inventory of purchases made by the user regardless of consumption status
* ## Usage
```tsx
import React, {useCallback} from 'react';
import {View} from 'react-native';
import {getPurchaseHistory} from 'react-native-iap';
const App = () => {
const history = useCallback(
async () =>
await getPurchaseHistory([
'com.example.product1',
'com.example.product2',
]),
[],
);
return <View />;
};
```
@param {alsoPublishToEventListener}:boolean. (IOS Sk2 only) When `true`, every element will also be pushed to the purchaseUpdated listener.
Note that this is only for backaward compatiblity. It won't publish to transactionUpdated (Storekit2) Defaults to `false`
@param {automaticallyFinishRestoredTransactions}:boolean. (IOS Sk1 only) When `true`, all the transactions that are returned are automatically
finished. This means that if you call this method again you won't get the same result on the same device. On the other hand, if `false` you'd
have to manually finish the returned transaction once you have delivered the content to your user.
@param {onlyIncludeActiveItems}:boolean. (IOS Sk2 only). Defaults to false, meaning that it will return one transaction per item purchased.
@See https://developer.apple.com/documentation/storekit/transaction/3851204-currententitlements for details
*/
export const getPurchaseHistory = ({
alsoPublishToEventListener = false,
automaticallyFinishRestoredTransactions = true,
onlyIncludeActiveItems = false,
}: {
alsoPublishToEventListener?: boolean;
automaticallyFinishRestoredTransactions?: boolean;
onlyIncludeActiveItems?: boolean;
} = {}): Promise<Purchase[]> =>
(
Platform.select({
ios: async () => {
if (isIosStorekit2()) {
return Promise.resolve(
(
await RNIapIosSk2.getAvailableItems(
alsoPublishToEventListener,
onlyIncludeActiveItems,
)
).map(transactionSk2ToPurchaseMap),
);
} else {
return RNIapIos.getAvailableItems(
automaticallyFinishRestoredTransactions,
);
}
},
android: async () => {
if (RNIapAmazonModule) {
return await RNIapAmazonModule.getAvailableItems();
}
const products = await RNIapModule.getPurchaseHistoryByType(
ANDROID_ITEM_TYPE_IAP,
);
const subscriptions = await RNIapModule.getPurchaseHistoryByType(
ANDROID_ITEM_TYPE_SUBSCRIPTION,
);
return products.concat(subscriptions);
},
}) || (() => Promise.resolve([]))
)();
/**
* Get all purchases made by the user (either non-consumable, or haven't been consumed yet)
* ## Usage
```tsx
import React, {useCallback} from 'react';
import {View} from 'react-native';
import {getAvailablePurchases} from 'react-native-iap';
const App = () => {
const availablePurchases = useCallback(
async () => await getAvailablePurchases(),
[],
);
return <View />;
};
```
## Restoring purchases
You can use `getAvailablePurchases()` to do what's commonly understood as "restoring" purchases.
:::note
For debugging you may want to consume all items, you have then to iterate over the purchases returned by `getAvailablePurchases()`.
:::
:::warning
Beware that if you consume an item without having recorded the purchase in your database the user may have paid for something without getting it delivered and you will have no way to recover the receipt to validate and restore their purchase.
:::
```tsx
import React from 'react';
import {Button} from 'react-native';
import {getAvailablePurchases,finishTransaction} from 'react-native-iap';
const App = () => {
handleRestore = async () => {
try {
const purchases = await getAvailablePurchases();
const newState = {premium: false, ads: true};
let titles = [];
await Promise.all(purchases.map(async purchase => {
switch (purchase.productId) {
case 'com.example.premium':
newState.premium = true;
titles.push('Premium Version');
break;
case 'com.example.no_ads':
newState.ads = false;
titles.push('No Ads');
break;
case 'com.example.coins100':
await finishTransaction({purchase});
CoinStore.addCoins(100);
}
}));
Alert.alert(
'Restore Successful',
`You successfully restored the following purchases: ${titles.join(', ')}`,
);
} catch (error) {
console.warn(error);
Alert.alert(error.message);
}
};
return (
<Button title="Restore purchases" onPress={handleRestore} />
)
};
```
@param {alsoPublishToEventListener}:boolean When `true`, every element will also be pushed to the purchaseUpdated listener.
Note that this is only for backaward compatiblity. It won't publish to transactionUpdated (Storekit2) Defaults to `false`
@param {onlyIncludeActiveItems}:boolean. (IOS Sk2 only). Defaults to true, meaning that it will return the transaction if suscription has not expired.
@See https://developer.apple.com/documentation/storekit/transaction/3851204-currententitlements for details
*
*/
export const getAvailablePurchases = ({
alsoPublishToEventListener = false,
automaticallyFinishRestoredTransactions = false,
onlyIncludeActiveItems = true,
}: {
alsoPublishToEventListener?: boolean;
automaticallyFinishRestoredTransactions?: boolean;
onlyIncludeActiveItems?: boolean;
} = {}): Promise<Purchase[]> =>
(
Platform.select({
ios: async () => {
if (isIosStorekit2()) {
return Promise.resolve(
(
await RNIapIosSk2.getAvailableItems(
alsoPublishToEventListener,
onlyIncludeActiveItems,
)
).map(transactionSk2ToPurchaseMap),
);
} else {
return RNIapIos.getAvailableItems(
automaticallyFinishRestoredTransactions,
);
}
},
android: async () => {
if (RNIapAmazonModule) {
return await RNIapAmazonModule.getAvailableItems();
}
const products = await RNIapModule.getAvailableItemsByType(
ANDROID_ITEM_TYPE_IAP,
);
const subscriptions = await RNIapModule.getAvailableItemsByType(
ANDROID_ITEM_TYPE_SUBSCRIPTION,
);
return products.concat(subscriptions);
},
}) || (() => Promise.resolve([]))
)();
/**
* Request a purchase for product. This will be received in `PurchaseUpdatedListener`.
* Request a purchase for a product (consumables or non-consumables).
The response will be received through the `PurchaseUpdatedListener`.
:::note
`andDangerouslyFinishTransactionAutomatically` defaults to false. We recommend
always keeping at false, and verifying the transaction receipts on the server-side.
:::
## Signature
```ts
requestPurchase(
The product's sku/ID
sku,
* You should set this to false and call finishTransaction manually when you have delivered the purchased goods to the user.
* @default false
andDangerouslyFinishTransactionAutomaticallyIOS = false,
/** Specifies an optional obfuscated string that is uniquely associated with the user's account in your app.
obfuscatedAccountIdAndroid,
Specifies an optional obfuscated string that is uniquely associated with the user's profile in your app.
obfuscatedProfileIdAndroid,
The purchaser's user ID
applicationUsername,
): Promise<ProductPurchase>;
```
## Usage
```tsx
import React, {useCallback} from 'react';
import {Button} from 'react-native';
import {requestPurchase, Product, Sku, getProducts} from 'react-native-iap';
const App = () => {
const products = useCallback(
async () => getProducts({skus:['com.example.product']}),
[],
);
const handlePurchase = async (sku: Sku) => {
await requestPurchase({sku});
};
return (
<>
{products.map((product) => (
<Button
key={product.productId}
title="Buy product"
onPress={() => handlePurchase(product.productId)}
/>
))}
</>
);
};
```
*/
export const requestPurchase = (
request: RequestPurchase,
): Promise<ProductPurchase | ProductPurchase[] | void> =>
(
Platform.select({
ios: async () => {
if (!('sku' in request)) {
throw new Error('sku is required for iOS purchase');
}
const {
sku,
andDangerouslyFinishTransactionAutomaticallyIOS = false,
appAccountToken,
quantity,
withOffer,
} = request;
if (andDangerouslyFinishTransactionAutomaticallyIOS) {
console.warn(
'You are dangerously allowing react-native-iap to finish your transaction automatically. You should set andDangerouslyFinishTransactionAutomatically to false when calling requestPurchase and call finishTransaction manually when you have delivered the purchased goods to the user. It defaults to true to provide backwards compatibility. Will default to false in version 4.0.0.',
);
}
if (isIosStorekit2()) {
const offer = offerSk2Map(withOffer);
const purchase = transactionSk2ToPurchaseMap(
await RNIapIosSk2.buyProduct(
sku,
andDangerouslyFinishTransactionAutomaticallyIOS,
appAccountToken,
quantity ?? -1,
offer,
),
);
return Promise.resolve(purchase);
} else {
return RNIapIos.buyProduct(
sku,
andDangerouslyFinishTransactionAutomaticallyIOS,
appAccountToken,
quantity ?? -1,
offerToRecord(withOffer),
);
}
},
android: async () => {
if (isAmazon) {
if (!('sku' in request)) {
throw new Error('sku is required for Amazon purchase');
}
const {sku} = request;
return RNIapAmazonModule.buyItemByType(sku);
} else {
if (!('skus' in request) || !request.skus.length) {
throw new Error('skus is required for Android purchase');
}
const {
skus,
obfuscatedAccountIdAndroid,
obfuscatedProfileIdAndroid,
isOfferPersonalized,
} = request;
return getAndroidModule().buyItemByType(
ANDROID_ITEM_TYPE_IAP,
skus,
undefined,
-1,
obfuscatedAccountIdAndroid,
obfuscatedProfileIdAndroid,
[],
isOfferPersonalized ?? false,
);
}
},
}) || Promise.resolve
)();
/**
* Request a purchase for product. This will be received in `PurchaseUpdatedListener`.
* Request a purchase for a subscription.
The response will be received through the `PurchaseUpdatedListener`.
:::note
`andDangerouslyFinishTransactionAutomatically` defaults to false. We recommend
always keeping at false, and verifying the transaction receipts on the server-side.
:::
## Signature
```ts
requestSubscription(
The product's sku/ID
sku,
* You should set this to false and call finishTransaction manually when you have delivered the purchased goods to the user.
* @default false
andDangerouslyFinishTransactionAutomaticallyIOS = false,
purchaseToken that the user is upgrading or downgrading from (Android).
purchaseTokenAndroid,
UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY, IMMEDIATE_WITH_TIME_PRORATION, IMMEDIATE_AND_CHARGE_PRORATED_PRICE, IMMEDIATE_WITHOUT_PRORATION, DEFERRED
prorationModeAndroid = -1,
/** Specifies an optional obfuscated string that is uniquely associated with the user's account in your app.
obfuscatedAccountIdAndroid,
Specifies an optional obfuscated string that is uniquely associated with the user's profile in your app.
obfuscatedProfileIdAndroid,
The purchaser's user ID
applicationUsername,
): Promise<SubscriptionPurchase>
```
## Usage
```tsx
import React, {useCallback} from 'react';
import {Button} from 'react-native';
import {
requestSubscription,
Product,
Sku,
getSubscriptions,
} from 'react-native-iap';
const App = () => {
const subscriptions = useCallback(
async () => getSubscriptions(['com.example.subscription']),
[],
);
const handlePurchase = async (sku: Sku) => {
await requestSubscription({sku});
};
return (
<>
{subscriptions.map((subscription) => (
<Button
key={subscription.productId}
title="Buy subscription"
onPress={() => handlePurchase(subscription.productId)}
/>
))}
</>
);
};
```
*/
export const requestSubscription = (
request: RequestSubscription,
): Promise<SubscriptionPurchase | SubscriptionPurchase[] | null | void> =>
(
Platform.select({
ios: async () => {
if (!('sku' in request)) {
throw new Error('sku is required for iOS subscriptions');
}
const {
sku,
andDangerouslyFinishTransactionAutomaticallyIOS = false,
appAccountToken,
quantity,
withOffer,
} = request;
if (andDangerouslyFinishTransactionAutomaticallyIOS) {
console.warn(
'You are dangerously allowing react-native-iap to finish your transaction automatically. You should set andDangerouslyFinishTransactionAutomatically to false when calling requestPurchase and call finishTransaction manually when you have delivered the purchased goods to the user. It defaults to true to provide backwards compatibility. Will default to false in version 4.0.0.',
);
}
if (isIosStorekit2()) {
const offer = offerSk2Map(withOffer);
const purchase = transactionSk2ToPurchaseMap(
await RNIapIosSk2.buyProduct(
sku,
andDangerouslyFinishTransactionAutomaticallyIOS,
appAccountToken,
quantity ?? -1,
offer,
),
);
return Promise.resolve(purchase);
} else {
return RNIapIos.buyProduct(
sku,
andDangerouslyFinishTransactionAutomaticallyIOS,
appAccountToken,
quantity ?? -1,
offerToRecord(withOffer),
);
}
},
android: async () => {
if (isAmazon) {
if (!('sku' in request)) {
throw new Error('sku is required for Amazon subscriptions');
}
const {sku} = request;
return RNIapAmazonModule.buyItemByType(sku);
} else {
if (
!('subscriptionOffers' in request) ||
request.subscriptionOffers.length === 0
) {
throw new Error(
'subscriptionOffers are required for Google Play subscriptions',
);
}
const {
subscriptionOffers,
purchaseTokenAndroid,
prorationModeAndroid = -1,
obfuscatedAccountIdAndroid,
obfuscatedProfileIdAndroid,
isOfferPersonalized,
} = request;
return RNIapModule.buyItemByType(
ANDROID_ITEM_TYPE_SUBSCRIPTION,
subscriptionOffers?.map((so) => so.sku),
purchaseTokenAndroid,
prorationModeAndroid,
obfuscatedAccountIdAndroid,
obfuscatedProfileIdAndroid,
subscriptionOffers?.map((so) => so.offerToken),
isOfferPersonalized ?? false,
);
}
},
}) || (() => Promise.resolve(null))
)();
/**
* Finish Transaction (both platforms)
* Abstracts Finish Transaction
* iOS: Tells StoreKit that you have delivered the purchase to the user and StoreKit can now let go of the transaction.
* Call this after you have persisted the purchased state to your server or local data in your app.
* `react-native-iap` will continue to deliver the purchase updated events with the successful purchase until you finish the transaction. **Even after the app has relaunched.**
* Android: it will consume purchase for consumables and acknowledge purchase for non-consumables.
*
```tsx
import React from 'react';
import {Button} from 'react-native';
import {finishTransaction} from 'react-native-iap';
const App = () => {
const handlePurchase = async () => {
// ... handle the purchase request
const result = finishTransaction({purchase});
};
return <Button title="Buy product" onPress={handlePurchase} />;
};
```
@returns {Promise<PurchaseResult | boolean>} Android: PurchaseResult, iOS: true
*/
export const finishTransaction = ({
purchase,
isConsumable,
developerPayloadAndroid,
}: {
purchase: Purchase;
isConsumable?: boolean;
developerPayloadAndroid?: string;
}): Promise<PurchaseResult | boolean> => {
return (
Platform.select({
ios: async () => {
const transactionId = purchase.transactionId;
if (!transactionId) {
return Promise.reject(
new Error('transactionId required to finish iOS transaction'),
);
}
await getIosModule().finishTransaction(transactionId);
return Promise.resolve(true);
},
android: async () => {
if (purchase?.purchaseToken) {
if (isConsumable) {
return getAndroidModule().consumeProduct(
purchase.purchaseToken,
developerPayloadAndroid,
);
} else if (
purchase.userIdAmazon ||
(!purchase.isAcknowledgedAndroid &&
purchase.purchaseStateAndroid === PurchaseStateAndroid.PURCHASED)
) {
return getAndroidModule().acknowledgePurchase(
purchase.purchaseToken,
developerPayloadAndroid,
);
} else {
return Promise.reject(
new Error('purchase is not suitable to be purchased'),
);
}
}
return Promise.reject(
new Error('purchase is not suitable to be purchased'),
);
},
}) || (() => Promise.reject(new Error('Unsupported Platform')))
)();
};
/**
* Deeplinks to native interface that allows users to manage their subscriptions
*
*/
export const deepLinkToSubscriptions = ({
sku,
isAmazonDevice = true,
}: {
sku?: string;
isAmazonDevice?: boolean;
}): Promise<void> => {
return (
Platform.select({
ios: async () => {
IapIos.deepLinkToSubscriptionsIos();
},
android: async () => {
if (isAmazon) {
IapAmazon.deepLinkToSubscriptionsAmazon({isAmazonDevice});
} else if (sku) {
IapAndroid.deepLinkToSubscriptionsAndroid({sku});
} else {
Promise.reject(
new Error(
'Sku is required to locate subscription in Android Store',
),
);
}
},
}) || (() => Promise.reject(new Error('Unsupported Platform')))
)();
};