flutter_inapp_purchase 0.8.7

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 95

flutter_inapp_purchase

pub version

In App Purchase plugin for flutter. This project has been forked from react-native-iap. We are trying to share same experience of in-app-purchase in flutter as in react-native. We will keep working on it as time goes by just like we did in react-native-iap.

PR is always welcomed.

Breaking Changes

  • There was parameter renaming in 0.5.0 to identify different parameters sent from the device. Please check the readme.

Getting Started

Follow the Medium Blog for the configuration.

For help getting started with Flutter, view our online documentation.

For help on editing plugin code, view the documentation.

Methods

FuncParamReturnDescription
prepareStringDeprecated Use initConnection instead.
initConnectionStringPrepare IAP module. Must be called on Android before any other purchase flow methods. In ios, it will simply call canMakePayments method and return value.
getProductsList<String> Product IDs/skusList<IAPItem>Get a list of products (consumable and non-consumable items, but not subscriptions). Note: On iOS versions earlier than 11.2 this method will return subscriptions if they are included in your list of SKUs. This is because we cannot differentiate between IAP products and subscriptions prior to 11.2.
getSubscriptionsList<String> Subscription IDs/skusList<IAPItem>Get a list of subscriptions. Note: On iOS this method has the same output as getProducts. Because iOS does not differentiate between IAP products and subscriptions.
getPurchaseHistoryList<IAPItem>Gets an invetory of purchases made by the user regardless of consumption status (where possible)
getAvailablePurchasesList<PurchasedItem>(aka restore purchase) Get all purchases made by the user (either non-consumable, or haven't been consumed yet)
getAppStoreInitiatedProductsList<IAPItem>If the user has initiated a purchase directly on the App Store, the products that the user is attempting to purchase will be returned here. (iOS only) Note: On iOS versions earlier than 11.0 this method will always return an empty list, as the functionality was introduced in v11.0. See Apple Docs for more info Always returns an empty list on Android.
buySubscriptionstring Subscription ID/sku, string Old Subscription ID/sku (on Android)PurchasedItemCreate (buy) a subscription to a sku. For upgrading/downgrading subscription on Android pass second parameter with current subscription ID, on iOS this is handled automatically by store.
buyProductstring Product ID/skuPurchasedItemBuy a product
buyProductWithoutFinishTransactionstring Product ID/skuPurchasedItemBuy a product without finish transaction call (iOS only)
finishTransactionvoidStringSend finishTransaction call to Apple IAP server. Call this function after receipt validation process
consumePurchaseString Purchase tokenStringConsume a product (on Android.) No-op on iOS.
endConnectionStringEnd billing connection (on Android.) No-op on iOS.
consumeAllItemsStringManually consume all items in android. Do NOT call if you have any non-consumables (one time purchase items). No-op on iOS.
validateReceiptIosMap<String,String> receiptBody, bool isTesthttp.ResponseValidate receipt for ios.
validateReceiptAndroidString packageName, String productId, String productToken, String accessToken, bool isSubscriptionhttp.ResponseValidate receipt for android.

Data Types

  • IAPItem

    final String productId;
    final String price;
    final String currency;
    final String type;
    final String localizedPrice;
    final String title;
    final String description;
    final String introductoryPrice;
    /// ios only
    final String introductoryPricePaymentModeIOS;
    final String introductoryPriceNumberOfPeriodsIOS;
    final String introductoryPriceSubscriptionPeriodIOS;
    final String subscriptionPeriodNumberIOS;
    final String subscriptionPeriodUnitIOS;
    /// android only
    final String subscriptionPeriodAndroid;
    final String introductoryPriceCyclesAndroid;
    final String introductoryPricePeriodAndroid;
    final String freeTrialPeriodAndroid;
    
  • PurchasedItem

    final dynamic transactionDate;
    final String transactionId;
    final String productId;
    final String transactionReceipt;
    final String purchaseToken;
    // Android only
    final bool autoRenewingAndroid;
    final String dataAndroid;
    final String signatureAndroid;
    // iOS only
    final dynamic originalTransactionDateIOS;
    final String originalTransactionIdentifierIOS;
    

Install

Add flutter_inapp_purchase as a dependency in pubspec.yaml

For help on adding as a dependency, view the documentation.

Configuring in app purchase

Usage Guide

Android connect and endConnection

  • You should start the billing service in android to use its funtionalities. We recommend you to use initConnection getter method in initState().
      /// start connection for android
      @override
      void initState() {
        super.initState();
        asyncInitState(); // async is not allowed on initState() directly
      }
    
      void asyncInitState() async {
        await FlutterInappPurchase.initConnection;
      }
    
  • You should end the billing service in android when you are done with it. Otherwise it will be keep running in background. We recommend to use this feature in dispose().
      /// start connection for android
      @override
      void dispose() async{
        super.dispose();
        await FlutterInappPurchase.endConnection;
      }
    

Get IAP items

  void getItems () async {
    List<IAPItem> items = await FlutterInappPurchase.getProducts(_productLists);
    for (var item in items) {
      print('${item.toString()}');
      this._items.add(item);
    }
  }

Purchase Item

  void purchase() async {
    PurchasedItem purchased = await FlutterInappPurchase.buyProduct(item.productId);
    print('purcuased - ${purchased.toString()}');
  }

Receipt validation

From 0.7.1, we support receipt validation. For Android, you need separate json file from the service account to get the access_token from google-apis, therefore it is impossible to implement serverless. You should have your own backend and get access_token. With access_token you can simply call validateReceiptAndroid method we implemented. Further reading is here. Currently, serverless receipt validation is possible using validateReceiptIos method. The first parameter, you should pass transactionReceipt which returns after buyProduct. The second parameter, you should pass whether this is test environment. If true, it will request to sandbox and false it will request to production.

  validateReceipt() async {
    var receiptBody = {
      'receipt-data': purchased.transactionReceipt,
      'password': '******'
    };
    const result = await validateReceiptIos(receiptBody, false);
    console.log(result);
  }

For further information, please refer to guide.

App Store initiated purchases

When the user starts an in-app purchase in the App Store, the transaction continues in your app, the product will then be added to a list that you can access through the method getAppStoreInitiatedProducts. This means you can decide how and when to continue the transaction. To continue the transaction simple use the standard purchase flow from this plugin.

void checkForAppStoreInitiatedProducts() async {
  List<IAPItem> appStoreProducts = await FlutterInappPurchase.getAppStoreInitiatedProducts(); // Get list of products
  if (appStoreProducts.length > 0) {
    _buyProduct(appStoreProducts.last); // Buy last product in the list
  }
}

Example

Below code is just a cp from example project. You can test this in real example project.

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final List<String>_productLists = Platform.isAndroid
      ? [
    'android.test.purchased',
    'point_1000',
    '5000_point',
    'android.test.canceled',
  ]
      : ['com.cooni.point1000','com.cooni.point5000'];

  String _platformVersion = 'Unknown';
  List<IAPItem> _items = [];

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await FlutterInappPurchase.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // initConnection
    var result = await FlutterInappPurchase.initConnection;
    print ('result: $result');

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });

    // refresh items for android
    String msg = await FlutterInappPurchase.consumeAllItems;
    print('consumeAllItems: $msg');
  }

  Future<Null> _buyProduct(IAPItem item) async {
    try {
      PurchasedItem purchased= await FlutterInappPurchase.buyProduct(item.productId);
      print('purcuased - ${purchased.toString()}');
    } catch (error) {
      print('$error');
    }
  }

  Future<Null> _getProduct() async {
    List<IAPItem> items = await FlutterInappPurchase.getProducts(_productLists);
    for (var item in items) {
      print('${item.toString()}');
      this._items.add(item);
    }

    setState(() {
      this._items = items;
    });
  }

  _renderInapps() {
    List<Widget> widgets = this._items.map((item) => Container(
      margin: EdgeInsets.symmetric(vertical: 10.0),
      child: Container(
        child: Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(bottom: 5.0),
              child: Text(
                item.toString(),
                style: TextStyle(
                  fontSize: 18.0,
                  color: Colors.black,
                ),
              ),
            ),
            FlatButton(
              color: Colors.orange,
              onPressed: () {
                this._buyProduct(item);
              },
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Container(
                      height: 48.0,
                      alignment: Alignment(-1.0, 0.0),
                      child: Text('Buy Item'),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    )).toList();
    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Inapp Plugin by dooboolab'),
        ),
        body:
        Container(
          padding: EdgeInsets.all(10.0),
          child: ListView(
            children: <Widget>[
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Container(
                    child: Text(
                      'Running on: $_platformVersion\n',
                      style: TextStyle(
                          fontSize: 18.0
                      ),
                    ),
                  ),
                  Container(
                    height: 60.0,
                    margin: EdgeInsets.only(bottom: 10.0),
                    child: ListView(
                      scrollDirection: Axis.horizontal,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Container(
                              margin: EdgeInsets.symmetric(horizontal: 15.0),
                              child: FlatButton(
                                color: Colors.green,
                                padding: EdgeInsets.all(0.0),
                                onPressed: () async {
                                  await FlutterInappPurchase.initConnection;
                                },
                                child: Container(
                                  padding: EdgeInsets.symmetric(horizontal: 20.0),
                                  alignment: Alignment(0.0, 0.0),
                                  child: Text(
                                    'Connect Billing',
                                    style: TextStyle(
                                      fontSize: 16.0,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            FlatButton(
                              color: Colors.green,
                              padding: EdgeInsets.all(0.0),
                              onPressed: () {
                                this._getProduct();
                              },
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 20.0),
                                alignment: Alignment(0.0, 0.0),
                                child: Text(
                                  'Get Items',
                                  style: TextStyle(
                                    fontSize: 16.0,
                                  ),
                                ),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 15.0),
                              child: FlatButton(
                                color: Colors.green,
                                padding: EdgeInsets.all(0.0),
                                onPressed: () async {
                                  await FlutterInappPurchase.endConnection;
                                  setState(() {
                                    this._items = [];
                                  });
                                },
                                child: Container(
                                  padding: EdgeInsets.symmetric(horizontal: 20.0),
                                  alignment: Alignment(0.0, 0.0),
                                  child: Text(
                                    'End Connection',
                                    style: TextStyle(
                                      fontSize: 16.0,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  Column(
                    children: this._renderInapps(),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Q & A

Can I buy product right away skipping fetching products if I already know productId?

  • You can in Android but not in ios. In ios you should always fetchProducts first. You can see more info here.

How do I validate receipt in ios?

  • Official doc is here.

How do I validate receipt in android?

  • Offical doc is here.
  • I've developed this feature for other developers to contribute easily who are aware of these things. The doc says you can also get the accessToken via play console without any of your backend server. You can get this by following process.
    • Select your app > Services & APIs > "YOUR LICENSE KEY FOR THIS APPLICATION Base64-encoded RSA public key to include in your binary". reference.

Invalid productId in ios.

  • Please try below and make sure you've done belows.
    • Steps
      1. Completed an effective "Agreements, Tax, and Banking."
      2. Setup sandbox testing account in "Users and Roles."
      3. Signed into iOS device with sandbox account.
      4. Set up three In-App Purchases with the following status: i. Ready to Submit ii. Missing Metadata iii. Waiting for Review
      5. Enable "In-App Purchase" in Xcode "Capabilities" and in Apple Developer -> "App ID" setting. Delete app / Restart device / Quit "store" related processes in Activity Monitor / Xcode Development Provisioning Profile -> Clean -> Build.

Help Maintenance

I've been maintaining quite many repos these days and burning out slowly. If you could help me cheer up, buying me a cup of coffee will make my life really happy and get much energy out of it. <br/><a href="https://www.buymeacoffee.com/dooboolab" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/purple_img.png" alt="Buy Me A Coffee" style="height: auto !important;width: auto !important;" ></a>

0.8.+

  • Fixed receipt validation param for android.
  • Updated http package.
  • Implemented new method getAppStoreInitiatedProducts.
    • Handling of iOS method paymentQueue:shouldAddStorePayment:forProduct:
    • Has no effect on Android.
  • Fixed issue with method buyProductWithoutFinishTransaction for iOS, was not getting the productId.
  • Fixed issue with toString method of class IAPItem, was printing incorrect values.
  • Fixes for #44. Unsafe getting originalJson when restoring item and Android.
  • Use dictionaryWithObjectsAndKeys in NSDictionary to fetch product values. This will prevent from NSInvalidArgumentException in ios which rarely occurs.
  • Fixed wrong npe in android when getAvailablePurchases.

0.7.1

  • Implemented receiptValidation for both android and ios.
    • In Android, you need own backend to get your accessToken.

0.7.0

  • Addition of Amazon In-App Purchases.

0.6.9

  • Prevent nil element exception when getting products.

0.6.8

  • Prevent nil exception in ios when fetching products.

0.6.7

  • Fix broken images on pub.

0.6.6

  • Added missing introductory fields in ios.

0.6.5

  • convert dynamic objects to PurchasedItems.
  • Fix return type for getAvailablePurchases().
  • Fix ios null value if optional operator.

0.6.3

  • Update readme.

0.6.2

  • Fixed failing when there is no introductory price in ios.

0.6.1

  • Fixed checkSubscribed that can interrupt billing lifecycle.

0.6.0

  • Major code refactoring by lukepighetti. Unify PlatformException, cleanup new, DateTime instead of string.

0.5.9

  • Fix getSubscription json encoding problem in ios.

0.5.8

  • Avoid crashing on android caused by IllegalStateException.

0.5.7

  • Avoid possible memory leak in android by deleting static declaration of activity and context.

0.5.6

  • Few types fixed.

0.5.4

  • Fixed error parsing IAPItem.

0.5.3

  • Fixed error parsing purchaseHistory.

0.5.2

  • Fix crashing on error.

0.5.1

  • Give better error message on ios.

0.5.0

  • Code migration.
  • Support subscription period.
  • There was parameter renaming in 0.5.0 to identify different parameters sent from the device. Please check the readme.

0.4.3

  • Fixed subscription return types.

0.4.0

  • Well formatted code.

0.3.3

  • Code formatted
  • Updated missing data types

0.3.1

  • Upgraded readme for ease of usage.
  • Enabled strong mode.

0.3.0

  • Moved dynamic return type away and instead give PurchasedItem.

0.2.3

  • Quickly fixed purchase bug out there in issue. Need much more improvement currently.

0.2.2

  • Migrated packages from FlutterInApp to FlutterInAppPurchase because pub won't get it.

0.1.0

example/README.md

flutter_inapp_purchase_example

Demonstrates how to use the flutter_inapp_purchase plugin.

Getting Started

For help getting started with Flutter, view our online documentation.

Use this package as a library

1. Depend on it

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


dependencies:
  flutter_inapp_purchase: ^0.8.7

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

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

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
  
Version Uploaded Documentation Archive
0.8.7 Dec 4, 2018 Go to the documentation of flutter_inapp_purchase 0.8.7 Download flutter_inapp_purchase 0.8.7 archive
0.8.6 Dec 4, 2018 Go to the documentation of flutter_inapp_purchase 0.8.6 Download flutter_inapp_purchase 0.8.6 archive
0.8.5 Oct 24, 2018 Go to the documentation of flutter_inapp_purchase 0.8.5 Download flutter_inapp_purchase 0.8.5 archive
0.8.4 Oct 24, 2018 Go to the documentation of flutter_inapp_purchase 0.8.4 Download flutter_inapp_purchase 0.8.4 archive
0.8.3 Oct 18, 2018 Go to the documentation of flutter_inapp_purchase 0.8.3 Download flutter_inapp_purchase 0.8.3 archive
0.8.2 Oct 16, 2018 Go to the documentation of flutter_inapp_purchase 0.8.2 Download flutter_inapp_purchase 0.8.2 archive
0.8.1 Oct 16, 2018 Go to the documentation of flutter_inapp_purchase 0.8.1 Download flutter_inapp_purchase 0.8.1 archive
0.8.0 Oct 10, 2018 Go to the documentation of flutter_inapp_purchase 0.8.0 Download flutter_inapp_purchase 0.8.0 archive
0.7.1 Oct 4, 2018 Go to the documentation of flutter_inapp_purchase 0.7.1 Download flutter_inapp_purchase 0.7.1 archive
0.7.0 Sep 30, 2018 Go to the documentation of flutter_inapp_purchase 0.7.0 Download flutter_inapp_purchase 0.7.0 archive

All 44 versions...

Popularity:
Describes how popular the package is relative to other packages. [more]
90
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]
95
Learn more about scoring.

We analyzed this package on Dec 5, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.1.0
  • pana: 0.12.7
  • Flutter: 1.0.0

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.20.1 <3.0.0
flutter 0.0.0
http >=0.11.3+16 <1.0.0 0.12.0
Transitive dependencies
async 2.0.8
charcode 1.1.2
collection 1.14.11
http_parser 3.1.3
meta 1.1.6
path 1.6.2
sky_engine 0.0.99
source_span 1.4.1
string_scanner 1.0.4
typed_data 1.1.6
vector_math 2.0.8