70 ratings
  • 1
  • 2
  • 3
  • 4
  • 5
5 star 12
4 star 7
3 star 21
2 star 10
1 star 20
Compatible with
  • Android

Xamarin.InAppBilling 2.2

Xamarin, Inc.

Component to assist in adding In-App Billing to a Xamarin.Android application via Google Play Services.

About Xamarin.InAppBilling

In-app Billing is a Google Play service that lets you sell a wide range digital content such as new game levels, downloadable media, or premium features directly from inside your Xamarin.Android mobile application. These purchases can either be standard, one-time billed products or recurring, automatically billed subscriptions.

The Xamarin.InAppBilling component simplifies the process of supporting In-App Billing (Version 3 API) by reducing the amount of common, repetitive code required and by adding several useful, helper functions.

Features

Xamarin.InAppBilling supports the following features:

  • Connect - Attaches your Xamarin.Android app to Google Play to process In-App Billing transactions.
  • QueryInventoryAsync - Given a list of Product IDs, this routine will return all available, active products matching those IDs not already purchased by the current user.
  • GetPurchases - Returns a list of all purchases made by the current user.
  • BuyProduct - Calls Google Play to purchase the given product.
  • ConsumePurchase - Given a purchased product, this routine informs Google Play that the given product has been consumed and is available for purchase again.
  • Disconnect - Unbinds from Google Play when your Activity ends.

Events

Xamarin.InAppBilling defines the following events that you can monitor and respond to:

  • OnConnected - Raised when the component attaches to Google Play.
  • OnDisconnected - Raised when the component detaches from Google Play.
  • OnInAppBillingError - Raised when an error occurs inside the component.
  • OnProductPurchasedError - Raised when there is an error purchasing a product or subscription.
  • OnProductPurchased - Raised when a product or subscription is fully processed by Google Play and returned.
  • OnPurchaseConsumedError - Raised when there is an error consuming a purchase.
  • OnPurchaseConsumed - Raised when a purchase is successfully consumed.
  • OnPurchaseFailedValidation - Raised when a previous purchase fails validation.
  • OnGetProductsError - Raised when a request to GetProducts fails.
  • OnInvalidOwnedItemsBundleReturned - Raised when an invalid bundle of purchases is returned from Google Play.
  • InAppBillingProcessingError - Raised when any other type of processing issue not covered by an existing event occurs.
  • OnUserCanceled - Raised when a user cancels an In App Billing request.
  • QueryInventoryError - Raised if there is an error querying Google Play Services for available inventory.
  • BuyProductError - Raised if there is an error buying a product from Google Play Services.

Secure Transactions

When developing Xamarin.Android applications that support In-App Billing there are several steps that should be taken to protect your app from being hacked by a malicious user and keep unlocked content safe.

While the best practice is to perform signature verification on a remote server and not on a device, this might not always be possible. Another technique is to obfuscate your Google Play public key and never store the assembled key in memory.

Xamarin.InAppBilling provides a quick and simple method to break your public key into a several pieces and to obfuscate those pieces. Once a public key has been provided to Xamarin.InAppBilling it is never stored as plain text, it is always encrypted in memory.

Required Setup and Limitations

While using the Xamarin.InAppBilling component greatly simplifies the amount of code required to use In-App Billing in your Xamarin.Android mobile application, the component still uses the Google Play In-App Billing (Version 3 API) to perform In-App Billing tasks and as such, has the same limitations and setup requirements as using the In-App Billing (Version 3 API) directly in your app.

To properly use the Xamarin.InAppBilling component, please follow all of the setup and testing instructions in the Getting Started document included with the component.

Android Examples

And here is a simplified example of adding In-App Billing to an Android Activity using Xamarin.InAppBilling:

using Xamarin.InAppBilling;
using Xamarin.InAppBilling.Utilities;
...

// Create a new connection to the Google Play Service
_serviceConnection = new InAppBillingServiceConnection (this, "<public-key>");
_serviceConnection.OnConnected += () => {

    // Load inventory or available products
    GetInventory();

    // Load any items already purchased
    LoadPurchasedItems();
};

// Attempt to connect to the service
_serviceConnection.Connect ();
...

private async Task GetInventory () {
    // Ask the open connection's billing handler to return a list of available products for the 
    // given list of items.
    // NOTE: We are asking for the Reserved Test Product IDs that allow you to test In-App
    // Billing without actually making a purchase.
    _products = await _serviceConnection.BillingHandler.QueryInventoryAsync (new List<string>   {
        ReservedTestProductIDs.Purchased,
        ReservedTestProductIDs.Canceled,
        ReservedTestProductIDs.Refunded,
        ReservedTestProductIDs.Unavailable
    }, ItemType.Product);

    // Were any products returned?
    if (_products == null) {
        // No, abort
        return;
    }
    ...
}
...

private void LoadPurchasedItems () {
    // Ask the open connection's billing handler to get any purchases
    var purchases = _serviceConnection.BillingHandler.GetPurchases (ItemType.Product);

    // Display any existing purchases
    ...
}
...

// Configure buy button
_buyButton.Click += (sender, e) => {
    // Ask the open connection's billing handler to purchase the selected product
    _serviceConnection.BillingHandler.BuyProduct(_selectedProduct);
};

Please see the Getting Started documentation for full instructions on configuring, implementing and testing the Xamarin.InAppBilling component in a Xamarin.Android mobile application. The Getting Started documentation also includes a Troubleshooting section to help diagnose and fix common issues may occur when using the component.

Some screenshots created with PlaceIt.

Release Notes

Version 02.02

The following features and bug fixes have been added to Xamarin.InAppBilling in version 02.02:

  • Google Play In-App Billing API - Upgraded to the latest version of the Google Play In-App Billing API.
  • ServiceUnavailable - Added ServiceUnavailable to the BillingResult enum.
  • Price_Amount_Micros & Price_Currency_Code - Added the new Price_Amount_Micros and Price_Currency_Code fields to the Product class.
  • Testing IAB - Updated the Testing In-App Billing in a Xamarin.Android App section Getting Started documentation to include the new required step of Publishing an Alpha or Beta channel version of the app before In App products can be tested.

Version 02.01

The following features and bug fixes have been added to Xamarin.InAppBilling in version 02.01:

  • purchaseData - Exposed purchase data (Response.InAppPurchaseData) to the OnProductPurchased and OnPurchaseFailedValidation events.
  • purchaseSignature - Exposed purchase signature (Response.InAppDataSignature) to the OnProductPurchased and OnPurchaseFailedValidation events.

Version 02.00

The following features and bug fixes have been added to Xamarin.InAppBilling in version 02.00:

  • In-App Billing v3 - Switched from Google Play Services In-App Billing Version 2 to Version 3.
  • Improved Security - Added protection to ensure that only the official Google Play app can handle billing requests, thus preventing other 3rd party apps from intercepting those requests.
  • OnProductPurchased - Changed the OnProductPurchased event so that it is fired only after a product has successfully been purchased from Google Play Services.
  • OnProductPurchaseCompleted - Removed the OnProductPurchaseCompleted event and replaced it with OnProductPurchased event as a more logical workflow.
  • OnUserCanceled - Added the OnUserCanceled event that is raised when a user cancels an In App Billing request.
  • QueryInventoryError - Added the QueryInventoryError event that is called if there is an error querying Google Play Services for available inventory.
  • BuyProductError - Added the BuyProductError event that is called if there is an error buying a product from Google Play Services.
  • Billing - Switched the Billing class to use constants so it would be easier to use in code without typecasting.
  • BillingResult - Switched the BillingResult class to use constants so it would be easier to use in code without typecasting.
  • ItemType - Switched the ItemType class to use constants so it would be easier to use in code without typecasting.
  • ReservedTestProductIDs - Switched the ReservedTestProductIDs class to use constants so it would be easier to use in code without typecasting.
  • Response - Switched the Response class to use constants so it would be easier to use in code without typecasting.
  • Null Error - Fixed an issue that could result in a null crashing the component on connect if it wasn't able to connect to the Google Play Services In-App Billing API.

Version 01.05

The following features and bug fixes have been added to Xamarin.InAppBilling in version 01.05:

  • GetPurchases - Fixes the situation that could lead to a Null Exception when a call GetPurchases fails to communicate with Google Play Services. GetPurchases will now fail gracefully and return a null.

Version 01.04

The following features and bug fixes have been added to Xamarin.InAppBilling in version 01.04:

  • GetPurchases - Added code to gracefully handle receiving a malformed Owned Items bundle from Google Play Service. GetPurchases will now return a null list and raise the InAppBillingProcessingError event.

Version 01.03

The following features and bug fixes have been added to Xamarin.InAppBilling in version 01.03:

  • Removed Newtonsoft.Json - Switched to a light-weight embedded Json parser and removed dependency on Newtonsoft.Json parser to solve conflicts with other components and projects.
  • HandleActivityResult - Added missing documentation for HandleActivityResult required to fire the OnProductPurchaseCompleted event.
  • InAppBillingProcessingError - Added the InAppBillingProcessingError event that will be raised for any processing error not covered by another error event.

Version 01.02

The following features and bug fixes have been added to Xamarin.InAppBilling in version 01.02:

  • GetPurchases Continuation - Fixes an issue with continuation of a large number of products or subscriptions (greater than 70).
  • Reserved Test Products - Fixed an issue where the reserved test product ID's would not validate using the latest Google Play API.
  • OnGetProductsError - Added the OnGetProductsError event to trap when a request to GetProducts fails.
  • OnInvalidOwnedItemsBundleReturned - Added the OnInvalidOwnedItemsBundleReturned event to trap when an invalid bundle of purchases is returned from Google Play.
  • OnProductPurchased Changed - The OnProductPurchased event is raised when an intent to purchase a product or subscription has been successfully sent to Google Play.
  • OnProductPurchaseCompleted - Added OnProductPurchaseCompleted event that's called once a product or subscription is fully processed by Google Play and returned. NOTE: You should check the state of the response code as this event is raised for both successful and unsuccessful purchases.
  • Documentation - Minor adjustments to the component's documentation.

Version 01.01

The following features and bug fixes have been added to Xamarin.InAppBilling in version 01.01:

  • GetPurchases Error - Fixes an IllegalArgumentException that could be thrown when calling serviceConnection.BillingHandler.GetPurchases method in a production application.
  • OnPurchaseFailedValidation - Added the OnPurchaseFailedValidation event to trap when a previously purchased item fails security validation.
  • Events - Fixes issue when OnProductPurchasedError and OnProductPurchased events could fail to be called correctly.
Write a Review

32 reviews

Tony Andrews rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Version 2.2 is broken on newer versions of Android. The connect call fails due to the problem described here: http://stackoverflow.com/questions/24480069/google-in-app-billing-illegalargumentexception-service-intent-must-be-explicit

Posted on: April 24 / Version: 1.1
Alex Darby rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Works as expected but make sure to call BillingHandler.BuyProduct() on the main Android thread in release build otherwise nothing will be triggered.

Posted on: December 31, 2016 / Version: 2.2
Maksim Ivanov rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Original Google InApp billing library has method getBuyIntentToReplaceSkus() for upgrade/downgrade existing subscription. This component does not have it. Update Plz. It has been 2 years since last update!

Posted on: December 20, 2016 / Version: 2.2
John Hardman rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

I am getting the same exception as Grigory Andrianov reported 18 months ago. It's not a linker settings problem in my case. Otherwise, apart from poor documentation, it seems ok. Would be good to get the component in an up to date NuGet package though.

Posted on: December 15, 2016 / Version: 2.2
Robert Jet rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Method GetPurchases (ItemType.Product) always return null. How can I fix it? Is this component not updated?

Posted on: December 10, 2016 / Version: 2.2
Rafael Saccomani rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

i am trying to use with dependency injection in xf but the Product Purchased not called after the user make the payment, can anyone solve this?

Posted on: November 26, 2016 / Version: 2.2
Bruno Van Thournout

Hi,

We are using this app in our production app that is currently in the store but we keep getting the error that the order could not be processed. This is BLOCKING all of our in app purchases for about 50 000 users, we need this fixed immediatly. I created a post about this: http://stackoverflow.com/questions/40146707/xamarin-inappbilling-android-error-your-order-could-not-be-processed-please-tr

Posted on: October 21, 2016 / Version: 2.2
Graham Smith rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Has been working perfectly for me :)

Posted on: July 29, 2016 / Version: 2.2
Simon Jackson

An official NuGet package would be nice.

Posted on: March 8, 2016 / Version: 2.2
Wojciech Grzesik rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Very badly documented... But at least it works.

QueryInventoryAsync was returning null in release (alpha testing) but after changing linker behavior to skip Xamarin.InAppBilling everything started to work. Had do waste a day to find this solution...

Posted on: January 13, 2016 / Version: 2.2
Sam

The Sample app crashes when making a purchase, does this need an update or something as its vital I get in app billing working and I cant even follow the sample code.

Posted on: November 24, 2015 / Version: 2.2
Platform Team rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

In InAppBillingServiceConnection.OnServiceConnected there is check for inapp billing support like this:

int num = this.Service.IsBillingSupported(3, packageName, "inapp"); if (num != 0) { Logger.Debug("In-app billing version 3 NOT supported for {0}", new object[] { packageName }); this.RaiseOnInAppBillingError(InAppBillingErrorType.BillingNotSupported, string.Format("In-app billing version 3 NOT supported for {0}", packageName)); this.Connected = false; }

Why dont you include the returned status code (num) into log? It would be helpful with debugging "In-app billing version 3 NOT supported" errors - now we have no idea what happened inside.

Posted on: November 4, 2015 / Version: 2.1
Terje Kolderup rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Can anyone help with this error, "Service Intent must be explicit":

http://stackoverflow.com/questions/32631470/xamarin-inappbilling-service-intent-must-be-explicit

Posted on: September 17, 2015 / Version: 2.2
ivanovme rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

I can't find out how to get purchase signature from owned items. Method GetPurchases returns only list of purchases (INAPP_PURCHASE_DATA_LIST). Where i should get a list of purchase signatures (INAPP_DATA_SIGNATURE_LIST)? (names from google docs)

Posted on: May 22, 2015 / Version: 2.2
Gavin Fowler rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

It's doesn't seem to be documented anywhere, and the samples don't reflect this, but you can only QueryInventory 20 products at a time.

Posted on: May 7, 2015 / Version: 2.2
Ricardo Kobayashi rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Its working

Posted on: April 13, 2015 / Version: 2.2
Grigory Andrianov rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

I'm getting an error at serviceConnection.BillingHandler.HandleOnActivityResult when trying to purchase ReservedTestProductIDs.Canceled or ReservedTestProductIDs.Refunded

The error: Error Decoding Returned Packet Information: System.NullReferenceException: Object reference not set to an instance of an object at Xamarin.InAppBilling.InAppBillingHandler.HandleActivityResult (Int32 requestCode, Result resultCode, Android.Content.Intent data) [0x00000] in :0

Call Stack: .Services.InAppPurchasing.IAPServiceAndroid.DisplayMessage (message="Error Decoding Returned Packet Information: System.NullReferenceException: Object reference not set …") in ** .Services.InAppPurchasing.IAPServiceAndroid.OnError (message="Error Decoding Returned Packet Information: System.NullReferenceException: Object reference not set …") in ** Xamarin.InAppBilling.InAppBillingHandler.RaiseInAppBillingProcessingError (message="Error Decoding Returned Packet Information: System.NullReferenceException: Object reference not set …") in Xamarin.InAppBilling.InAppBillingHandler.HandleActivityResult (requestCode=1001, resultCode=Android.App.Result.Ok, data={Intent { (has extras) }}) in .Services.InAppPurchasing.LicensesAndroid.OnActivityResult (requestCode=1001, resultCode=Android.App.Result.Ok, data={Intent { (has extras) }}) in ** .Activity1.OnActivityResult (requestCode=1001, resultCode=Android.App.Result.Ok, data={Intent { (has extras) }}) in ** Android.App.Activity.n_OnActivityResult_IILandroid_content_Intent_ (jnienv=0xffffffffaaf04b68, native__this=0xffffffffffc929ac, requestCode=1001, native_resultCode=-1, native_data=0xffffffffffc929b0) in ***** object.b7be5d57-0411-4d43-90e1-49369cc7242a (arg0=0xffffffffaaf04b68, arg1=0xffffffffffc929ac, arg2=1001, arg3=-1, arg4=0xffffffffffc929b0) in

Everything else works fine, Thanks

Posted on: March 26, 2015 / Version: 2.0
Yaroslav Kihtan rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Crashes in release mode. This is due to the linking settings being set to "Link all assemblies". So now I have to ship release mode with "Link SDK assemblies only".

Add to project file:

<AndroidLinkSkip>Xamarin.InAppBilling</AndroidLinkSkip>

This library does not support "price_amount_micros" and "price_currency_code" - needed for ecommerce analytics purposes for example. Shame the code is not open source.

Totally agreed. There is an ability to get product details manually:

service.Service.GetSkuDetails(...)
Posted on: March 20, 2015 / Version: 2.1
Raymond Kelly rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Crashes in release mode. This is due to the linking settings being set to "Link all assemblies". So now I have to ship release mode with "Link SDK assemblies only".

Posted on: March 3, 2015 / Version: 2.1
jonas laksen

Can anyone help me / make a tutorial on how to implement this in xamarin.forms?

Right now it is not possible to add this package to the forms application, I get the following error: "Could not install package 'xamstore-xamarin.inappbilling 1.5'. You are trying to install this package into a project that targets 'portable-net45+win+wp80+MonoTouch10+MonoAndroid10+xamarinmac20+xamarinios10', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author."

Posted on: February 3, 2015 / Version: 2.1
commader amir

i want using in app billing for another android market like china market etc..

anyone can give a code class?

Posted on: January 8, 2015 / Version: 2.1
Sergio Alonso da Costa Júnior rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Does not work with all devices.

It was a huge pain to touch this component. Use this solution instead: https://github.com/ddebilt/play.billing.v3 And don't use Security.Unify() because it caused consuming to fail.

Posted on: September 18, 2014 / Version: 1.5
urs ammann rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

i use Xamarin.InAppBilling and received a massage from Google Play Support:

We recommend that you migrate your version 2 implementation to version 3 as soon as possible to avoid any disruption to your app monetization for the above apps. For apps in this list that have already been updated, please verify your implementation.

It seems the Xamarin.InAppBilling use something from the Version 2 API?

Posted on: September 13, 2014 / Version: 1.5
Ricardo Akio Kobayashi rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Version 1.05 Ok

Posted on: June 18, 2014 / Version: 1.0
Marco P rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

After several tries and googling I had the component working, but:

1) The most important event, "OnProductPurchaseCompleted" is not called AFTER the purchase has been confirmed, but when the purchase begins, when the user can still cancel the transaction. This way it's totally useless. The only way to have it working properly is by setting "SingleTop" instead of "SingleInstance" on the main activity. This obvisouly should not be a requirement (and anyway there's no documentation about).

2) I would like to know if point n. 3 of Evgeny Loskutov's review can fix the issue I pointed out. If so, it should be clearly stated in the documentation.

Honestly I don't understand why there's not enough effort put on this vital component which is the reason most of us are making apps: get a profit! Willing to change my review if anyone answer.

Posted on: May 29, 2014 / Version: 1.5
Eugene Smykov rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Please, add Fragment support (OnActivityResult not called in fragments)

Posted on: May 12, 2014 / Version: 1.5
Stepan Stepanko rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Still a lot of bugs (v 1.2), please open source code or don't publish this... We can help with debugging

Posted on: April 17, 2014 / Version: 1.2
Evgeny Loskutov rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

All testing was done in 1.1 and 1.2. The quality of the component is surprisingly low and definitely not production ready. Here are the problems I found:

1) OnProductPurchaseCompleted is not raised for products with reserved IDs (com.android.purchased and such). Not sure if it is raised for other products either. 2) The sample application from the component distribution package does not actually use the component. From what I can see it relies on its own implementation of in-app billing. 3) OnProductPurchased event is not named right. It is not raised when product is purchased. It is raised when transaction was initiated. This problem traveled through multiple versions of the component. It should be renamed to something like OnProductPurchaseStarted. 4) Desparate to make OnProductPurchaseCompleted work I was calling BillingHandler.HandleActivityResult in my OnActivityResult. It is not documented. But it crashes somewhere inside BillingHandler code. Despite being undocumented, it should not crash. 5) Why not provide the source code of the component? The implementation should be open as a) it is a critical part of an app; b) there is no intellectual property in something like this whatsoever.

Posted on: April 17, 2014 / Version: 1.2
Android Developer rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

Crashes somewhere inside BillingHandler code, exception "java.io.IOException: DER length more than 4 bytes"

Posted on: April 17, 2014 / Version: 1.3
Jordi Benaiges

I have a problem when reading purchased items, I've explained it in the forum:

http://forums.xamarin.com/discussion/12023/crash-when-using-xamarin-inappbilling#latest

thanks!

Posted on: April 17, 2014 / Version: 1.0
Kenton Pickard rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

DON'T USE 1.0 OF THIS COMPONENT! IT WILL FAIL.

The link posted by Jordi describes the crash you'll get either in production or when doing testing against the Google store with your actual product IDs. The reserved test IDs like com.android.purchased work fine. For most people, the crash will start happening when you think you're almost ready to ship which is quite frustrating for you and your clients.

Also, the documentation listed on this page is misleading at best. Those events that are listed do not do what it says they do. See http://stackoverflow.com/questions/21102119/xamarin-inappbilling-onproductpurchase-onproductpurchasederror-events

Posted on: April 17, 2014 / Version: 1.0
Andrew Vogan rates this with
  • 1
  • 2
  • 3
  • 4
  • 5

A better code example above would be one that worked on the actual app store instead of just a simulation. Unless your IAP's are expensive (most are not), the costs of getting it wrong are higher than the cost of paying Google a few bucks for some real test runs. And I don't think my suggestion is crazy either, given the other reviews here and the snafu that apparently happened with this component.

Note: I do appreciate the free component, though, and will modify my review when it's fixed. Good luck debugging and thanks again to Xamarin.

Posted on: April 17, 2014 / Version: 1.0