react-native-iap 9.0.0-beta → 9.0.0-beta12

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