purchases_flutter 0.3.2

RevenueCat

😻 In-app Subscriptions Made Easy 😻

pub package

purchases_flutter #

purchases_flutter is a client for the RevenueCat subscription and purchase tracking system. It is an open source framework that provides a wrapper around StoreKit, Google Play Billing and the RevenueCat backend to make implementing in-app subscriptions in Flutter easy - receipt validation and status tracking included!

Features #

RevenueCat
Server-side receipt validation
➡️Webhooks - enhanced server-to-server communication with events for purchases, renewals, cancellations, and more
🖥macOS support
🎯Subscription status tracking - know whether a user is subscribed whether they're on iOS, Android or web
📊Analytics - automatic calculation of metrics like conversion, mrr, and churn
📝Online documentation up to date
🔀Integrations - over a dozen integrations to easily send purchase data where you need it
💯Well maintained - frequent releases
📮Great support - Help Center
🤩Awesome new features

Installation #

To use this plugin, add purchases_flutter as a dependency in your pubspec.yaml file.

Requirements #

purchases_flutter requires XCode 10.2+ and minimum targets iOS 9.0+ and macOS 10.12+

Getting Started #

For more detailed information, you can view our complete documentation at docs.revenuecat.com.

1. Get a RevenueCat API key #

Log in to the RevenueCat dashboard and obtain a free API key for your application.

2. Initialize an Purchases object

Don't forget to enable the In-App Purchase capability for your project under Project Target -> Capabilities -> In-App Purchase

You should only configure Purchases once (usually on app launch) as soon as your app has a unique user id for your user. This can be when a user logs in if you have accounts or on launch if you can generate a random user identifier.

import 'package:purchases_flutter/purchases_flutter.dart';

Purchases.setDebugLogsEnabled(true);
await Purchases.setup("my_api_key");

3. Displaying Available Products #

Purchases will automatically fetch the latest active entitlements and get the product information from Apple or Google. This means when users launch your purchase screen, products will already be loaded.

Below is an example of fetching entitlements and launching an upsell screen.

try {
  Map<String, Entitlement> entitlements = await Purchases.getEntitlements();
} on PlatformException catch(e) {
  
}

4. Make a purchase #

When it comes time to make a purchase, Purchases has a simple method, makePurchase. The code sample below shows the process of purchasing a product and confirming it unlocks the "my_entitlement_identifier" content.

try {
  PurchaserInfo purchaserInfo = await Purchases.makePurchase(product.identifier);
  var isPro = purchaserInfo.entitlements.all["my_entitlement_identifier"].isActive;
  if (isPro) {
    // Unlock that great "pro" content
  }
} on PlatformException catch (e) {
  if (!(e.details as Map)["userCancelled"]) {
    showError(e);
  }
}

makePurchase handles the underlying framework interaction and automatically validates purchases with Apple and Google through our secure servers. This helps reduce in-app purchase fraud and decreases the complexity of your app. Receipt tokens are stored remotely and always kept up-to-date.

5. Get Subscription Status #

Purchases makes it easy to check what active subscriptions the current user has. This can be done two ways within the .purchaserInfo method:

  1. Checking active Entitlements - this lets you see what entitlements (from RevenueCat dashboard) are active for the user.
  2. Checking the active subscriptions - this lets you see what product ids (from iTunes Connect or Play Store) are active for the user.
// Get purchaser info
try {
  PurchaserInfo purchaserInfo = await Purchases.getPurchaserInfo();
  if (purchaserInfo.entitlements.all["my_entitlement_identifier"].isActive) {
    // Grant user "pro" access
  }
} on PlatformException catch (e) {
  // Error fetching purchaser info
}

Since the SDK updates and caches the latest PurchaserInfo when the app becomes active, the completion block in .purchaserInfo won't need to make a network request in most cases.

Listening For Purchaser Info Updates #

Since Purchases SDK works seamlessly on any platform, a user's purchase info may change from a variety of sources. You can respond to any changes in purchaser info by conforming to an optional listener. This will fire whenever we receive a change in purchaser info and you should expect it to be called at launch and throughout the life of the app.

Depending on your app, it may be sufficient to ignore the delegate and simply handle changes to purchaser information the next time your app is launched.

Purchases.addPurchaserInfoUpdateListener((purchaserInfo) => {
  // handle any changes to purchaserInfo
});

Restoring Purchases #

Restoring purchases is a mechanism by which your user can restore their in-app purchases, reactivating any content that had previously been purchased from the same store account (Apple or Google).

If two different App User IDs try to restore transactions from the same underlying store account (Apple or Google) RevenueCat will create an alias between the two App User IDs and count them as the same user going forward.

This is a common if your app does not have accounts and is relying on RevenueCat's random App User IDs.

try {
  PurchaserInfo purchaserInfo = Purchases.restoreTransactions();
} on PlatformException catch (e) {
 // Error restoring
}

Restoring purchases for logged in users:

If you've provided your own App User ID, calling restoreTransactions could alias the logged in user to another generated App User ID that has made a purchase on the same device.

Allow Sharing App or Play Store Accounts

By default, RevenueCat will not let you reuse an App or Play Store account that already has an active subscription. If you set allowSharingAppStoreAccount = True the SDK will be permissive in accepting shared accounts, creating aliases as needed.

By default allowSharingAppStoreAccount is True for RevenueCat random App User IDs but must be enabled manually if you want to allow permissive sharing for your own App User IDs.

Error Handling #

When an error has occurred, an PlatformException will be thrown. For a complete list of errors, see our online error handling documentation: https://docs.revenuecat.com/docs/errors

When investigating or logging errors, review the details dictionary, paying attention to the following keys:

  • readableErrorCode contains a cross-platform error name string that can be used for identifying the error.
  • underlyingErrorMessage contains the underlying error that caused the error in question, if an underlying error is present.

Debugging #

You can enabled detailed debug logs by setting setDebugLogsEnabled(true). You can set this before you configure Purchases.

Purchases.setDebugLogsEnabled(true);
await Purchases.setup("my_api_key");

OS_ACTIVITY_MODE

On iOS, disabling OS_ACTIVITY_MODE in your XCode scheme will block debug logs from printing in the console. If you have debug logs enabled, but don't see any output, go to Product -> Scheme -> Edit Scheme... in Xcode and uncheck the OS_ACTIVITY_MODE environment variable.

Example output:

[Purchases] - DEBUG: Debug logging enabled.
[Purchases] - DEBUG: SDK Version - 2.6.0
[Purchases] - DEBUG: Initial App User ID - (null)
[Purchases] - DEBUG: GET /v1/subscribers/<APP_USER_ID>
[Purchases] - DEBUG: GET /v1/subscribers/<APP_USER_ID>/products
[Purchases] - DEBUG: No cached entitlements, fetching
[Purchases] - DEBUG: Vending purchaserInfo from cache
[Purchases] - DEBUG: applicationDidBecomeActive
[Purchases] - DEBUG: GET /v1/subscribers/<APP_USER_ID>/products 200

Entitlements #

An entitlement represents features or content that a user is "entitled" to. With Entitlements, you can set up your available in-app products remotely and control their availability without the need to update your app. For more information on configuring entitlements, look at our entitlements documetation.

Sample App #

We've added an example in this project showing a simple example using Purchases with the RevenueCat backend. Note that the pre-registered in app purchases in the demo apps are for illustration purposes only and may not be valid in App Store Connect. Set up your own purchases with RevenueCat when running the example.

Next Steps #

Reporting Issues #

You can use Github Issues to report any bugs and issues with Purchases. Here is some advice for users that want to report an issue:

  1. Make sure that you are using the latest version of Purchases. The issue that you are about to report may be already fixed in the latest master branch version: https://github.com/revenuecat/purchases-flutter/tree/master.
  2. Providing reproducible steps for the issue will shorten the time it takes for it to be fixed - a Gist is always welcomed!
  3. Since some issues are Sandbox specific, specifying what environment you encountered the issue might help. ​

Technical Support or Questions #

If you have questions or need help integrating Purchases please start by heading to our online documentation and checking out the guides and support resources we have there.

Feature Requests #

If there is something you'd like to see included or feel anything is missing you can add a feature to our public roadmap. If the feature already exists, or you see something else you'd like, upvote it.

Pricing #

Purchases SDK is free to use but some features require a paid plan. You can find more about that on our website on the pricing plan page.

0.3.2 #

  • Fixes expirationDate in EntitlementInfo for iOS.

0.3.1 #

  • Fixes crash when there's a trial period and not an introductory price on Android.

0.3.0 #

  • Deprecates activeEntitlements in PurchaserInfo and adds entitlements object to PurchaserInfo. For more info check out https://docs.revenuecat.com/docs/purchaserinfo
  • Fixes exception when calling makePurchase with a bad product identifier in iOS
  • Fixes makePurchase missing the userCancelled boolean in Android
  • Fixes makePurchase not working in Android when calling with oldSkus parameter
  • Fixes trial info being lost in Android. Access introductoryPrice in the product information to get information around the trial period.

0.2.2 #

0.2.1 #

  • Makes some changes to the introductory pricing due to some inconsistencies introduced in 0.2.0. Introductory pricing is now an object part of the product.

0.2.0 #

0.1.4 #

  • Fixes UninitializedPropertyAccessException when trying to close the instance onDestroy of the Android Activity.

0.1.3 #

  • Formats files

0.1.2 #

  • Adds more docs to custom types
  • Fixes report issue link

0.1.1 #

  • Fixes userCancelled in Android
  • Adds docs

0.1.0 #

  • Initial release

example/README.md

This project is a starting point for a Flutter application with a RevenueCat integration. For help getting started with, view our online documentation.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  purchases_flutter: ^0.3.2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:purchases_flutter/purchases_flutter.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
79
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
89
Learn more about scoring.

We analyzed this package on Sep 17, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.0
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.2

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Fix lib/purchaser_info_wrapper.dart. (-0.50 points)

Analysis of lib/purchaser_info_wrapper.dart reported 1 hint:

line 35 col 9: 'activeEntitlements' is deprecated and shouldn't be used.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test