-
Notifications
You must be signed in to change notification settings - Fork 170
/
purchases_flutter.dart
435 lines (385 loc) · 17 KB
/
purchases_flutter.dart
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
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'object_wrappers.dart';
export 'object_wrappers.dart';
typedef void PurchaserInfoUpdateListener(PurchaserInfo purchaserInfo);
class Purchases {
static final Set<PurchaserInfoUpdateListener> _purchaserInfoUpdateListeners =
Set();
static final _channel = new MethodChannel('purchases_flutter')
..setMethodCallHandler((MethodCall call) async {
switch (call.method) {
case "Purchases-PurchaserInfoUpdated":
_purchaserInfoUpdateListeners.forEach(
(listener) => listener(PurchaserInfo.fromJson(call.arguments)));
break;
}
});
/// Sets up Purchases with your API key and an app user id.
///
/// [apiKey] RevenueCat API Key.
///
/// [appUserID] An optional unique id for identifying the user.
///
/// [observerMode] 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.
static Future<void> setup(String apiKey,
{String appUserId, bool observerMode = false}) async {
if (appUserId == null) {
return await _channel.invokeMethod('setupPurchases', {'apiKey': apiKey});
} else {
return await _channel.invokeMethod('setupPurchases', {
'apiKey': apiKey,
'appUserId': appUserId,
'observerMode': observerMode
});
}
}
/// 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.
/// If a 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.
static Future<void> setAllowSharingStoreAccount(bool allowSharing) async {
await _channel.invokeMethod(
'setAllowSharingStoreAccount', {'allowSharing': allowSharing});
}
/// Sets a function to be called on updated purchaser info.
///
/// The function is called right away with the latest purchaser info as soon
/// as it's set.
///
/// [purchaserInfoUpdateListener] PurchaserInfo update listener.
static void addPurchaserInfoUpdateListener(
PurchaserInfoUpdateListener purchaserInfoUpdateListener) async {
_purchaserInfoUpdateListeners.add(purchaserInfoUpdateListener);
}
/// Removes a given PurchaserInfoUpdateListener
///
/// [listenerToRemove] PurchaserInfoListener reference of the listener to remove.
static void removePurchaserInfoUpdateListener(
PurchaserInfoUpdateListener listenerToRemove) async {
_purchaserInfoUpdateListeners.remove(listenerToRemove);
}
/// Add a dict of attribution information
///
/// [data] Attribution data from any of the [PurchasesAttributionNetwork].
///
/// [network] Which network, see [PurchasesAttributionNetwork].
///
/// [networkUserId] An optional unique id for identifying the user.
static Future<void> addAttributionData(
Map<String, Object> data, PurchasesAttributionNetwork network,
{String networkUserId}) async {
await _channel.invokeMethod('addAttributionData', {
'data': data,
'network': network.index,
'networkUserId': networkUserId
});
}
/// Deprecated in favor of getOfferings.
@Deprecated("use getOfferings instead")
static void getEntitlements() async {}
/// Fetch the configured offerings for this users. Offerings allows you to
/// configure your in-app products via RevenueCat and greatly simplifies
/// management. See [the guide](https://docs.revenuecat.com/offerings) for
/// more info.
///
/// Offerings will be fetched and cached on instantiation so that, by the time
/// they are needed, your prices are loaded for your purchase flow.
///
/// Time is money.
static Future<Offerings> getOfferings() async {
return Offerings.fromJson(await _channel.invokeMethod('getOfferings'));
}
/// Fetch the product info. Returns a list of products or throws an error if
/// the products are not properly configured in RevenueCat or if there is
/// another error while retrieving them.
///
/// [productIdentifiers] Array of product identifiers
///
/// [type] Optional type of products to fetch, can be PurchaseType.INAPP
/// or PurchaseType.SUBS. Subs by default
static Future<List<Product>> getProducts(List<String> productIdentifiers,
{PurchaseType type = PurchaseType.subs}) async {
List<dynamic> result = await _channel.invokeMethod('getProductInfo',
{'productIdentifiers': productIdentifiers, 'type': describeEnum(type)});
return result.map((item) => Product.fromJson(item)).toList();
}
@Deprecated("use purchaseProduct/purchasePackage instead")
static Future<PurchaserInfo> makePurchase(String productIdentifier,
{String oldSKU, String type = "subs"}) async {
var purchaseType = PurchaseType.subs;
if (type == "inapp") {
purchaseType = PurchaseType.inapp;
}
return purchaseProduct(productIdentifier,
upgradeInfo: new UpgradeInfo(oldSKU), type: purchaseType);
}
/// Makes a purchase. Returns a [PurchaserInfo] object. Throws a
/// [PlatformException] if the purchase is unsuccessful.
/// Check if `PurchasesErrorHelper.getErrorCode(e)` is
/// `PurchasesErrorCode.purchaseCancelledError` to check if the user cancelled
/// the purchase.
///
/// [productIdentifier] The product identifier of the product you want to
/// purchase.
///
/// [upgradeInfo] Android only. Optional UpgradeInfo you wish to upgrade from
/// containing the oldSKU and the optional prorationMode.
///
/// [type] Android only. Optional type of product, can be PurchaseType.INAPP
/// or PurchaseType.SUBS. Subs by default.
static Future<PurchaserInfo> purchaseProduct(String productIdentifier,
{UpgradeInfo upgradeInfo, PurchaseType type = PurchaseType.subs}) async {
var response = await _channel.invokeMethod('purchaseProduct', {
'productIdentifier': productIdentifier,
'oldSKU': upgradeInfo != null ? upgradeInfo.oldSKU : null,
'prorationMode': upgradeInfo != null && upgradeInfo.prorationMode != null
? upgradeInfo.prorationMode.index
: null,
'type': describeEnum(type)
});
return PurchaserInfo.fromJson(response["purchaserInfo"]);
}
/// Makes a purchase. Returns a [PurchaserInfo] object. Throws a
/// [PlatformException] if the purchase is unsuccessful.
/// Check if `PurchasesErrorHelper.getErrorCode(e)` is
/// `PurchasesErrorCode.purchaseCancelledError` to check if the user cancelled
/// the purchase.
///
/// [packageToPurchase] The Package you wish to purchase
///
/// [upgradeInfo] Android only. Optional UpgradeInfo you wish to upgrade from
/// containing the oldSKU and the optional prorationMode.
static Future<PurchaserInfo> purchasePackage(Package packageToPurchase,
{UpgradeInfo upgradeInfo}) async {
var response = await _channel.invokeMethod('purchasePackage', {
'packageIdentifier': packageToPurchase.identifier,
'offeringIdentifier': packageToPurchase.offeringIdentifier,
'oldSKU': upgradeInfo != null ? upgradeInfo.oldSKU : null,
'prorationMode': upgradeInfo != null && upgradeInfo.prorationMode != null
? upgradeInfo.prorationMode.index
: null
});
return PurchaserInfo.fromJson(response["purchaserInfo"]);
}
/// Restores a user's previous purchases and links their appUserIDs to any
/// user's also using those purchases.
///
/// Returns a [PurchaserInfo] object, or throws a [PlatformException] if there
/// was a problem restoring transactions.
static Future<PurchaserInfo> restoreTransactions() async {
Map<dynamic, dynamic> result =
await _channel.invokeMethod('restoreTransactions');
return PurchaserInfo.fromJson(result);
}
/// Gets the current appUserID.
static Future<String> get appUserID async {
return await _channel.invokeMethod('getAppUserID') as String;
}
/// This function will alias two appUserIDs together.
///
/// Returns a [PurchaserInfo] object, or throws a [PlatformException] if there
/// was a problem restoring transactions.
///
/// [newAppUserID] The new appUserID that should be linked to the currently
/// identified appUserID.
static Future<PurchaserInfo> createAlias(String newAppUserID) async {
Map<dynamic, dynamic> result = await _channel
.invokeMethod('createAlias', {'newAppUserID': newAppUserID});
return PurchaserInfo.fromJson(result);
}
/// This function will identify the current user with an appUserID.
/// Typically this would be used after a logout to identify a new user without
/// calling configure
///
/// Returns a [PurchaserInfo] object, or throws a [PlatformException] if there
/// was a problem restoring transactions.
///
/// [newAppUserID] The appUserID that should be linked to the currently user
static Future<PurchaserInfo> identify(String appUserID) async {
Map<dynamic, dynamic> result =
await _channel.invokeMethod('identify', {'appUserID': appUserID});
return PurchaserInfo.fromJson(result);
}
/// Resets the Purchases client clearing the saved appUserID. This will
/// generate a random user id and save it in the cache.
///
/// Returns a [PurchaserInfo] object, or throws a [PlatformException] if there
/// was a problem restoring transactions.
static Future<PurchaserInfo> reset() async {
Map<dynamic, dynamic> result = await _channel.invokeMethod('reset');
return PurchaserInfo.fromJson(result);
}
/// Enables/Disables debugs logs
static Future<void> setDebugLogsEnabled(bool enabled) async {
return await _channel
.invokeMethod('setDebugLogsEnabled', {'enabled': enabled});
}
/// Gets current purchaser info, which will normally be cached.
static Future<PurchaserInfo> getPurchaserInfo() async {
Map<dynamic, dynamic> result =
await _channel.invokeMethod('getPurchaserInfo');
return PurchaserInfo.fromJson(result);
}
/// This method will send all the purchases to the RevenueCat backend.
///
/// **WARNING**: Call this when using your own implementation of in-app
/// purchases.
///
/// This method should be called anytime a sync is needed, like after a
/// successful purchase.
static Future<void> syncPurchases() async {
return await _channel.invokeMethod("syncPurchases");
}
/// iOS only. Enable automatic collection of Apple Search Ad attribution. Disabled by
/// default
static Future<void> setAutomaticAppleSearchAdsAttributionCollection(
bool enabled) async {
return await _channel.invokeMethod(
'setAutomaticAppleSearchAdsAttributionCollection',
{'enabled': enabled});
}
/// If the `appUserID` has been generated by RevenueCat
static Future<bool> get isAnonymous async {
return await _channel.invokeMethod('isAnonymous') as bool;
}
/// 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
/// `introEligibilityStatusUnknown`. 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 introEligibilityStatusUnknown.
///
/// [productIdentifiers] Array of product identifiers
static Future<Map<String, IntroEligibility>>
checkTrialOrIntroductoryPriceEligibility(
List<String> productIdentifiers) async {
Map<dynamic, dynamic> eligibilityMap = await _channel.invokeMethod(
'checkTrialOrIntroductoryPriceEligibility',
{'productIdentifiers': productIdentifiers});
return eligibilityMap.map((key, value) =>
MapEntry(key as String, IntroEligibility.fromJson(value)));
}
/// Invalidates the cache for purchaser 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/purchaserinfo#section-get-user-information for more information on
/// using the cache properly.
///
/// This is useful for cases where purchaser information might have been updated outside of the app, like if a
/// promotional subscription is granted through the RevenueCat dashboard.
static Future<void> invalidatePurchaserInfoCache() async {
return await _channel.invokeMethod('invalidatePurchaserInfoCache');
}
///================================================================================
/// Subscriber Attributes
///================================================================================
/// 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
///
/// [attributes] Map of attributes by key. Set the value as an empty string to delete an attribute.
static Future<void> setAttributes(Map<String, String> attributes) async {
await _channel.invokeMethod('setAttributes', {'attributes': attributes});
}
/// Subscriber attribute associated with the email address for the user
///
/// [email] Empty String or null will delete the subscriber attribute.
static Future<void> setEmail(String email) async {
await _channel.invokeMethod('setEmail', {'email': email});
}
/// Subscriber attribute associated with the phone number for the user
///
/// [phoneNumber] Empty String or null will delete the subscriber attribute.
static Future<void> setPhoneNumber(String phoneNumber) async {
await _channel.invokeMethod('setPhoneNumber', {'phoneNumber': phoneNumber});
}
/// Subscriber attribute associated with the display name for the user
///
/// [displayName] Empty String or null will delete the subscriber attribute.
static Future<void> setDisplayName(String displayName) async {
await _channel.invokeMethod('setDisplayName', {'displayName': displayName});
}
/// Subscriber attribute associated with the push token for the user
///
/// [pushToken] Null will delete the subscriber attribute.
static Future<void> setPushToken(String pushToken) async {
await _channel.invokeMethod('setPushToken', {'pushToken': pushToken});
}
}
/// This class holds the information used when upgrading from another sku.
///
/// [oldSKU] The oldSKU to upgrade from.
/// [prorationMode] The [ProrationMode] to use when upgrading the given oldSKU.
class UpgradeInfo {
String oldSKU;
ProrationMode prorationMode;
UpgradeInfo(this.oldSKU, {this.prorationMode});
}
/// Replace SKU's ProrationMode.
enum ProrationMode {
unknownSubscriptionUpgradeDowngradePolicy,
/// Replacement takes effect immediately, and the remaining time will be
/// prorated and credited to the user. This is the current default behavior.
immediateWithTimeProration,
/// Replacement takes effect immediately, and the billing cycle remains the
/// same. The price for the remaining period will be charged. This option is
/// only available for subscription upgrade.
immediateAndChargeProratedPrice,
/// Replacement takes effect immediately, and the new price will be charged on
/// next recurrence time. The billing cycle stays the same.
immediateWithoutProration,
/// Replacement takes effect when the old plan expires, and the new price will
/// be charged at the same time.
deferred
}
/// Supported SKU types.
enum PurchaseType {
/// A type of SKU for in-app products.
inapp,
/// A type of SKU for subscriptions.
subs
}
/// Supported Attribution networks.
enum PurchasesAttributionNetwork {
appleSearchAds,
adjust,
appsflyer,
branch,
tenjin,
facebook
}
enum IntroEligibilityStatus {
/// RevenueCat doesn't have enough information to determine eligibility.
introEligibilityStatusUnknown,
/// The user is not eligible for a free trial or intro pricing for this product.
introEligibilityStatusIneligible,
/// The user is eligible for a free trial or intro pricing for this product.
introEligibilityStatusEligible
}
/// Holds the introductory price status
class IntroEligibility {
/// The introductory price eligibility status
IntroEligibilityStatus status;
/// Description of the status
String description;
IntroEligibility.fromJson(Map<dynamic, dynamic> map)
: status = IntroEligibilityStatus.values[map["status"]],
description = map["description"];
}