-
Notifications
You must be signed in to change notification settings - Fork 77
/
purchases.ts
1258 lines (1162 loc) · 52.6 KB
/
purchases.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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {NativeEventEmitter, NativeModules} from "react-native";
import {PurchasesError, PURCHASES_ERROR_CODE, UninitializedPurchasesError, UnsupportedPlatformError} from "./errors";
import {CustomerInfo, PurchasesEntitlementInfo} from "./customerInfo";
import {
PRORATION_MODE,
PACKAGE_TYPE,
INTRO_ELIGIBILITY_STATUS,
PurchasesOfferings,
PurchasesStoreProduct,
UpgradeInfo,
PurchasesPromotionalOffer,
PurchasesPackage,
IntroEligibility,
PurchasesStoreProductDiscount,
SubscriptionOption,
PRODUCT_CATEGORY,
GoogleProductChangeInfo
} from "./offerings";
import {Platform} from "react-native";
const {RNPurchases} = NativeModules;
const eventEmitter = new NativeEventEmitter(RNPurchases);
/**
* Listener used on updated customer info
* @callback CustomerInfoUpdateListener
* @param {Object} customerInfo Object containing info for the customer
*/
export type CustomerInfoUpdateListener = (customerInfo: CustomerInfo) => void;
export type ShouldPurchasePromoProductListener = (deferredPurchase: () => Promise<MakePurchaseResult>) => void;
export type MakePurchaseResult = { productIdentifier: string; customerInfo: CustomerInfo; };
export type LogHandler = (logLevel: LOG_LEVEL, message: string) => void;
let customerInfoUpdateListeners: CustomerInfoUpdateListener[] = [];
let shouldPurchasePromoProductListeners: ShouldPurchasePromoProductListener[] = [];
let customLogHandler: LogHandler;
eventEmitter.addListener(
"Purchases-CustomerInfoUpdated",
(customerInfo: CustomerInfo) => {
customerInfoUpdateListeners.forEach(listener => listener(customerInfo));
}
);
eventEmitter.addListener(
"Purchases-ShouldPurchasePromoProduct",
({callbackID}: { callbackID: number }) => {
shouldPurchasePromoProductListeners.forEach(listener =>
listener(() => RNPurchases.makeDeferredPurchase(callbackID))
);
}
);
eventEmitter.addListener(
"Purchases-LogHandlerEvent",
({logLevel, message}: { logLevel: LOG_LEVEL, message: string }) => {
const logLevelEnum = LOG_LEVEL[logLevel];
customLogHandler(logLevelEnum, message);
}
);
/**
* @deprecated, use PRODUCT_CATEGORY
*/
export enum PURCHASE_TYPE {
/**
* A type of SKU for in-app products.
*/
INAPP = "inapp",
/**
* A type of SKU for subscriptions.
*/
SUBS = "subs",
}
/**
* Enum for billing features.
* Currently, these are only relevant for Google Play Android users:
* https://developer.android.com/reference/com/android/billingclient/api/BillingClient.FeatureType
*/
export enum BILLING_FEATURE {
/**
* Purchase/query for subscriptions.
*/
SUBSCRIPTIONS,
/**
* Subscriptions update/replace.
*/
SUBSCRIPTIONS_UPDATE,
/**
* Purchase/query for in-app items on VR.
*/
IN_APP_ITEMS_ON_VR,
/**
* Purchase/query for subscriptions on VR.
*/
SUBSCRIPTIONS_ON_VR,
/**
* Launch a price change confirmation flow.
*/
PRICE_CHANGE_CONFIRMATION,
}
export enum REFUND_REQUEST_STATUS {
/**
* Apple has received the refund request.
*/
SUCCESS,
/**
* User canceled submission of the refund request.
*/
USER_CANCELLED,
/**
* There was an error with the request. See message for more details.
*/
ERROR
}
/**
* Holds the logIn result
*/
export interface LogInResult {
/**
* The Customer Info for the user.
*/
readonly customerInfo: CustomerInfo;
/**
* True if the call resulted in a new user getting created in the RevenueCat backend.
*/
readonly created: boolean;
}
export enum LOG_LEVEL {
VERBOSE = "VERBOSE",
DEBUG = "DEBUG",
INFO = "INFO",
WARN = "WARN",
ERROR = "ERROR"
}
/**
* Holds parameters to initialize the SDK.
*/
export interface PurchasesConfiguration {
/**
* RevenueCat API Key. Needs to be a string
*/
apiKey: string;
/**
* A unique id for identifying the user
*/
appUserID?: string | null;
/**
* An optional boolean. Set this to TRUE if you have your own IAP implementation and
* want to use only RevenueCat's backend. Default is FALSE. If you are on Android and setting this to ON, you will have
* to acknowledge the purchases yourself.
*/
observerMode?: boolean;
/**
* An optional string. iOS-only, will be ignored for Android.
* Set this if you would like the RevenueCat SDK to store its preferences in a different NSUserDefaults
* suite, otherwise it will use standardUserDefaults. Default is null, which will make the SDK use standardUserDefaults.
*/
userDefaultsSuiteName?: string;
/**
* iOS-only, will be ignored for Android.
* Set this to TRUE to enable StoreKit2.
* Default is FALSE.
*
* @deprecated RevenueCat currently uses StoreKit 1 for purchases, as its stability in production scenarios has
* proven to be more performant than StoreKit 2.
* We're collecting more data on the best approach, but StoreKit 1 vs StoreKit 2 is an implementation detail
* that you shouldn't need to care about.
* We recommend not using this parameter, letting RevenueCat decide for you which StoreKit implementation to use.
*/
usesStoreKit2IfAvailable?: boolean;
/**
* An optional boolean. Android only. Required to configure the plugin to be used in the Amazon Appstore.
*/
useAmazon?: boolean;
}
export default class Purchases {
/**
* Supported SKU types.
* @readonly
* @enum {string}
* @deprecated, use PRODUCT_CATEGORY
*/
public static PURCHASE_TYPE = PURCHASE_TYPE;
/**
* Supported product categories.
* @readonly
* @enum {string}
*/
public static PRODUCT_CATEGORY = PRODUCT_CATEGORY;
/**
* Enum for billing features.
* Currently, these are only relevant for Google Play Android users:
* https://developer.android.com/reference/com/android/billingclient/api/BillingClient.FeatureType
* @readonly
* @enum {string}
*/
public static BILLING_FEATURE = BILLING_FEATURE;
/**
* Enum with possible return states for beginning refund request.
* @readonly
* @enum {string}
*/
public static REFUND_REQUEST_STATUS = REFUND_REQUEST_STATUS;
/**
* Replace SKU's ProrationMode.
* @readonly
* @enum {number}
*/
public static PRORATION_MODE = PRORATION_MODE;
/**
* Enumeration of all possible Package types.
* @readonly
* @enum {string}
*/
public static PACKAGE_TYPE = PACKAGE_TYPE;
/**
* Enum of different possible states for intro price eligibility status.
* @readonly
* @enum {number}
*/
public static INTRO_ELIGIBILITY_STATUS = INTRO_ELIGIBILITY_STATUS;
/**
* Enum of all error codes the SDK produces.
* @readonly
* @enum {string}
*/
public static PURCHASES_ERROR_CODE = PURCHASES_ERROR_CODE;
/**
* List of valid log levels.
* @readonly
* @enum {string}
*/
public static LOG_LEVEL = LOG_LEVEL;
/**
* @internal
*/
public static UninitializedPurchasesError = UninitializedPurchasesError;
/**
* @internal
*/
public static UnsupportedPlatformError = UnsupportedPlatformError;
/**
* Sets up Purchases with your API key and an app user id.
* @param {String} apiKey RevenueCat API Key. Needs to be a String
* @param {String?} appUserID An optional unique id for identifying the user. Needs to be a string.
* @param {boolean} [observerMode=false] An optional boolean. Set this to TRUE if you have your own IAP implementation and want to use only RevenueCat's backend. Default is FALSE.
* @param {boolean} [usesStoreKit2IfAvailable=false] DEPRECATED. An optional boolean. iOS-only. Defaults to FALSE. Setting this to TRUE will enable StoreKit2 on compatible devices.
* We recommend not using this parameter, letting RevenueCat decide for you which StoreKit implementation to use.
* @param {boolean} [useAmazon=false] An optional boolean. Android-only. Set this to TRUE to enable Amazon on compatible devices.
* @param {String?} userDefaultsSuiteName An optional string. iOS-only, will be ignored for Android.
* Set this if you would like the RevenueCat SDK to store its preferences in a different NSUserDefaults suite, otherwise it will use standardUserDefaults.
* Default is null, which will make the SDK use standardUserDefaults.
*/
public static configure({
apiKey,
appUserID = null,
observerMode = false,
userDefaultsSuiteName,
usesStoreKit2IfAvailable = false,
useAmazon = false
}: PurchasesConfiguration): void {
if (apiKey === undefined || typeof apiKey !== "string") {
throw new Error("Invalid API key. It must be called with an Object: configure({apiKey: \"key\"})");
}
if (appUserID !== null && typeof appUserID !== "undefined" && typeof appUserID !== "string") {
throw new Error("appUserID needs to be a string");
}
RNPurchases.setupPurchases(
apiKey,
appUserID,
observerMode,
userDefaultsSuiteName,
usesStoreKit2IfAvailable,
useAmazon
);
}
/**
* @deprecated, configure behavior through the RevenueCat dashboard instead.
* If an user tries to purchase a product that is active on the current app store account,
* we will treat it as a restore and alias the new ID with the previous id.
* @param {boolean} allowSharing Set this to true if you are passing in an appUserID but it is anonymous,
* this is true by default if you didn't pass an appUserID
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet.
*/
public static async setAllowSharingStoreAccount(allowSharing: boolean): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.setAllowSharingStoreAccount(allowSharing);
}
/**
* @param {boolean} finishTransactions Set finishTransactions to false if you aren't using Purchases SDK to
* make the purchase
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet.
*/
public static async setFinishTransactions(finishTransactions: boolean): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.setFinishTransactions(finishTransactions);
}
/**
* iOS only.
* @param {boolean} simulatesAskToBuyInSandbox Set this property to true *only* when testing the ask-to-buy / SCA
* purchases flow. More information: http://errors.rev.cat/ask-to-buy
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet.
*/
public static async setSimulatesAskToBuyInSandbox(simulatesAskToBuyInSandbox: boolean): Promise<void> {
if (Platform.OS === "ios") {
RNPurchases.setSimulatesAskToBuyInSandbox(simulatesAskToBuyInSandbox);
}
}
/**
* Sets a function to be called on updated customer info
* @param {CustomerInfoUpdateListener} customerInfoUpdateListener CustomerInfo update listener
*/
public static addCustomerInfoUpdateListener(
customerInfoUpdateListener: CustomerInfoUpdateListener
): void {
if (typeof customerInfoUpdateListener !== "function") {
throw new Error("addCustomerInfoUpdateListener needs a function");
}
customerInfoUpdateListeners.push(customerInfoUpdateListener);
}
/**
* Removes a given CustomerInfoUpdateListener
* @param {CustomerInfoUpdateListener} listenerToRemove CustomerInfoUpdateListener reference of the listener to remove
* @returns {boolean} True if listener was removed, false otherwise
*/
public static removeCustomerInfoUpdateListener(
listenerToRemove: CustomerInfoUpdateListener
): boolean {
if (customerInfoUpdateListeners.includes(listenerToRemove)) {
customerInfoUpdateListeners = customerInfoUpdateListeners.filter(
listener => listenerToRemove !== listener
);
return true;
}
return false;
}
/**
* Sets a function to be called on purchases initiated on the Apple App Store. This is only used in iOS.
* @param {ShouldPurchasePromoProductListener} shouldPurchasePromoProductListener Called when a user initiates a
* promotional in-app purchase from the App Store. If your app is able to handle a purchase at the current time, run
* the deferredPurchase function. If the app is not in a state to make a purchase: cache the deferredPurchase, then
* call the deferredPurchase when the app is ready to make the promotional purchase.
* If the purchase should never be made, you don't need to ever call the deferredPurchase and the app will not
* proceed with promotional purchases.
*/
public static addShouldPurchasePromoProductListener(
shouldPurchasePromoProductListener: ShouldPurchasePromoProductListener
): void {
if (typeof shouldPurchasePromoProductListener !== "function") {
throw new Error("addShouldPurchasePromoProductListener needs a function");
}
shouldPurchasePromoProductListeners.push(shouldPurchasePromoProductListener);
}
/**
* Removes a given ShouldPurchasePromoProductListener
* @param {ShouldPurchasePromoProductListener} listenerToRemove ShouldPurchasePromoProductListener reference of
* the listener to remove
* @returns {boolean} True if listener was removed, false otherwise
*/
public static removeShouldPurchasePromoProductListener(
listenerToRemove: ShouldPurchasePromoProductListener
): boolean {
if (shouldPurchasePromoProductListeners.includes(listenerToRemove)) {
shouldPurchasePromoProductListeners = shouldPurchasePromoProductListeners.filter(
listener => listenerToRemove !== listener
);
return true;
}
return false;
}
/**
* Gets the map of entitlements -> offerings -> products
* @returns {Promise<PurchasesOfferings>} Promise of entitlements structure. The promise will be rejected if configure
* has not been called yet.
*/
public static async getOfferings(): Promise<PurchasesOfferings> {
await Purchases.throwIfNotConfigured();
return RNPurchases.getOfferings();
}
/**
* Fetch the product info
* @param {String[]} productIdentifiers Array of product identifiers
* @param {String} type Optional type of products to fetch, can be SUBSCRIPTION or NON_SUBSCRIPTION. SUBSCRIPTION by default
* @returns {Promise<PurchasesStoreProduct[]>} A promise containing an array of products. The promise will be rejected
* if the products are not properly configured in RevenueCat or if there is another error retrieving them.
* Rejections return an error code, and a userInfo object with more information. The promise will also be rejected
* if configure has not been called yet.
*/
public static async getProducts(
productIdentifiers: string[],
type: PURCHASE_TYPE | PRODUCT_CATEGORY = PRODUCT_CATEGORY.SUBSCRIPTION
): Promise<PurchasesStoreProduct[]> {
await Purchases.throwIfNotConfigured();
return RNPurchases.getProductInfo(productIdentifiers, type);
}
/**
* Make a purchase
*
* @param {String} productIdentifier The product identifier of the product you want to purchase
* @param {UpgradeInfo} upgradeInfo Android only. Optional UpgradeInfo you wish to upgrade from containing the oldSKU
* and the optional prorationMode.
* @param {String} type Optional type of product, can be inapp or subs. Subs by default
* @deprecated, use purchaseStoreProduct instead
*/
public static async purchaseProduct(
productIdentifier: string,
upgradeInfo?: UpgradeInfo | null,
type: PURCHASE_TYPE = PURCHASE_TYPE.SUBS,
): Promise<MakePurchaseResult> {
await Purchases.throwIfNotConfigured();
return RNPurchases.purchaseProduct(
productIdentifier,
upgradeInfo,
type,
null,
null,
null
).catch((error: PurchasesError) => {
error.userCancelled = error.code === PURCHASES_ERROR_CODE.PURCHASE_CANCELLED_ERROR;
throw error;
});
}
/**
* Make a purchase
*
* @param {PurchasesStoreProduct} product The product you want to purchase
* @param {GoogleProductChangeInfo} googleProductChangeInfo Android only. Optional GoogleProductChangeInfo you
* wish to upgrade from containing the oldProductIdentifier and the optional prorationMode.
* @param {boolean} googleIsPersonalizedPrice Android and Google only. Optional boolean indicates personalized pricing on products available for purchase in the EU.
* For compliance with EU regulations. User will see "This price has been customize for you" in the purchase dialog when true.
* See https://developer.android.com/google/play/billing/integrate#personalized-price for more info.
* @returns {Promise<{ productIdentifier: string, customerInfo:CustomerInfo }>} A promise of an object containing
* a customer info object and a product identifier. Rejections return an error code,
* a boolean indicating if the user cancelled the purchase, and an object with more information. The promise will
* also be rejected if configure has not been called yet.
*/
public static async purchaseStoreProduct(
product: PurchasesStoreProduct,
googleProductChangeInfo?: GoogleProductChangeInfo | null,
googleIsPersonalizedPrice?: boolean | null,
): Promise<MakePurchaseResult> {
await Purchases.throwIfNotConfigured();
return RNPurchases.purchaseProduct(
product.identifier,
googleProductChangeInfo,
product.productCategory,
null,
googleIsPersonalizedPrice == null ? null : {isPersonalizedPrice: googleIsPersonalizedPrice},
product.presentedOfferingIdentifier
).catch((error: PurchasesError) => {
error.userCancelled = error.code === PURCHASES_ERROR_CODE.PURCHASE_CANCELLED_ERROR;
throw error;
});
}
/**
* iOS only. Purchase a product applying a given discount.
*
* @param {PurchasesStoreProduct} product The product you want to purchase
* @param {PurchasesPromotionalOffer} discount Discount to apply to this package. Retrieve this discount using getPromotionalOffer.
* @param {boolean} googleIsPersonalizedPrice Android and Google only. Optional boolean indicates personalized pricing on products available for purchase in the EU.
* For compliance with EU regulations. User will see "This price has been customize for you" in the purchase dialog when true.
* See https://developer.android.com/google/play/billing/integrate#personalized-price for more info.
* @returns {Promise<{ productIdentifier: string, customerInfo:CustomerInfo }>} A promise of an object containing
* a customer info object and a product identifier. Rejections return an error code,
* a boolean indicating if the user cancelled the purchase, and an object with more information. The promise will be
* rejected if configure has not been called yet.
*/
public static async purchaseDiscountedProduct(
product: PurchasesStoreProduct,
discount: PurchasesPromotionalOffer,
): Promise<MakePurchaseResult> {
await Purchases.throwIfNotConfigured();
if (typeof discount === "undefined" || discount == null) {
throw new Error("A discount is required");
}
return RNPurchases.purchaseProduct(
product.identifier,
null,
null,
discount.timestamp.toString(),
null,
product.presentedOfferingIdentifier
).catch((error: PurchasesError) => {
error.userCancelled = error.code === PURCHASES_ERROR_CODE.PURCHASE_CANCELLED_ERROR;
throw error;
});
}
/**
* Make a purchase
*
* @param {PurchasesPackage} aPackage The Package you wish to purchase. You can get the Packages by calling getOfferings
* @param {UpgradeInfo} upgradeInfo DEPRECATED. Use googleProductChangeInfo.
* @param {GoogleProductChangeInfo} googleProductChangeInfo Android only. Optional GoogleProductChangeInfo you
* wish to upgrade from containing the oldProductIdentifier and the optional prorationMode.
* @param {boolean} googleIsPersonalizedPrice Android and Google only. Optional boolean indicates personalized pricing on products available for purchase in the EU.
* For compliance with EU regulations. User will see "This price has been customize for you" in the purchase dialog when true.
* See https://developer.android.com/google/play/billing/integrate#personalized-price for more info.
* @returns {Promise<{ productIdentifier: string, customerInfo: CustomerInfo }>} A promise of an object containing
* a customer info object and a product identifier. Rejections return an error code, a boolean indicating if the
* user cancelled the purchase, and an object with more information. The promise will be also be rejected if configure
* has not been called yet.
*/
public static async purchasePackage(
aPackage: PurchasesPackage,
upgradeInfo?: UpgradeInfo | null,
googleProductChangeInfo?: GoogleProductChangeInfo | null,
googleIsPersonalizedPrice?: boolean | null,
): Promise<MakePurchaseResult> {
await Purchases.throwIfNotConfigured();
return RNPurchases.purchasePackage(
aPackage.identifier,
aPackage.offeringIdentifier,
googleProductChangeInfo || upgradeInfo,
null,
googleIsPersonalizedPrice == null ? null : {isPersonalizedPrice: googleIsPersonalizedPrice},
).catch((error: PurchasesError) => {
error.userCancelled = error.code === PURCHASES_ERROR_CODE.PURCHASE_CANCELLED_ERROR;
throw error;
});
}
/**
* Google only. Make a purchase of a subscriptionOption
*
* @param {SubscriptionOption} subscriptionOption The SubscriptionOption you wish to purchase. You can get the SubscriptionOption from StoreProducts by calling getOfferings
* @param {GoogleProductChangeInfo} googleProductChangeInfo Android only. Optional GoogleProductChangeInfo you
* wish to upgrade from containing the oldProductIdentifier and the optional prorationMode.
* @param {boolean} googleIsPersonalizedPrice Android and Google only. Optional boolean indicates personalized pricing on products available for purchase in the EU.
* For compliance with EU regulations. User will see "This price has been customize for you" in the purchase dialog when true.
* See https://developer.android.com/google/play/billing/integrate#personalized-price for more info.
* @returns {Promise<{ productIdentifier: string, customerInfo: CustomerInfo }>} A promise of an object containing
* a customer info object and a product identifier. Rejections return an error code, a boolean indicating if the
* user cancelled the purchase, and an object with more information. The promise will be also be rejected if configure
* has not been called yet.
*/
public static async purchaseSubscriptionOption(
subscriptionOption: SubscriptionOption,
googleProductChangeInfo?: GoogleProductChangeInfo,
googleIsPersonalizedPrice?: boolean,
): Promise<MakePurchaseResult> {
await Purchases.throwIfNotConfigured();
await Purchases.throwIfIOSPlatform();
return RNPurchases.purchaseSubscriptionOption(
subscriptionOption.productId,
subscriptionOption.id,
googleProductChangeInfo,
null,
googleIsPersonalizedPrice == null ? null : {isPersonalizedPrice: googleIsPersonalizedPrice},
subscriptionOption.presentedOfferingIdentifier
).catch((error: PurchasesError) => {
error.userCancelled = error.code === PURCHASES_ERROR_CODE.PURCHASE_CANCELLED_ERROR;
throw error;
});
}
/**
* iOS only. Purchase a package applying a given discount.
*
* @param {PurchasesPackage} aPackage The Package you wish to purchase. You can get the Packages by calling getOfferings
* @param {PurchasesPromotionalOffer} discount Discount to apply to this package. Retrieve this discount using getPromotionalOffer.
* @returns {Promise<{ productIdentifier: string, customerInfo: CustomerInfo }>} A promise of an object containing
* a customer info object and a product identifier. Rejections return an error code, a boolean indicating if the
* user cancelled the purchase, and an object with more information. The promise will be also be rejected if configure
* has not been called yet.
*/
public static async purchaseDiscountedPackage(
aPackage: PurchasesPackage,
discount: PurchasesPromotionalOffer
): Promise<MakePurchaseResult> {
await Purchases.throwIfNotConfigured();
if (typeof discount === "undefined" || discount == null) {
throw new Error("A discount is required");
}
return RNPurchases.purchasePackage(
aPackage.identifier,
aPackage.offeringIdentifier,
null,
discount.timestamp.toString()
).catch((error: PurchasesError) => {
error.userCancelled = error.code === PURCHASES_ERROR_CODE.PURCHASE_CANCELLED_ERROR;
throw error;
});
}
/**
* Restores a user's previous purchases and links their appUserIDs to any user's also using those purchases.
* @returns {Promise<CustomerInfo>} A promise of a customer info object. Rejections return an error code, and an
* userInfo object with more information. The promise will be also be rejected if configure has not been called yet.
*/
public static async restorePurchases(): Promise<CustomerInfo> {
await Purchases.throwIfNotConfigured();
return RNPurchases.restorePurchases();
}
/**
* Get the appUserID
* @returns {Promise<string>} The app user id in a promise
*/
public static async getAppUserID(): Promise<string> {
await Purchases.throwIfNotConfigured();
return RNPurchases.getAppUserID();
}
/**
* This function will logIn the current user with an appUserID. Typically this would be used after a log in
* to identify a user without calling configure.
* @param {String} appUserID The appUserID that should be linked to the currently user
* @returns {Promise<LogInResult>} A promise of an object that contains the customerInfo after logging in, as well
* as a boolean indicating whether the user has just been created for the first time in the RevenueCat backend. The
* promise will be rejected if configure has not been called yet or if there's an issue logging in.
*/
public static async logIn(appUserID: string): Promise<LogInResult> {
await Purchases.throwIfNotConfigured();
// noinspection SuspiciousTypeOfGuard
if (typeof appUserID !== "string") {
throw new Error("appUserID needs to be a string");
}
return RNPurchases.logIn(appUserID);
}
/**
* Logs out the Purchases client clearing the saved appUserID. This will generate a random user id and save it in the cache.
* @returns {Promise<CustomerInfo>} A promise of a customer info object. Rejections return an error code,
* and a userInfo object with more information. The promise will be rejected if configure has not been called yet or if
* there's an issue logging out.
*/
public static async logOut(): Promise<CustomerInfo> {
await Purchases.throwIfNotConfigured();
return RNPurchases.logOut();
}
/**
* Enables/Disables debugs logs
* @param {boolean} enabled Enable or not debug logs
* @deprecated, use setLogLevel instead
*/
public static async setDebugLogsEnabled(enabled: boolean): Promise<void> {
RNPurchases.setDebugLogsEnabled(enabled);
}
/**
* Used to set the log level. Useful for debugging issues with the lovely team @RevenueCat.
* The default is {LOG_LEVEL.INFO} in release builds and {LOG_LEVEL.DEBUG} in debug builds.
* @param {LOG_LEVEL} level
*/
public static async setLogLevel(level: LOG_LEVEL): Promise<void> {
RNPurchases.setLogLevel(level);
}
/**
* Set a custom log handler for redirecting logs to your own logging system.
* By default, this sends info, warning, and error messages.
* If you wish to receive Debug level messages, see [setLogLevel].
* @param {LogHandler} logHandler It will get called for each log event.
* Use this function to redirect the log to your own logging system
*/
public static setLogHandler(logHandler: LogHandler): void {
customLogHandler = logHandler;
RNPurchases.setLogHandler();
}
/**
* Gets current customer info
* @returns {Promise<CustomerInfo>} A promise of a customer info object. Rejections return an error code, and an
* userInfo object with more information. The promise will be rejected if configure has not been called yet or if
* there's an issue getting the customer information.
*/
public static async getCustomerInfo(): Promise<CustomerInfo> {
await Purchases.throwIfNotConfigured();
return RNPurchases.getCustomerInfo();
}
/**
* This method will send all the purchases to the RevenueCat backend. Call this when using your own implementation
* for subscriptions anytime a sync is needed, like after a successful purchase.
*
* @warning This function should only be called if you're not calling purchaseProduct/purchaseStoreProduct/purchasePackage/purchaseSubscriptionOption.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* syncing purchases.
*/
public static async syncPurchases(): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.syncPurchases();
}
/**
* This method will send a purchase to the RevenueCat backend. This function should only be called if you are
* in Amazon observer mode or performing a client side migration of your current users to RevenueCat.
*
* The receipt IDs are cached if successfully posted so they are not posted more than once.
*
* @param {string} productID Product ID associated to the purchase.
* @param {string} receiptID ReceiptId that represents the Amazon purchase.
* @param {string} amazonUserID Amazon's userID. This parameter will be ignored when syncing a Google purchase.
* @param {(string|null|undefined)} isoCurrencyCode Product's currency code in ISO 4217 format.
* @param {(number|null|undefined)} price Product's price.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* syncing purchases.
*/
public static async syncObserverModeAmazonPurchase(productID: string, receiptID: string,
amazonUserID: string, isoCurrencyCode?: string | null,
price?: number | null): Promise<void> {
await Purchases.throwIfIOSPlatform();
await Purchases.throwIfNotConfigured();
RNPurchases.syncObserverModeAmazonPurchase(productID, receiptID, amazonUserID, isoCurrencyCode, price);
}
/**
* @deprecated, use enableAdServicesAttributionTokenCollection instead.
* Enable automatic collection of Apple Search Ad attribution. Disabled by default
* @param {boolean} enabled Enable or not automatic apple search ads attribution collection
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet.
*/
public static async setAutomaticAppleSearchAdsAttributionCollection(
enabled: boolean
): Promise<void> {
if (Platform.OS === "ios") {
RNPurchases.setAutomaticAppleSearchAdsAttributionCollection(enabled);
}
}
/**
* Enable automatic collection of Apple Search Ad attribution on iOS. Disabled by default
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet.
*/
public static async enableAdServicesAttributionTokenCollection(): Promise<void> {
if (Platform.OS === "ios") {
await Purchases.throwIfNotConfigured();
RNPurchases.enableAdServicesAttributionTokenCollection();
}
}
/**
* @returns { Promise<boolean> } If the `appUserID` has been generated by RevenueCat or not.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet.
*/
public static async isAnonymous(): Promise<boolean> {
await Purchases.throwIfNotConfigured();
return RNPurchases.isAnonymous();
}
/**
* iOS only. Computes whether or not a user is eligible for the introductory pricing period of a given product.
* You should use this method to determine whether or not you show the user the normal product price or the
* introductory price. This also applies to trials (trials are considered a type of introductory pricing).
*
* @note Subscription groups are automatically collected for determining eligibility. If RevenueCat can't
* definitively compute the eligibility, most likely because of missing group information, it will return
* `INTRO_ELIGIBILITY_STATUS_UNKNOWN`. The best course of action on unknown status is to display the non-intro
* pricing, to not create a misleading situation. To avoid this, make sure you are testing with the latest version of
* iOS so that the subscription group can be collected by the SDK. Android always returns INTRO_ELIGIBILITY_STATUS_UNKNOWN.
*
* @param productIdentifiers Array of product identifiers for which you want to compute eligibility
* @returns { Promise<[productId: string]: IntroEligibility> } A map of IntroEligility per productId. The promise
* will be rejected if configure has not been called yet or if there's in an error checking eligibility.
*/
public static async checkTrialOrIntroductoryPriceEligibility(
productIdentifiers: string[]
): Promise<{ [productId: string]: IntroEligibility }> {
await Purchases.throwIfNotConfigured();
return RNPurchases.checkTrialOrIntroductoryPriceEligibility(
productIdentifiers
);
}
/**
* iOS only. Use this function to retrieve the `PurchasesPromotionalOffer` for a given `PurchasesPackage`.
*
* @param product The `PurchasesStoreProduct` the user intends to purchase.
* @param discount The `PurchasesStoreProductDiscount` to apply to the product.
* @returns { Promise<PurchasesPromotionalOffer> } Returns when the `PurchasesPaymentDiscount` is returned.
* Null is returned for Android and incompatible iOS versions. The promise will be rejected if configure has not been
* called yet or if there's an error getting the payment discount.
*/
public static async getPromotionalOffer(
product: PurchasesStoreProduct,
discount: PurchasesStoreProductDiscount
): Promise<PurchasesPromotionalOffer | undefined> {
await Purchases.throwIfNotConfigured();
if (Platform.OS === "android") {
return Promise.resolve(undefined);
}
if (typeof discount === "undefined" || discount == null) {
throw new Error("A discount is required");
}
return RNPurchases.getPromotionalOffer(
product.identifier,
discount.identifier
);
}
/**
* Invalidates the cache for customer information.
*
* Most apps will not need to use this method; invalidating the cache can leave your app in an invalid state.
* Refer to https://docs.revenuecat.com/docs/customer-info#section-get-user-information for more information on
* using the cache properly.
*
* This is useful for cases where customer information might have been updated outside of the app, like if a
* promotional subscription is granted through the RevenueCat dashboard.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or there's an error
* invalidating the customer info cache.
*/
public static async invalidateCustomerInfoCache(): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.invalidateCustomerInfoCache();
}
/** iOS only. Presents a code redemption sheet, useful for redeeming offer codes
* Refer to https://docs.revenuecat.com/docs/ios-subscription-offers#offer-codes for more information on how
* to configure and use offer codes
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or there's an error
* presenting the code redemption sheet.
*/
public static async presentCodeRedemptionSheet(): Promise<void> {
if (Platform.OS === "ios") {
await Purchases.throwIfNotConfigured();
RNPurchases.presentCodeRedemptionSheet();
}
}
/**
* Subscriber attributes are useful for storing additional, structured information on a user.
* Since attributes are writable using a public key they should not be used for
* managing secure or sensitive information such as subscription status, coins, etc.
*
* Key names starting with "$" are reserved names used by RevenueCat. For a full list of key
* restrictions refer to our guide: https://docs.revenuecat.com/docs/subscriber-attributes
*
* @param attributes Map of attributes by key. Set the value as an empty string to delete an attribute.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or there's an error
* setting the subscriber attributes.
*/
public static async setAttributes(attributes: { [key: string]: string | null }): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.setAttributes(attributes);
}
/**
* Subscriber attribute associated with the email address for the user
*
* @param email Empty String or null will delete the subscriber attribute.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* setting the email.
*/
public static async setEmail(email: string | null): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.setEmail(email);
}
/**
* Subscriber attribute associated with the phone number for the user
*
* @param phoneNumber Empty String or null will delete the subscriber attribute.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* setting the phone number.
*/
public static async setPhoneNumber(phoneNumber: string | null): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.setPhoneNumber(phoneNumber);
}
/**
* Subscriber attribute associated with the display name for the user
*
* @param displayName Empty String or null will delete the subscriber attribute.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* setting the display name.
*/
public static async setDisplayName(displayName: string | null): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.setDisplayName(displayName);
}
/**
* Subscriber attribute associated with the push token for the user
*
* @param pushToken null will delete the subscriber attribute.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* setting the push token.
*/
public static async setPushToken(pushToken: string | null): Promise<void> {
await Purchases.throwIfNotConfigured()
RNPurchases.setPushToken(pushToken);
}
/**
* Set this property to your proxy URL before configuring Purchases *only* if you've received a proxy key value
* from your RevenueCat contact.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* setting the proxy url.
*/
public static async setProxyURL(url: string): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.setProxyURLString(url);
}
/**
* Automatically collect subscriber attributes associated with the device identifiers.
* $idfa, $idfv, $ip on iOS
* $gpsAdId, $androidId, $ip on Android
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* setting collecting the device identifiers.
*/
public static async collectDeviceIdentifiers(): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.collectDeviceIdentifiers();
}
/**
* Subscriber attribute associated with the Adjust Id for the user
* Required for the RevenueCat Adjust integration
*
* @param adjustID Adjust ID to use in Adjust integration. Empty String or null will delete the subscriber attribute.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* setting Adjust ID.
*/
public static async setAdjustID(adjustID: string | null): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.setAdjustID(adjustID);
}
/**
* Subscriber attribute associated with the AppsFlyer Id for the user
* Required for the RevenueCat AppsFlyer integration
* @param appsflyerID Appsflyer ID to use in Appsflyer integration. Empty String or null will delete the subscriber attribute.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* setting the Appsflyer ID.
*/
public static async setAppsflyerID(appsflyerID: string | null): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.setAppsflyerID(appsflyerID);
}
/**
* Subscriber attribute associated with the Facebook SDK Anonymous Id for the user
* Recommended for the RevenueCat Facebook integration
*
* @param fbAnonymousID Facebook Anonymous ID to use in Mparticle integration. Empty String or null will delete the subscriber attribute.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* setting the Facebook Anonymous ID.
*/
public static async setFBAnonymousID(fbAnonymousID: string | null): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.setFBAnonymousID(fbAnonymousID);
}
/**
* Subscriber attribute associated with the mParticle Id for the user
* Recommended for the RevenueCat mParticle integration
*
* @param mparticleID Mparticle ID to use in Mparticle integration. Empty String or null will delete the subscriber attribute.
* @returns {Promise<void>} The promise will be rejected if configure has not been called yet or if there's an error
* setting the Mparticle ID.
*/
public static async setMparticleID(mparticleID: string | null): Promise<void> {
await Purchases.throwIfNotConfigured();
RNPurchases.setMparticleID(mparticleID);
}