react-native-iap 8.5.1 → 8.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +4 -20
  2. package/RNIap.podspec +33 -18
  3. package/android/build.gradle +137 -38
  4. package/android/gradle.properties +8 -0
  5. package/ios/RNIapIos-Bridging-Header.h +2 -0
  6. package/ios/RNIapIos.m +14 -2
  7. package/ios/RNIapIos.swift +903 -881
  8. package/ios/{RNIap.xcodeproj → RNIapIos.xcodeproj}/project.pbxproj +29 -116
  9. package/lib/commonjs/__test__/iap.test.js +21 -0
  10. package/lib/commonjs/__test__/iap.test.js.map +1 -0
  11. package/lib/commonjs/hooks/useIAP.js +78 -0
  12. package/lib/commonjs/hooks/useIAP.js.map +1 -0
  13. package/lib/commonjs/hooks/withIAPContext.js +92 -0
  14. package/lib/commonjs/hooks/withIAPContext.js.map +1 -0
  15. package/lib/commonjs/iap.js +577 -0
  16. package/lib/commonjs/iap.js.map +1 -0
  17. package/lib/commonjs/index.js +59 -0
  18. package/lib/commonjs/index.js.map +1 -0
  19. package/lib/commonjs/types/amazon.js +2 -0
  20. package/lib/commonjs/types/amazon.js.map +1 -0
  21. package/lib/commonjs/types/android.js +55 -0
  22. package/lib/commonjs/types/android.js.map +1 -0
  23. package/lib/commonjs/types/apple.js +165 -0
  24. package/lib/commonjs/types/apple.js.map +1 -0
  25. package/lib/commonjs/types/index.js +59 -0
  26. package/lib/commonjs/types/index.js.map +1 -0
  27. package/lib/module/__test__/iap.test.js +17 -0
  28. package/lib/module/__test__/iap.test.js.map +1 -0
  29. package/lib/module/hooks/useIAP.js +68 -0
  30. package/lib/module/hooks/useIAP.js.map +1 -0
  31. package/lib/module/hooks/withIAPContext.js +76 -0
  32. package/lib/module/hooks/withIAPContext.js.map +1 -0
  33. package/lib/module/iap.js +488 -0
  34. package/lib/module/iap.js.map +1 -0
  35. package/lib/module/index.js +6 -0
  36. package/lib/module/index.js.map +1 -0
  37. package/lib/module/types/amazon.js +2 -0
  38. package/lib/module/types/amazon.js.map +1 -0
  39. package/lib/module/types/android.js +44 -0
  40. package/lib/module/types/android.js.map +1 -0
  41. package/lib/module/types/apple.js +153 -0
  42. package/lib/module/types/apple.js.map +1 -0
  43. package/lib/module/types/index.js +48 -0
  44. package/lib/module/types/index.js.map +1 -0
  45. package/{src → lib/typescript}/__test__/iap.test.d.ts +0 -0
  46. package/{src → lib/typescript}/hooks/useIAP.d.ts +1 -1
  47. package/{src → lib/typescript}/hooks/withIAPContext.d.ts +1 -1
  48. package/{src → lib/typescript}/iap.d.ts +13 -11
  49. package/{src → lib/typescript}/index.d.ts +2 -1
  50. package/{src → lib/typescript}/types/amazon.d.ts +0 -0
  51. package/{src → lib/typescript}/types/android.d.ts +0 -0
  52. package/{src → lib/typescript}/types/apple.d.ts +0 -0
  53. package/{src → lib/typescript}/types/index.d.ts +25 -4
  54. package/package.json +87 -56
  55. package/src/__test__/iap.test.ts +20 -0
  56. package/src/hooks/useIAP.ts +130 -0
  57. package/src/hooks/withIAPContext.tsx +160 -0
  58. package/src/iap.ts +686 -0
  59. package/src/{index.js → index.ts} +4 -1
  60. package/src/types/amazon.ts +23 -0
  61. package/src/types/android.ts +51 -0
  62. package/src/types/apple.ts +467 -0
  63. package/src/types/index.ts +185 -0
  64. package/.editorconfig +0 -10
  65. package/.flowconfig +0 -11
  66. package/.monolinterrc +0 -3
  67. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  68. package/android/gradle/wrapper/gradle-wrapper.properties +0 -6
  69. package/android/gradlew +0 -160
  70. package/android/gradlew.bat +0 -90
  71. package/babel.config.js +0 -10
  72. package/index.d.ts +0 -3
  73. package/index.js +0 -3
  74. package/index.js.flow +0 -9
  75. package/ios/RNIap.xcodeproj/xcshareddata/xcschemes/RNIap.xcscheme +0 -80
  76. package/jest.config.js +0 -194
  77. package/src/__test__/iap.test.js +0 -59
  78. package/src/hooks/useIAP.js +0 -141
  79. package/src/hooks/withIAPContext.js +0 -150
  80. package/src/iap.js +0 -631
  81. package/src/types/amazon.js +0 -1
  82. package/src/types/android.js +0 -22
  83. package/src/types/apple.js +0 -165
  84. package/src/types/index.js +0 -40
  85. package/test/mocks/react-native-modules.js +0 -14
package/src/iap.ts ADDED
@@ -0,0 +1,686 @@
1
+ import {
2
+ EmitterSubscription,
3
+ Linking,
4
+ NativeEventEmitter,
5
+ NativeModules,
6
+ Platform,
7
+ } from 'react-native';
8
+
9
+ import type * as Amazon from './types/amazon';
10
+ import type * as Android from './types/android';
11
+ import type * as Apple from './types/apple';
12
+ import {ReceiptValidationStatus} from './types/apple';
13
+ import type {
14
+ InAppPurchase,
15
+ Product,
16
+ ProductCommon,
17
+ ProductPurchase,
18
+ PurchaseError,
19
+ PurchaseResult,
20
+ RequestPurchase,
21
+ RequestSubscription,
22
+ Subscription,
23
+ SubscriptionPurchase,
24
+ } from './types';
25
+ import {
26
+ IAPErrorCode,
27
+ InstallSourceAndroid,
28
+ PurchaseStateAndroid,
29
+ } from './types';
30
+
31
+ const {RNIapIos, RNIapModule, RNIapAmazonModule} = NativeModules;
32
+ const isAndroid = Platform.OS === 'android';
33
+ const ANDROID_ITEM_TYPE_SUBSCRIPTION = 'subs';
34
+ const ANDROID_ITEM_TYPE_IAP = 'inapp';
35
+
36
+ export const getInstallSourceAndroid = (): InstallSourceAndroid => {
37
+ return RNIapModule
38
+ ? InstallSourceAndroid.GOOGLE_PLAY
39
+ : InstallSourceAndroid.AMAZON;
40
+ };
41
+
42
+ const checkNativeAndroidAvailable = (): void => {
43
+ if (!RNIapModule && !RNIapAmazonModule) {
44
+ throw new Error(IAPErrorCode.E_IAP_NOT_AVAILABLE);
45
+ }
46
+ };
47
+
48
+ const getAndroidModule = (): typeof RNIapModule | typeof RNIapAmazonModule => {
49
+ checkNativeAndroidAvailable();
50
+
51
+ return RNIapModule ? RNIapModule : RNIapAmazonModule;
52
+ };
53
+
54
+ const checkNativeIOSAvailable = (): void => {
55
+ if (!RNIapIos) {
56
+ throw new Error(IAPErrorCode.E_IAP_NOT_AVAILABLE);
57
+ }
58
+ };
59
+
60
+ const getIosModule = (): typeof RNIapIos => {
61
+ checkNativeIOSAvailable();
62
+
63
+ return RNIapIos;
64
+ };
65
+
66
+ const getNativeModule = ():
67
+ | typeof RNIapModule
68
+ | typeof RNIapAmazonModule
69
+ | typeof RNIapIos => {
70
+ if (isAndroid) {
71
+ return getAndroidModule();
72
+ }
73
+
74
+ return getIosModule();
75
+ };
76
+
77
+ /**
78
+ * Init module for purchase flow. Required on Android. In ios it will check whether user canMakePayment.
79
+ * @returns {Promise<boolean>}
80
+ */
81
+ export const initConnection = (): Promise<boolean> =>
82
+ getNativeModule().initConnection();
83
+
84
+ /**
85
+ * End module for purchase flow.
86
+ * @returns {Promise<void>}
87
+ */
88
+ export const endConnection = (): Promise<void> =>
89
+ getNativeModule().endConnection();
90
+
91
+ /**
92
+ * Consume all 'ghost' purchases (that is, pending payment that already failed but is still marked as pending in Play Store cache). Android only.
93
+ * @returns {Promise<boolean>}
94
+ */
95
+ export const flushFailedPurchasesCachedAsPendingAndroid = (): Promise<
96
+ string[]
97
+ > => getAndroidModule().flushFailedPurchasesCachedAsPending();
98
+
99
+ /**
100
+ * Fill products with additional data
101
+ * @param {Array<ProductCommon>} products Products
102
+ */
103
+ const fillProductsAdditionalData = async (
104
+ products: Array<ProductCommon>,
105
+ ): Promise<Array<ProductCommon>> => {
106
+ // Amazon
107
+ if (RNIapAmazonModule) {
108
+ // On amazon we must get the user marketplace to detect the currency
109
+ const user = await RNIapAmazonModule.getUser();
110
+
111
+ const currencies = {
112
+ CA: 'CAD',
113
+ ES: 'EUR',
114
+ AU: 'AUD',
115
+ DE: 'EUR',
116
+ IN: 'INR',
117
+ US: 'USD',
118
+ JP: 'JPY',
119
+ GB: 'GBP',
120
+ IT: 'EUR',
121
+ BR: 'BRL',
122
+ FR: 'EUR',
123
+ };
124
+
125
+ const currency =
126
+ currencies[user.userMarketplaceAmazon as keyof typeof currencies];
127
+
128
+ // Add currency to products
129
+ products.forEach((product) => {
130
+ if (currency) {
131
+ product.currency = currency;
132
+ }
133
+ });
134
+ }
135
+
136
+ return products;
137
+ };
138
+
139
+ /**
140
+ * Get a list of products (consumable and non-consumable items, but not subscriptions)
141
+ * @param {string[]} skus The item skus
142
+ * @returns {Promise<Product[]>}
143
+ */
144
+ export const getProducts = (skus: string[]): Promise<Array<Product>> =>
145
+ (
146
+ Platform.select({
147
+ ios: async () => {
148
+ const items = await getIosModule().getItems(skus);
149
+
150
+ return items.filter(
151
+ (item: Product) =>
152
+ skus.includes(item.productId) && item.type === 'iap',
153
+ );
154
+ },
155
+ android: async () => {
156
+ const products = await getAndroidModule().getItemsByType(
157
+ ANDROID_ITEM_TYPE_IAP,
158
+ skus,
159
+ );
160
+
161
+ return fillProductsAdditionalData(products);
162
+ },
163
+ }) || Promise.resolve
164
+ )();
165
+
166
+ /**
167
+ * Get a list of subscriptions
168
+ * @param {string[]} skus The item skus
169
+ * @returns {Promise<Subscription[]>}
170
+ */
171
+ export const getSubscriptions = (skus: string[]): Promise<Subscription[]> =>
172
+ (
173
+ Platform.select({
174
+ ios: async () => {
175
+ const items = await getIosModule().getItems(skus);
176
+
177
+ return items.filter(
178
+ (item: Subscription) =>
179
+ skus.includes(item.productId) && item.type === 'subs',
180
+ );
181
+ },
182
+ android: async () => {
183
+ const subscriptions = await getAndroidModule().getItemsByType(
184
+ ANDROID_ITEM_TYPE_SUBSCRIPTION,
185
+ skus,
186
+ );
187
+
188
+ return fillProductsAdditionalData(subscriptions);
189
+ },
190
+ }) || Promise.resolve
191
+ )();
192
+
193
+ /**
194
+ * Gets an inventory of purchases made by the user regardless of consumption status
195
+ * @returns {Promise<(InAppPurchase | SubscriptionPurchase)[]>}
196
+ */
197
+ export const getPurchaseHistory = (): Promise<
198
+ (InAppPurchase | SubscriptionPurchase)[]
199
+ > =>
200
+ (
201
+ Platform.select({
202
+ ios: async () => {
203
+ return getIosModule().getAvailableItems();
204
+ },
205
+ android: async () => {
206
+ if (RNIapAmazonModule) {
207
+ return await RNIapAmazonModule.getAvailableItems();
208
+ }
209
+
210
+ const products = await getAndroidModule().getPurchaseHistoryByType(
211
+ ANDROID_ITEM_TYPE_IAP,
212
+ );
213
+
214
+ const subscriptions = await getAndroidModule().getPurchaseHistoryByType(
215
+ ANDROID_ITEM_TYPE_SUBSCRIPTION,
216
+ );
217
+
218
+ return products.concat(subscriptions);
219
+ },
220
+ }) || Promise.resolve
221
+ )();
222
+
223
+ /**
224
+ * Get all purchases made by the user (either non-consumable, or haven't been consumed yet)
225
+ * @returns {Promise<(InAppPurchase | SubscriptionPurchase)[]>}
226
+ */
227
+ export const getAvailablePurchases = (): Promise<
228
+ (InAppPurchase | SubscriptionPurchase)[]
229
+ > =>
230
+ (
231
+ Platform.select({
232
+ ios: async () => {
233
+ return getIosModule().getAvailableItems();
234
+ },
235
+ android: async () => {
236
+ if (RNIapAmazonModule) {
237
+ return await RNIapAmazonModule.getAvailableItems();
238
+ }
239
+
240
+ const products = await getAndroidModule().getAvailableItemsByType(
241
+ ANDROID_ITEM_TYPE_IAP,
242
+ );
243
+
244
+ const subscriptions = await getAndroidModule().getAvailableItemsByType(
245
+ ANDROID_ITEM_TYPE_SUBSCRIPTION,
246
+ );
247
+
248
+ return products.concat(subscriptions);
249
+ },
250
+ }) || Promise.resolve
251
+ )();
252
+
253
+ /**
254
+ * Request a purchase for product. This will be received in `PurchaseUpdatedListener`.
255
+ * @param {string} sku The product's sku/ID
256
+ * @param {string} [applicationUsername] The purchaser's user ID
257
+ * @param {boolean} [andDangerouslyFinishTransactionAutomaticallyIOS] You should set this to false 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.
258
+ * @param {string} [obfuscatedAccountIdAndroid] Specifies an optional obfuscated string that is uniquely associated with the user's account in your app.
259
+ * @param {string} [obfuscatedProfileIdAndroid] Specifies an optional obfuscated string that is uniquely associated with the user's profile in your app.
260
+ * @returns {Promise<InAppPurchase>}
261
+ */
262
+
263
+ export const requestPurchase = ({
264
+ sku,
265
+ andDangerouslyFinishTransactionAutomaticallyIOS = false,
266
+ obfuscatedAccountIdAndroid,
267
+ obfuscatedProfileIdAndroid,
268
+ applicationUsername,
269
+ }: RequestPurchase): Promise<InAppPurchase> =>
270
+ (
271
+ Platform.select({
272
+ ios: async () => {
273
+ if (andDangerouslyFinishTransactionAutomaticallyIOS) {
274
+ console.warn(
275
+ '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.',
276
+ );
277
+ }
278
+
279
+ return getIosModule().buyProduct(
280
+ sku,
281
+ andDangerouslyFinishTransactionAutomaticallyIOS,
282
+ applicationUsername,
283
+ );
284
+ },
285
+ android: async () => {
286
+ return getAndroidModule().buyItemByType(
287
+ ANDROID_ITEM_TYPE_IAP,
288
+ sku,
289
+ null,
290
+ 0,
291
+ obfuscatedAccountIdAndroid,
292
+ obfuscatedProfileIdAndroid,
293
+ );
294
+ },
295
+ }) || Promise.resolve
296
+ )();
297
+
298
+ /**
299
+ * Request a purchase for product. This will be received in `PurchaseUpdatedListener`.
300
+ * @param {string} [sku] The product's sku/ID
301
+ * @param {string} [applicationUsername] The purchaser's user ID
302
+ * @param {boolean} [andDangerouslyFinishTransactionAutomaticallyIOS] You should set this to false 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.
303
+ * @param {string} [purchaseTokenAndroid] purchaseToken that the user is upgrading or downgrading from (Android).
304
+ * @param {ProrationModesAndroid} [prorationModeAndroid] UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY, IMMEDIATE_WITH_TIME_PRORATION, IMMEDIATE_AND_CHARGE_PRORATED_PRICE, IMMEDIATE_WITHOUT_PRORATION, DEFERRED
305
+ * @param {string} [obfuscatedAccountIdAndroid] Specifies an optional obfuscated string that is uniquely associated with the user's account in your app.
306
+ * @param {string} [obfuscatedProfileIdAndroid] Specifies an optional obfuscated string that is uniquely associated with the user's profile in your app.
307
+ * @returns {Promise<SubscriptionPurchase | null>} Promise resolves to null when using proratioModesAndroid=DEFERRED, and to a SubscriptionPurchase otherwise
308
+ */
309
+ export const requestSubscription = ({
310
+ sku,
311
+ andDangerouslyFinishTransactionAutomaticallyIOS = false,
312
+ purchaseTokenAndroid,
313
+ prorationModeAndroid = -1,
314
+ obfuscatedAccountIdAndroid,
315
+ obfuscatedProfileIdAndroid,
316
+ applicationUsername,
317
+ }: RequestSubscription): Promise<SubscriptionPurchase | null> =>
318
+ (
319
+ Platform.select({
320
+ ios: async () => {
321
+ if (andDangerouslyFinishTransactionAutomaticallyIOS) {
322
+ console.warn(
323
+ '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.',
324
+ );
325
+ }
326
+
327
+ return getIosModule().buyProduct(
328
+ sku,
329
+ andDangerouslyFinishTransactionAutomaticallyIOS,
330
+ applicationUsername,
331
+ );
332
+ },
333
+ android: async () => {
334
+ return getAndroidModule().buyItemByType(
335
+ ANDROID_ITEM_TYPE_SUBSCRIPTION,
336
+ sku,
337
+ purchaseTokenAndroid,
338
+ prorationModeAndroid,
339
+ obfuscatedAccountIdAndroid,
340
+ obfuscatedProfileIdAndroid,
341
+ );
342
+ },
343
+ }) || Promise.resolve
344
+ )();
345
+
346
+ /**
347
+ * Request a purchase for product. This will be received in `PurchaseUpdatedListener`.
348
+ * @param {string} sku The product's sku/ID
349
+ * @returns {Promise<void>}
350
+ */
351
+ export const requestPurchaseWithQuantityIOS = (
352
+ sku: string,
353
+ quantity: number,
354
+ ): Promise<InAppPurchase> =>
355
+ getIosModule().buyProductWithQuantityIOS(sku, quantity);
356
+
357
+ /**
358
+ * Finish Transaction (both platforms)
359
+ * Abstracts Finish Transaction
360
+ * iOS: Tells StoreKit that you have delivered the purchase to the user and StoreKit can now let go of the transaction.
361
+ * Call this after you have persisted the purchased state to your server or local data in your app.
362
+ * `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.**
363
+ * Android: it will consume purchase for consumables and acknowledge purchase for non-consumables.
364
+ * @param {object} purchase The purchase that you would like to finish.
365
+ * @param {boolean} isConsumable Checks if purchase is consumable. Has effect on `android`.
366
+ * @param {string} developerPayloadAndroid Android developerPayload.
367
+ * @returns {Promise<string | void> }
368
+ */
369
+ export const finishTransaction = (
370
+ purchase: InAppPurchase | ProductPurchase,
371
+ isConsumable?: boolean,
372
+ developerPayloadAndroid?: string,
373
+ ): Promise<string | void> => {
374
+ return (
375
+ Platform.select({
376
+ ios: async () => {
377
+ return getIosModule().finishTransaction(purchase.transactionId);
378
+ },
379
+ android: async () => {
380
+ if (purchase) {
381
+ if (isConsumable) {
382
+ return getAndroidModule().consumeProduct(
383
+ purchase.purchaseToken,
384
+ developerPayloadAndroid,
385
+ );
386
+ } else if (
387
+ purchase.userIdAmazon ||
388
+ (!purchase.isAcknowledgedAndroid &&
389
+ purchase.purchaseStateAndroid === PurchaseStateAndroid.PURCHASED)
390
+ ) {
391
+ return getAndroidModule().acknowledgePurchase(
392
+ purchase.purchaseToken,
393
+ developerPayloadAndroid,
394
+ );
395
+ } else {
396
+ throw new Error('purchase is not suitable to be purchased');
397
+ }
398
+ } else {
399
+ throw new Error('purchase is not assigned');
400
+ }
401
+ },
402
+ }) || Promise.resolve
403
+ )();
404
+ };
405
+
406
+ /**
407
+ * Clear Transaction (iOS only)
408
+ * Finish remaining transactions. Related to issue #257 and #801
409
+ * link : https://github.com/dooboolab/react-native-iap/issues/257
410
+ * https://github.com/dooboolab/react-native-iap/issues/801
411
+ * @returns {Promise<void>}
412
+ */
413
+ export const clearTransactionIOS = (): Promise<void> =>
414
+ getIosModule().clearTransaction();
415
+
416
+ /**
417
+ * Clear valid Products (iOS only)
418
+ * Remove all products which are validated by Apple server.
419
+ * @returns {void}
420
+ */
421
+ export const clearProductsIOS = (): Promise<void> =>
422
+ getIosModule().clearProducts();
423
+
424
+ /**
425
+ * Acknowledge a product (on Android.) No-op on iOS.
426
+ * @param {string} token The product's token (on Android)
427
+ * @returns {Promise<PurchaseResult | void>}
428
+ */
429
+ export const acknowledgePurchaseAndroid = (
430
+ token: string,
431
+ developerPayload?: string,
432
+ ): Promise<PurchaseResult | void> => {
433
+ return getAndroidModule().acknowledgePurchase(token, developerPayload);
434
+ };
435
+
436
+ /**
437
+ * Deep link to subscriptions screen on Android. No-op on iOS.
438
+ * @param {string} sku The product's SKU (on Android)
439
+ * @returns {Promise<void>}
440
+ */
441
+ export const deepLinkToSubscriptionsAndroid = async (
442
+ sku: string,
443
+ ): Promise<void> => {
444
+ checkNativeAndroidAvailable();
445
+
446
+ return Linking.openURL(
447
+ `https://play.google.com/store/account/subscriptions?package=${await RNIapModule.getPackageName()}&sku=${sku}`,
448
+ );
449
+ };
450
+
451
+ /**
452
+ * Should Add Store Payment (iOS only)
453
+ * Indicates the the App Store purchase should continue from the app instead of the App Store.
454
+ * @returns {Promise<Product | null>} promoted product
455
+ */
456
+ export const getPromotedProductIOS = (): Promise<Product | null> =>
457
+ getIosModule().promotedProduct();
458
+
459
+ /**
460
+ * Buy the currently selected promoted product (iOS only)
461
+ * Initiates the payment process for a promoted product. Should only be called in response to the `iap-promoted-product` event.
462
+ * @returns {Promise<void>}
463
+ */
464
+ export const buyPromotedProductIOS = (): Promise<void> =>
465
+ getIosModule().buyPromotedProduct();
466
+
467
+ const fetchJsonOrThrow = async (
468
+ url: string,
469
+ receiptBody: Record<string, unknown>,
470
+ ): Promise<Apple.ReceiptValidationResponse | false> => {
471
+ const response = await fetch(url, {
472
+ method: 'POST',
473
+ headers: {
474
+ Accept: 'application/json',
475
+ 'Content-Type': 'application/json',
476
+ },
477
+ body: JSON.stringify(receiptBody),
478
+ });
479
+
480
+ if (!response.ok) {
481
+ throw Object.assign(new Error(response.statusText), {
482
+ statusCode: response.status,
483
+ });
484
+ }
485
+
486
+ return response.json();
487
+ };
488
+
489
+ const requestAgnosticReceiptValidationIos = async (
490
+ receiptBody: Record<string, unknown>,
491
+ ): Promise<Apple.ReceiptValidationResponse | false> => {
492
+ const response = await fetchJsonOrThrow(
493
+ 'https://buy.itunes.apple.com/verifyReceipt',
494
+ receiptBody,
495
+ );
496
+
497
+ // Best practice is to check for test receipt and check sandbox instead
498
+ // https://developer.apple.com/documentation/appstorereceipts/verifyreceipt
499
+ if (response && response.status === ReceiptValidationStatus.TEST_RECEIPT) {
500
+ const testResponse = await fetchJsonOrThrow(
501
+ 'https://sandbox.itunes.apple.com/verifyReceipt',
502
+ receiptBody,
503
+ );
504
+
505
+ return testResponse;
506
+ }
507
+
508
+ return response;
509
+ };
510
+
511
+ /**
512
+ * Buy products or subscriptions with offers (iOS only)
513
+ *
514
+ * Runs the payment process with some info you must fetch
515
+ * from your server.
516
+ * @param {string} sku The product identifier
517
+ * @param {string} forUser An user identifier on you system
518
+ * @param {Apple.PaymentDiscount} withOffer The offer information
519
+ * @param {string} withOffer.identifier The offer identifier
520
+ * @param {string} withOffer.keyIdentifier Key identifier that it uses to generate the signature
521
+ * @param {string} withOffer.nonce An UUID returned from the server
522
+ * @param {string} withOffer.signature The actual signature returned from the server
523
+ * @param {number} withOffer.timestamp The timestamp of the signature
524
+ * @returns {Promise<void>}
525
+ */
526
+ export const requestPurchaseWithOfferIOS = (
527
+ sku: string,
528
+ forUser: string,
529
+ withOffer: Apple.PaymentDiscount,
530
+ ): Promise<void> => getIosModule().buyProductWithOffer(sku, forUser, withOffer);
531
+
532
+ /**
533
+ * Validate receipt for iOS.
534
+ * @param {object} receiptBody the receipt body to send to apple server.
535
+ * @param {boolean} isTest whether this is in test environment which is sandbox.
536
+ * @returns {Promise<Apple.ReceiptValidationResponse | false>}
537
+ */
538
+ export const validateReceiptIos = async (
539
+ receiptBody: Record<string, unknown>,
540
+ isTest?: boolean,
541
+ ): Promise<Apple.ReceiptValidationResponse | false> => {
542
+ if (isTest == null) {
543
+ return await requestAgnosticReceiptValidationIos(receiptBody);
544
+ }
545
+
546
+ const url = isTest
547
+ ? 'https://sandbox.itunes.apple.com/verifyReceipt'
548
+ : 'https://buy.itunes.apple.com/verifyReceipt';
549
+
550
+ const response = await fetchJsonOrThrow(url, receiptBody);
551
+
552
+ return response;
553
+ };
554
+
555
+ /**
556
+ * Validate receipt for Android. NOTE: This method is here for debugging purposes only. Including
557
+ * your access token in the binary you ship to users is potentially dangerous.
558
+ * Use server side validation instead for your production builds
559
+ * @param {string} packageName package name of your app.
560
+ * @param {string} productId product id for your in app product.
561
+ * @param {string} productToken token for your purchase.
562
+ * @param {string} accessToken accessToken from googleApis.
563
+ * @param {boolean} isSub whether this is subscription or inapp. `true` for subscription.
564
+ * @returns {Promise<object>}
565
+ */
566
+ export const validateReceiptAndroid = async (
567
+ packageName: string,
568
+ productId: string,
569
+ productToken: string,
570
+ accessToken: string,
571
+ isSub?: boolean,
572
+ ): Promise<Android.ReceiptType> => {
573
+ const type = isSub ? 'subscriptions' : 'products';
574
+
575
+ const url =
576
+ 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications' +
577
+ `/${packageName}/purchases/${type}/${productId}` +
578
+ `/tokens/${productToken}?access_token=${accessToken}`;
579
+
580
+ const response = await fetch(url, {
581
+ method: 'GET',
582
+ headers: {
583
+ 'Content-Type': 'application/json',
584
+ },
585
+ });
586
+
587
+ if (!response.ok) {
588
+ throw Object.assign(new Error(response.statusText), {
589
+ statusCode: response.status,
590
+ });
591
+ }
592
+
593
+ return response.json();
594
+ };
595
+
596
+ /**
597
+ * Validate receipt for Amazon. NOTE: This method is here for debugging purposes only. Including
598
+ * your developer secret in the binary you ship to users is potentially dangerous.
599
+ * Use server side validation instead for your production builds
600
+ * @param {string} developerSecret: from the Amazon developer console.
601
+ * @param {string} userId who purchased the item.
602
+ * @param {string} receiptId long obfuscated string returned when purchasing the item
603
+ * @param {boolean} useSandbox Defaults to true, use sandbox environment or production.
604
+ * @returns {Promise<object>}
605
+ */
606
+ export const validateReceiptAmazon = async (
607
+ developerSecret: string,
608
+ userId: string,
609
+ receiptId: string,
610
+ useSandbox: boolean = true,
611
+ ): Promise<Amazon.ReceiptType> => {
612
+ const sandBoxUrl = useSandbox ? 'sandbox/' : '';
613
+ const url = `https://appstore-sdk.amazon.com/${sandBoxUrl}version/1.0/verifyReceiptId/developer/${developerSecret}/user/${userId}/receiptId/${receiptId}`;
614
+
615
+ const response = await fetch(url, {
616
+ method: 'GET',
617
+ headers: {
618
+ 'Content-Type': 'application/json',
619
+ },
620
+ });
621
+
622
+ if (!response.ok) {
623
+ throw Object.assign(new Error(response.statusText), {
624
+ statusCode: response.status,
625
+ });
626
+ }
627
+
628
+ return response.json();
629
+ };
630
+
631
+ /**
632
+ * Add IAP purchase event
633
+ * @returns {callback(e: InAppPurchase | ProductPurchase)}
634
+ */
635
+ export const purchaseUpdatedListener = (
636
+ listener: (event: InAppPurchase | SubscriptionPurchase) => void,
637
+ ): EmitterSubscription => {
638
+ const emitterSubscription = new NativeEventEmitter(
639
+ getNativeModule(),
640
+ ).addListener('purchase-updated', listener);
641
+
642
+ if (isAndroid) {
643
+ getAndroidModule().startListening();
644
+ }
645
+
646
+ return emitterSubscription;
647
+ };
648
+
649
+ /**
650
+ * Add IAP purchase error event
651
+ * @returns {callback(e: PurchaseError)}
652
+ */
653
+ export const purchaseErrorListener = (
654
+ listener: (errorEvent: PurchaseError) => void,
655
+ ): EmitterSubscription =>
656
+ new NativeEventEmitter(getNativeModule()).addListener(
657
+ 'purchase-error',
658
+ listener,
659
+ );
660
+
661
+ /**
662
+ * Add IAP promoted subscription event
663
+ * Only available on iOS
664
+ */
665
+ export const promotedProductListener = (
666
+ listener: () => void,
667
+ ): EmitterSubscription =>
668
+ new NativeEventEmitter(getIosModule()).addListener(
669
+ 'iap-promoted-product',
670
+ listener,
671
+ );
672
+
673
+ /**
674
+ * Get the current receipt base64 encoded in IOS.
675
+ * @param {forceRefresh?:boolean}
676
+ * @returns {Promise<ProductPurchase[]>}
677
+ */
678
+ export const getPendingPurchasesIOS = async (): Promise<ProductPurchase[]> =>
679
+ getIosModule().getPendingTransactions();
680
+
681
+ /**
682
+ * Launches a modal to register the redeem offer code in IOS.
683
+ * @returns {Promise<null>}
684
+ */
685
+ export const presentCodeRedemptionSheetIOS = async (): Promise<null> =>
686
+ getIosModule().presentCodeRedemptionSheet();
@@ -1,4 +1,7 @@
1
+ import * as iap from './iap';
2
+
1
3
  export * from './types';
2
4
  export * from './hooks/useIAP';
3
5
  export * from './hooks/withIAPContext';
4
- export * from './iap';
6
+
7
+ export default iap;