Making Android In-App Purchases With IonicFramework

The future of mobile app design is in the freemium model.  No one wants to risk paying for an application that might stink so as a developer it is a good idea to charge for features in your app rather than the app itself.

Using Apache Cordova, IonicFramework, and the poiuytrez AndroidInAppBilling plugin you can easily handle Android in-app purchases.

In your existing Ionic project, make sure that you’ve added the Android platform.  This can be done by running the following command from the command line:

The next step is to add the in-app billing plugin to your project.  Run the following commands to download and install the plugin:

Because the plugin does not reside in the root of the Git repository you must first download the entire repository to your computer and then install the latest version of the plugin.  In this case it is version 3.  So when using the above four commands, make sure to replace the path information with your own.

The AndroidInAppBilling plugin has a few commands that we are going to focus on, but there will be others you can implement on your own:

Before we begin to implement these methods in our app.js file, we need to first add the apps Base64-encoded RSA public key to the project.  Failing to add this will result in the plugin not functioning properly.  You can find this key in your Google Play Developer Console and navigating to Services & APIs inside your particular application.

Google Play License Key

Add this public key to res/values/billing_key.xml like so:

With the public key added, we can now start making in-app purchases.  The plugin must first be initialized in order to be used.  It is recommended to do this in your $ionicPlatform.ready() method:

The above code will first check to make sure you are on an Android device and that the inappbilling plugin is available.  If this is true then initialize the plugin with a defined set of product ids.  The product ids are whatever you set when adding to the Google Developer Console.  For debug purposes the showLog option is set to true.

Once initialized, we can start using other IAB commands.  For example, if you want to get all purchases that the user made in your app you can run the following:

If the method is successful, a JSON array will be returned containing INAPP_PURCHASE_DATA like explained in the official Android documentation.  Below was taken directly from the documentation:


Field Description
orderId A unique order identifier for the transaction. This corresponds to the Google Wallet Order ID.
packageName The application package from which the purchase originated.
purchaseId The item’s product identifier. Every item has a product ID, which you must specify in the application’s product list on the Google Play Developer Console.
purchaseTime The time the product was purchased, in milliseconds since the epoch (Jan 1, 1970).
purchaseState The purchase state of the order. Possible values are 0 (purchased), 1 (canceled), or 2 (refunded).
developerPayload A developer-specified string that contains supplemental information about an order. You can specify a value for this field when you make a getBuyIntentrequest.
purchaseToken A token that uniquely identifies a purchase for a given item and user pair.

Let’s say that you review the purchase list from getPurchases() and determine that you want to buy something that hasn’t already been purchased.  Simply run the following:

To string all this together, see the example app.js below.  It will initialize the IAB plugin for Android in the $ionicPlatform.ready() and get all the user’s purchases at the same time.  Then in a controller a user can make a purchase.

 

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • Reza Rahmati

    Hi
    When I call inappbilling.init I get null as error message. Am I missing something?

    • That’s weird. Can you share your full logs? I’m thinking there may be an uncaught exception somewhere.

      Regards

      • Reza Rahmati

        Hi Nic

        There is a Null Refrence error in the log,

        Here is my log

        E/PluginManager(13659): Uncaught exception from plugin
        E/PluginManager(13659): java.lang.NullPointerException
        E/PluginManager(13659): at com.smartmobilesoftware.util.IabHelper.startSetup(IabHelper.java:276)
        E/PluginManager(13659): at com.smartmobilesoftware.inappbilling.InAppBillingPlugin.init(InAppBillingPlugin.java:148)
        E/PluginManager(13659): at com.smartmobilesoftware.inappbilling.InAppBillingPlugin.execute(InAppBillingPlugin.java:67)
        E/PluginManager(13659): at org.apache.cordova.CordovaPlugin.execute(CordovaPlugin.java:84)
        E/PluginManager(13659): at org.apache.cordova.PluginManager.exec(PluginManager.java:147)
        E/PluginManager(13659): at org.apache.cordova.CordovaBridge.jsExec(CordovaBridge.java:59)
        E/PluginManager(13659): at org.apache.cordova.CordovaBridge.promptOnJsPrompt(CordovaBridge.java:129)
        E/PluginManager(13659): at org.apache.cordova.CordovaChromeClient.onJsPrompt(CordovaChromeClient.java:192)
        E/PluginManager(13659): at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:886)
        E/PluginManager(13659): at android.os.Handler.dispatchMessage(Handler.java:99)
        E/PluginManager(13659): at android.os.Looper.loop(Looper.java:137)
        E/PluginManager(13659): at android.app.ActivityThread.main(ActivityThread.java:4921)
        E/PluginManager(13659): at java.lang.reflect.Method.invokeNative(Native Method)
        E/PluginManager(13659): at java.lang.reflect.Method.invoke(Method.java:511)
        E/PluginManager(13659): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
        E/PluginManager(13659): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
        E/PluginManager(13659): at dalvik.system.NativeStart.main(Native Method)

        and this is the code

        I have changed some ids to be compatible with another market

        // if (mContext == null)
        // logDebug(“mContext is null.”)
        // else
        // logDebug(“mContext is not null.”);
        // if (serviceIntent == null)
        // logDebug(“serviceIntent is null.”)
        // else
        // logDebug(“serviceIntent is not null.”);
        /* line 276 */ if (mContext != null && !mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
        // service available to handle that Intent
        mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
        }
        else {
        // no service available to handle that Intent
        if (listener != null) {
        listener.onIabSetupFinished(
        new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
        “Billing service unavailable on device.”));
        }
        }

        also I have add some if else to check which one is null but I get “Command failed with exit code 8” on compile time.
        Then I added some conditions to if statement to prevent running code on null object, but it didn’t help.

        • Reza Rahmati

          I removed this line serviceIntent.setPackage(“ir.cafebazaar.pardakht”);
          and things become right, weired 😉

          • That is weird! Thanks for reporting back though. It will definitely help other readers 🙂

        • Can you try the following plugin commit with your project?:

          https://github.com/poiuytrez/AndroidInAppBilling/tree/e5fa36b713d947eed828d9ac0c3faecd7fb91c53

          It should be the same version I used when writing this tutorial as well as my app Snapper for Digital Ocean.. I’m thinking a bug might have been introduced in the plugin during one of the more recent commits.

          If that doesn’t work, then I think you may have a configuration issue, either on Google Play or in your code. Are you sure you are using the correct billing key and your billing skus are configured for testing?

  • Muhammad Rayhan

    Thanks for the great tutorial Nic!
    I haven’t test the real in-app purchases yet, but at least I’m able to get “IAB initialized” 🙂

    However, it’s not working as expected in my case. I need to do:
    cordova plugin add org.apache.cordova.device

    in order to have device object defined in app.js

    cordova plugin add /home/nraboy/Desktop/AndroidInAppBilling/v3 –variable BILLING_KEY “xxxx”

    in order to have inappbilling defined in app.js

    I don’t know whether other experience this also, but above tricks works for me.

    • It is strange that you had to do these extra steps, but thanks for sharing. This could help others experiencing the same issue.

      Regards,

  • Wils

    hi nic, I am a newbie of ionic.
    i have a problem to implement in-app puchase for android platform in ionic.
    my project use ionic modular methode. I have followed the steps in your blog. in this case, inappbilling and device is not defined.
    how can I fix it?
    could you help me to give a more detailed tutorial or video?

    • What do your full Android logs say? If you’re not sure how to get them, please see this:

      https://www.thepolyglotdeveloper.com/2014/12/debugging-android-source-code-adb/

      Regards,

      • Wils

        nic, in my console, “inappbilling” is not defined. how can i fix it?

        i try implement in app.js like this.

        function appRun( $state, $ionicPlatform, $cordovaStatusbar, MomentSetupService, $ionicPopup) {
        // App Ready!
        $ionicPlatform.ready( function() {
        MomentSetupService.set();

        inappbilling.init(function(resultInit) {
        inappbilling.getPurchases(function(result) {
        console.log(“PURCHASE RESPONSE -> ” + JSON.stringify(result));
        },
        function(errorPurchases) {
        console.log(“PURCHASE ERROR -> ” + errorPurchases);
        });
        },

        },
        {showLog: true},
        [“signup”]);
        }
        });

        }

        not define log ->image 1
        and my app.js position ->image 2

        please help me nic,
        Thanks

        • I’m not sure what debug utility you are using. Can you use ADB and paste the full logs?

          Also, please confirm that you are NOT using Ionic Serve, Ionic View, or Ionic Live-Reload.

          Regards,

  • jvolt

    Hi Nic, I’ve been following your instructions about providing Android in-app purchases, but just after I bought ad_free my app crashes.

    I am using a developer account, Google says it will not bill me for that, I think at this days Google permit that developers can buy their own in-app items, am I wrong?

    My code is the same as yours ( on http://pastebin.com/HPcyZTr1 ), Ionic 1.4.5.

    The error shown in Google Developer Console is:

    java.lang.IllegalArgumentException: com.smartmobilesoftware.util.Base64DecoderException: single trailing character at offset 388
    at com.smartmobilesoftware.util.Security.generatePublicKey(Security.java:70)
    at com.smartmobilesoftware.util.Security.verifyPurchase(Security.java:47)
    at com.smartmobilesoftware.util.IabHelper.queryPurchases(IabHelper.java:869)
    at com.smartmobilesoftware.util.IabHelper.queryInventory(IabHelper.java:544)
    at com.smartmobilesoftware.util.IabHelper.queryInventory(IabHelper.java:522)
    at com.smartmobilesoftware.util.IabHelper$2.run(IabHelper.java:617)
    at java.lang.Thread.run(Thread.java:841)
    Caused by: com.smartmobilesoftware.util.Base64DecoderException: single trailing character at offset 388
    at com.smartmobilesoftware.util.Base64.decode(Base64.java:531)
    at com.smartmobilesoftware.util.Base64.decode(Base64.java:446)
    at com.smartmobilesoftware.util.Base64.decode(Base64.java:392)
    at com.smartmobilesoftware.util.Security.generatePublicKey(Security.java:60)

    • Java errors typically mean there is an issue with the plugin itself. You might want to open an issue ticket with the developer on his GitHub.

      Also, Google does not allow developers to purchase their own apps and in-app-purchases. You must create a new Google account if you wish to test your purchases in production.

      Regards,

  • Albert Vince Mendiola

    Hi Nic, i was installing this plugin to my app and i got this error when trying to build it. i don’t how to fix this, i tried removing the plugin but the problem persist. 🙁

    BUILD FAILED

    C:UsersVinceAppDataLocalAndroidandroid-sdktoolsantbuild.xml:653: The following error occurred while executing this line:
    C:UsersVinceAppDataLocalAndroidandroid-sdktoolsantbuild.xml:698: null returned: 1

    Total time: 2 seconds
    C:UsersVinceDocumentsubuntu-boxgg-mobileplatformsandroidcordovanode_modulesqq.js:126
    throw e;
    ^
    Error code 1 for command: cmd with args: /s,/c,ant,debug,-f,C:UsersVinceDocumentsubuntu-boxgg-mobileplatformsandr

    oidbuild.xml,-Dout.dir=ant-build,-Dgen.absolute.dir=ant-gen

    ERROR building one of the platforms: Error: C:UsersVinceDocumentsubuntu-boxgg-mobileplatformsandroidcordovabuil

    d.bat: Command failed with exit code 1

    You may not have the required environment or OS to build this project

    Error: C:UsersVinceDocumentsubuntu-boxgg-mobileplatformsandroidcordovabuild.bat: Command failed with exit code

    1

    at ChildProcess.emit (events.js:110:17)
    at maybeClose (child_process.js:1008:16)
    at Process.ChildProcess._handle.onexit (child_process.js:1080:5)

    • Sounds like your install of Ionic Framework, Apache Cordova, or Android is not correct. Nowhere in that log leads me to believe it is the code or plugin with problems.

      You may want to consult install documentation or the forums for getting help set up.

      Regards,

      • Albert Vince Mendiola

        i see, thanks nic, i’ll look into it.

        Regards,

      • Albert Vince Mendiola

        Hi Nic, finally found the reason causing the build failure. this is my fault.

        Kind Regards,

      • Albert Vince Mendiola

        Hi Nic! i’ve manage to install the plugin following your tutorial, I’ve encounter this error

        i did not yet setup a product id from play google console and merchant account. i just followed the tutorial and installed the signed APK to my device. do i need to do that first? is this the reason to cause the error? by the way i remove the condition(if device = android) temporarily.

        D/CordovaLog(10724): file:///android_asset/www/js/controllers.js: Line 328 : In App purchase
        I/Web Console(10724): In App purchase:328
        D/CordovaLog(10724): file:///android_asset/www/plugins/com.smartmobilesoftware.androidinappbilling/www/inappbilling.js: Line 6:InAppBilling[js]: set up ok
        I/Web Console(10724): InAppBilling[js]: setup ok:6
        D/CordovaLog(10724):file:///android_asset/www/plugins/com.smartmobilesoftware.androidinappbilling/www/inappbilling.js: Line 6 : InAppBilling[js]: load [“productId1″,”productId2″,”productId3”]
        I/Web Console(10724): InAppBilling[js]: load [“productId1″,”productId2″,”productId3”]:6
        D/CORDOVA_BILLING(10724): Num SKUs Found: 3
        D/CORDOVA_BILLING(10724): Product SKU Added: productId1
        D/CORDOVA_BILLING(10724): Product SKU Added: productId2
        D/CORDOVA_BILLING(10724): Product SKU Added: productId3
        D/CORDOVA_BILLING(10724): init start
        D/CORDOVA_BILLING(10724): Creating IAB helper.
        D/CORDOVA_BILLING(10724): Starting setup.
        D/IabHelper(10724): Starting in-app billing setup.
        D/IabHelper(10724): Billing service connected.
        D/IabHelper(10724): Checking for in-app billing 3 support.
        D/CORDOVA_BILLING(10724): onActivityResult(0,0,null
        E/IabHelper(10724): In-app billing error: Illegal state for operation (handleActivityResult): IAB helper is not set up.
        D/Finsky (10890): [915] InAppBillingUtils.pickAccount: com.syntacticsinc.gameofgenerals: Account determined from installer data – [NStR7rG3gHHTGMyFChqhAgKdROU]
        D/IabHelper(10724): In-app billing version 3 supported for com.syntacticsinc.gameofgenerals
        D/Finsky (10890): [890] InAppBillingUtils.pickAccount: com.syntacticsinc.gameofgenerals: Account determined from installer data – [NStR7rG3gHHTGMyFChqhAgKdROU]
        D/IabHelper(10724): Subscriptions AVAILABLE.
        D/CORDOVA_BILLING(10724): Setup finished.
        D/CORDOVA_BILLING(10724): Setup successful. Querying inventory w/ SKUs.
        D/IabHelper(10724): Starting async operation: refresh inventory
        D/CordovaLog(10724):file:///android_asset/www/plugins/com.smartmobilesoftware.androidinappbilling/www/inappbilling.js: Line 6 : InAppBilling[js]: buy called!

        D/IabHelper(10724): Querying owned items, item type: inapp
        D/IabHelper(10724): Package name: com.company.app
        D/IabHelper(10724): Calling getPurchases with continuation token: null
        I/Web Console(10724): InAppBilling[js]: buy called!:6
        D/CordovaLog(10724): file:///android_asset/www/js/controllers.js: Line 349 : ERROR BUYING -> IAB helper is not set up. Can’t perform operation: handle
        ActivityResult

        I/Web Console(10724): ERROR BUYING -> IAB helper is not set up. Can’t perform operation: handleActivityResult:349
        D/Finsky (10890): [891] InAppBillingUtils.pickAccount: com.company.app: Account determined from installer data – [NStR7rG3gHHTGMyFChqhAgKdROU]
        D/IabHelper(10724): Owned items response: 0
        D/IabHelper(10724): Continuation token: null
        D/IabHelper(10724): Querying SKU details.
        D/IabHelper(10724): moreSkus: Building SKUs List
        D/IabHelper(10724): moreSkus: productId1
        D/IabHelper(10724): moreSkus: productId2
        D/IabHelper(10724): moreSkus: productId3
        D/Finsky (10890): [915] InAppBillingUtils.pickAccount: com.company.app: Account determined from installer data – [NStR7rG3gHHTGMyFChqhAgKdROU]
        D/IabHelper(10724): Querying owned items, item type: subs
        D/IabHelper(10724): Package name: com.company.app
        D/IabHelper(10724): Calling getPurchases with continuation token: null
        D/Finsky (10890): [890] InAppBillingUtils.pickAccount: com.company.app: Account determined from installer data – [NStR7rG3gHHTGMyFChqhAgKdROU]
        D/IabHelper(10724): Owned items response: 0
        D/IabHelper(10724): Continuation token: null
        D/IabHelper(10724): Querying SKU details.
        D/IabHelper(10724): moreSkus: Building SKUs List
        D/IabHelper(10724): moreSkus: productId1
        D/IabHelper(10724): moreSkus: productId2
        D/IabHelper(10724): moreSkus: productId3
        D/Finsky (10890): [891] InAppBillingUtils.pickAccount: com.company.app: Account determined from installer data – [NStR7rG3gHHTGMyFChqhAgKdROU]
        D/IabHelper(10724): Ending async operation: refresh inventory
        D/CORDOVA_BILLING(10724): Inside mGotInventoryListener
        D/CORDOVA_BILLING(10724): Query inventory was successful.
        W/CordovaPlugin(10724): Attempted to send a second callback for ID: InAppBillingPlugin1414016375
        W/CordovaPlugin(10724): Result was: “OK”

        thank you for the tutorial by the way, it is very simple and straightforward.

        Regards,

        • Albert Vince Mendiola

          Hi Nic! I’ve manage to integrate the plugin properly. it’s working now. the reason it didn’t work in the first try was i initialized the plugin in my app.js and called buy from my controller.js. what i did was i initialized the plugin in the controller.js

          $scope.initbuy = function() {
          inappbilling.init(function(resultInit) {
          inappbilling.getPurchases(function(result) {
          console.log(“PURCHASE RESPONSE -> ” + JSON.stringify(result));

          Thanks a lot for the tutorial. Have a good one!

          Best Regards!

          • I’m glad you figured it out 🙂

  • ron

    Thanks!
    What is BILLING_KEY? where can I find it?

    • It is the public key, probably found in your Google Play dashboard Services and APIs section.

      • ron

        thank you 🙂

  • ron

    inappbilling.buy error function get “IAB helper is not set up. Can’t perform operation: handleActivityResult”

    any idea?

  • vina

    Hi Nic, Thanks for showing this tutorial.

    I am using ionic framework with angularjs
    Everything working fine but when buying an items at first the payment successfully succeeded but it redirect to error callback function instead of success callback function and shows the following error message,

    ” Error purchasing :iabResult:Signature verification failed for sku android.test.purchased (response:-1003:Purchase signature verification failed) ” .

    followed by when i reinitialize the plugins it shows the following error

    ” Failed to query inventory:labResult:Error refreshing inventory (querying owned items). (response:-1003:Purchase signature verification failed) ”

    can you explain me what is happening, i was confused on describing the method .

    • Are you trying to purchase items using the same account as your developer account? If so, you’re going to get all kinds of errors. Also did you remember to add a correct billing key? The key is used for signatures during purchases.

      Regards,

      • vina

        Thanks Nic,

        The billing key i am using in my code is same as in google play developer account and also i wasn’t purchased on same developer account but it provides the same error message..
        Is there anything to change. in my code.. why because i need to use consume purchase method.

        • Put your entire project on GitHub and I’ll take a look. I’m pretty sure the error will exist in your configuration, not your code though.

          Regards,

          • Rangel Torrezan

            Hi, I’m too having same problem, someone get solve?

    • Rajkanna

      Hi Vina….We too encountering the same issues…buying first time is success but could not make consumable purchase for buying coins. Can you please share us your fix for this. Appreciate your help on this

      • You sure you set the IAB item as consumable via the Google Play dashboard? I know that dashboard can often be confusing.

        • Rajkanna

          Hi Nic…Thanks for your prompt response…Let me check and update you the status.

  • Rangel Torrezan

    Hi Nic …

    I add plugin, and aplication start fine … without errors, but i can’t get purchases.

    In the console show PURCHASE REPONSE -> [ ] …

    The products were created correct on play store.

    any idea?

  • Rangel Torrezan

    Hi Nic Raboy …

    I’m trying to use this plugin … and when run with ionic run android -l -c -s I can get logs e the plugin works, just for get itens. This is fine. But, when I run on device (compile, assign and install) dont show itens.

    Have you any ideia?

    I publish version (0.0.4) in google Play Store (alfa test) and I used the same version in device.

    I tried use the cordova-plugin-purchase (https://github.com/j3k0/cordova-plugin-purchase) and get the same problem.

    Tks for your help.

    • I encourage you to not use live-reload when testing. It has a history of problems, one of which you might be facing right now. Beyond that, what do the logs say when you’re on a device?

      • Rangel Torrezan

        @nicraboy:disqus, i used logcat | grep -i “console”, but i can’t get any log to help.

        • Your best bet is to do it without grepping and search the logs manually as you trigger the purchase events. They may not be broadcasting on “console”.

          Regards,

          • Rangel Torrezan

            hi @nicraboy:disqus. I got the error: file:///android_asset/www/lib/ionic/js/ionic.bundle.js: Line 20434 : ReferenceError: inappbilling is not defined.

            When I ran with ionic run emulate, the plugin worked fine.

          • What version of Android are you using on your device and what version are you using in the simulator?

            Regards,

  • Shandy Kurnia

    Hi NIc,

    I’m trying use your plugin but i found some issues.
    So whenever i try to reload price product which i managed in Google Play account, I got error when GooglePlay popup showed , such as “The Item you are requested is not available for purchase”.
    Any advice what should i check regarding that error ?

    Thanks

    • You would have to read the Google documentation regarding In-App-Billing. The plugin only makes it possible, but it still uses all the policies that Google put in place.

      Best,

  • Kumar Gandhi K

    Thanks for the write up Nic. I needed it.
    Besides too many ads on the page dude. I remember coming here a while back and don’t remember seeing any ads.

    • Three ads within the content, then whatever Disqus decides they want to put right above the comment section. Without donations or purchasing of my paid content, this blog needs ads to survive. It is expensive to run.

      Regards,

  • Nibhatish

    I was facing error – missing variable Billing_key at step – cordova plugin add /home/nraboy/Desktop/AndroidInAppBilling/. Adding –variable BILLING_KEY=” worked for me

  • Martin Capraro

    Hi Nic

    Thanks for the great tutorial Nic. This is exactly what I was looking for. I am however having some trouble using the plugin.

    I follow the steps exactly, but calling the InAppBilling.init function throws the error ‘Uncaught ReferenceError: InAppBilling is not defined, http://localhost:8101/js/app.js‘. The result is the same if I test on a device and use adb logcat. I’ve been Googling it for days, with no luck, and the plugin’s documentation appears to be out of date with the latest version.

    I’ve installed and uninstalled the plugin multiple times (with cordova plugin add /path/to/cloned/repo/AndroidInAppBilling –variable BILLING_KEY=”…”). I’m using the Webstorm IDE, and InAppBilling.prototype.init definitely resolves there, so I think the problem lies in the config that ties the pieces together so to speak.

    I’m running cordova 5.4.1 and Ionic 1.7.12.

    Any help or workarounds you can recommend would be greatly appreciated.

    Regards
    Martin

    • The http://localhost:8101 in your log tells me you’re trying to use ionic serve, ionic live reload or ionic view. These services cannot be used when working with native plugins, otherwise you’ll get errors exactly as you are now.

      Regards,

      • Martin Capraro

        Thanks so much for the reply!

        I get the same error when running ionic emulate android (see below for adb logcat log, and notice the error that’s being thrown ) and also when I build the apk file and manually install it. I’d be very happy if there is something obvious I’m missing/misunderstanding.

        01-12 12:44:57.370 2229 2229 I chromium: [INFO:CONSOLE(24)] “Trying to fire up AndroidInAppBilling plugin…”, source: file:///android_asset/www/js/app.js (24)
        01-12 12:44:57.370 2229 2229 I chromium: [INFO:CONSOLE(25)] “typeoff InAppBilling = undefined”, source: file:///android_asset/www/js/app.js (25)
        01-12 12:44:57.370 2229 2229 I chromium: [INFO:CONSOLE(28)] “Uncaught ReferenceError: InAppBilling is not defined”, source: file:///android_asset/www/js/app.js (28)

        • Are you wrapping your code in an $ionicPlatform.ready? Are you sure the plugin is installed correctly?

          • Martin Capraro

            Yes, the code is wrapped in $ionicPlatform.ready. I’m not sure if the plugin is correctly installed, but it is displayed when I do cordova plugin list 😀 (I installed it using cordova plugin add /path/to/cloned/repo/AndroidInAppBilling –variable BILLING_KEY=”…” )

            If I paste the contents of inappbilling.js in a file and include that as a script in index.html I at least get the log message

            2 271452 log InAppBilling[js]: setup ok
            3 271452 log InAppBilling[js]: load [“productId1″,”productId2″,”productId3”]

            which is otherwise not displayed. This suggests to me that the plugin is just not properly wired up for some reason.

          • s3v3n

            i have some same problems, too. I think, that i must first upload a new apk to google play with billig support, to test on the emulator (Genymotion) because i get the following errors:

            Start: ionic run android -l -c -s (genymotion)

            9 297570 log InAppBilling[js]: setup ok
            10 297574 log InAppBilling[js]: load [“ad_free”]
            11 297581 log InAppBilling[js]: buy called!
            12 297587 log ERROR BUYING -> Billing plugin was not initialized
            13 297588 log INITIALIZATION ERROR -> Problem setting up in-app billing: IabResult: Error checking for billing v3 support. (response: 3:Billing Unavailable)

            I have read all comments here, and i have testet your Github “v3”, too with same result. How can i setup this plugin?

  • James

    Hi Nic,

    Nice tutorial.

    I would like to implement your code into my project, however before I do so I was wondering how can I display premium content only when the user has purchased to unlock them?

    Free user unlocked premium content –> app displays the premium content to that user.

    What would be the simplest way to do so?

    Thanks in advance Nic:)

    James.

    • Well you can either bundle your premium content within your app and use an if/then to determine if you’ve purchased or you can store the premium content remotely and only download it when it has been purchased.

      Best,

  • Shri Kant Kaushik

    I am getting the error Authentication required. Please help me!!!!

    • That isn’t enough information for me to help you with. What are you trying to do? What Android version are you using? Is this a device or simulator? The more you give me the more I can help.

      Best,

      • Shri Kant Kaushik

        I am trying to add inapp purchase for my app. I am using device with 4.4 android version. ProductId should be present in in app product in my Google developer account and I am using that I’d.

      • I’m testing the plugin cordova-plugin-purchase and I have the same issue with the authentication 🙁
        PD: I’m debugging in debug mode using ionic run android and GapDebug.

        Any idea Nic? 🙂

        • Alexey Rubinchyk

          Same error

  • siddharth

    Have you provide any tutorial on android pay and apple pay integration ..i am new and want to know how to implement it in ionic