Detailed Steps to Add In App Purchase Android?

In App purchase is an amazing way to earn great amount of bucks from your Android app. IAP is mostly used to unlock the great additional features inside your app that you want to monetise from. Monetisation in an application is one of the most important aspects of distributing the required product to the rest of the Globe. Like it or not, Google charges 30% of their fees on each successful transaction that your application will make.

Monetization is basically done to catch a widespread impact on your product across the Globe.

Android, being so much widespread and very common these days, it provides amazing features for users to purchase various products from their app and this is what is termed as In App Purchase. From this set of Application Programming Interfaces, developers can offer two types of products:

  • Managed In App products. These products are generally managed by the developer or the host of the application, and they are further branched into two types, consumable and non-consumable. A consumable product is usually on a long run and, once consumed, can be bought again, whereas the other one is a onetime benefit that the user will continue having in the app.
  • Subscriptions. These products comes basically with a validity period or a time duration like days, months, years and they are automatically renewed at the end of each billing cycle. As soon as the Subscription expires, the product is no longer available to the customer.
In App Purchase Android
In App Purchase Android

Your application makes the In App Purchase service using an API which is basically the Application Programming Interface used to fetch the required data that is exposed by the Google Play app and is installed on the device. The Google Play app then sends billing requests, responses and communicate between your application and the server. Your application sends billing or a purchase requests to the Google Play app over Inter Process communication which is basically called as IPC and receives responses from the Google Play app Server. Your application need not manage any network connections between your server and the Google Play server.

Android Mobile Applications
Android Mobile Applications

*You must have a Google payments merchandise account to use the In App Purchase service.

The In App Purchase API provides the following features:

  • Your app makes number of requests through a Various APIs that allows users to fetch the details of various products and their billing details. The API quickly provides products based on the user’s ownership and experience.
  • This API propagates the required order info to the device of the user on every successful purchase. The process goes on synchronously.
  • All purchases are managed by Google Play Servers. The user can’t own different copies of a same In App Purchase product.
  • But the Purchased products that are consumed gets a tag of unowned and when required the user can purchase that product again from Google Play store, as that product is now set of unowned.
  • The API provides support for the users, purchases and subscriptions.

In App products are basically the products that the owner of a App makes for sale to its users from inside his application. There are numerous examples of In App products include game currencies, upgrades that basically enhance or increase the user experience, and obviously new fresh content for the application. In-app Billing is used to sell only digital products. But yes, you define your products using the Google Play Console.

The Google Play Console is where you set or publish your In App Purchase application and manage the various products that are available for categorized purchases from your application. You can also set a product list of all your In App products that are linked with your application, they can be of one time purchase or can even be a continuous subscription, it all depends on you. You can define information for each product such as the following:

  • Product Type.
  • Unique product ID or SKU
  • Price.
  • Product Description.
  • Google Play handling
  • Tracking of purchases.
  • Subscription time or period, and even more..

What is the In App Purchase flow?

To make a purchase, your application needs a billing request for a required In App Purchase product. Google Play then handles everything from all of the checkouts transaction details, to validating the mode of payment and obviously the financial transaction.

Then, Google Play sends your application about the purchase details, like the order Id, date and time, and the amount paid. Your application don’t need to handle anything related to the transaction all the required tasks related to transaction are handled by Google Play Servers.

Google Play Console
Google Play Console

Play Billing Library can be used to handle all the development related tasks. This library works as an Interface on top of the Android Definition Language file that interacts with the In App Purchase API. Play Billing app is Basically used to focus on the development part, such as listing various products, displaying required product details, or showing the purchase flows. The Play Billing Library provides a very easier way to use an alternative for developing with the Android Interface Definition Language.

Below are the steps:-

  1. Add the Play Billing Library to your app.
  2. Configuring all your products in the Google Play Console.
  3. Testing the In App Purchase products.

Merchant account and In App purchase products

Test your android app for In App purchase :-

Log into your Google Play Developer Console and now you need to add In app purchase products

Go to the > Store presence > In App products menu.

Click on the Add new product button. Now, add the title and description of your product. Set your price and yes now you are done. Make sure you click on the Inactive button and activate the required product.

Create android application

Go and update the AndroidManifest.xml file by adding the following user permissions code.

<uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="android.permission.INTERNET" />

Now you need to add an aidl file to your project.

IInAppBillingService.aidl is an Android Interface Definition Language (AIDL) file that provides an interface to the in-app Purchasing service. You can use this interface to make purchasing requests by requesting IPC route calls.

You can find the IInAppBillingService.aidl file in the Trivial Drive sample app. To add an In App Purchase library to your project, follow these instructions:

In Android Studio, import the IInAppBillingService.aidl file to your project as described in the following steps:


Now, Create a guide called aidl under src / main. To create an aidl directory, right-click on the application node in the project tools window, selecting the new menu option -> Folder -> for AIDL. Within the Project toolbar the Aidl folder should now be listed.


Install the new package com.android.vending.billing in this directory. Right-click on the aid folder and select New -> Item Menu Package. In the dialog that appears, enter com.android.vending.billing in the text field and click OK.
Import the IInAppBillingService file.aidl to this package.


Build your app. You should see a file named IInAppBillingService.java in the gen / directory of your project.
Include help classes from the Trivial Drive sample util / directory file in your project. Remember to change the package name in those files correctly so that your project can be successfully integrated.
You need to start by adding the following dependencies to your gradle building file.

<compile 'com.android.billingclient:billing:1.0' />

The Play Billing Library offers the function of repurchasing any previously purchased items. This can be done using the consumeAsync () method and as parameters, this method takes the purchase token and the example of the ConsumeResponseListener section as a re-use result.

ABHelper is just a help section, which provides an interface and gives you an example of how to use IInAppBillingService. InAppBillingService is part of the in-app billing API. Used to buy and test their condition.

Here is an example of an app purchase function in question and use flow.

public class PurchaseActivity extends AppCompatActivity {
    Activity activity = PurchaseActivity.this;
    private String TAG = Constants.TAG;
    @BindView(R.id.rvItems) RecyclerView rvItems;
    @BindView(R.id.llLoader) LinearLayout llLoader;
    @BindView(R.id.llEmptyList) LinearLayout llEmptyList;
    @BindView(R.id.llNoInternet) LinearLayout llNoInternet;
    @BindView(R.id.btnContinue) Button btnContinue;
    LinearLayoutManager lm;
    ItemAdapter adapter;
    List<String> additionalSkuList = Arrays.asList("1", "2", "3");
    int RC_REQUEST = 10001;

    IabHelper mHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_purchase);

        ButterKnife.bind(this);

        String base64EncodedPublicKey = "_BASE64_KEY_";

        mHelper = new IabHelper(this, base64EncodedPublicKey);

        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            public void onIabSetupFinished(IabResult result) {
                if (!result.isSuccess()) {
                    Toast.makeText(activity, "Problem setting up In-app Billing: " + result, Toast.LENGTH_SHORT).show();
                } else {
                    loadProducts();
                }
            }
        });
    }

    private void loadProducts() {
        try {
            mHelper.queryInventoryAsync(true, additionalSkuList, null, new IabHelper.QueryInventoryFinishedListener() {
                @Override
                public void onQueryInventoryFinished(IabResult result, Inventory inv) {
                    List<PurchaseItem> items = new ArrayList<>();
                    PurchaseItem item;

                    for (String s : additionalSkuList) {
                        item = new PurchaseItem();
                        item.setTitle(inv.getSkuDetails(s).getTitle());
                        item.setDescription(inv.getSkuDetails(s).getDescription());
                        item.setPrice(inv.getSkuDetails(s).getPrice());
                        item.setId(inv.getSkuDetails(s).getSku());
                        items.add(item);
                    }

                    llLoader.setVisibility(View.GONE);

                    if (items.isEmpty()) {
                        rvItems.setVisibility(View.GONE);
                        llEmptyList.setVisibility(View.VISIBLE);
                    } else {
                        llEmptyList.setVisibility(View.GONE);
                        rvItems.setVisibility(View.VISIBLE);

                        lm = new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false);
                        rvItems.setLayoutManager(lm);

                        adapter = new ItemAdapter(activity, items);
                        rvItems.setAdapter(adapter);
                    }
                }
            });
        } catch (IabHelper.IabAsyncInProgressException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHelper != null) try {
            mHelper.dispose();
        } catch (IabHelper.IabAsyncInProgressException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        mHelper = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
            // not handled, so handle it ourselves (here's where you'd
            // perform any handling of activity results not related to in-app
            // billing...
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @OnClick(R.id.btnContinue)
    public void clickContinue(View v) {
        PurchaseItem item = adapter.getSelected();

        try {
            mHelper.launchPurchaseFlow(activity, item.getId(), RC_REQUEST, mPurchaseFinishedListener, "");
        } catch (IabHelper.IabAsyncInProgressException e) {
            Log.d(TAG, "onProductClick: " + e.getMessage());
        }
    }

    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        @Override
        public void onIabPurchaseFinished(IabResult result, me.proft.sandbox.utils.billing.Purchase purchase) {
            Log.d(TAG, "Purchase finished: " + result + ", purchase: " + purchase);

            // if we were disposed of in the meantime, quit.
            if (mHelper == null) return;

            if (result.isFailure()) {
                Toast.makeText(activity, "Error purchasing: " + result, Toast.LENGTH_SHORT).show();
                return;
            }

            Log.d(TAG, "Purchase successful." + purchase);

            try {
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            } catch (IabHelper.IabAsyncInProgressException e) {
                e.printStackTrace();
            }
        }
    };

    IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
        @Override
        public void onConsumeFinished(me.proft.sandbox.utils.billing.Purchase purchase, IabResult result) {
            Log.d(TAG, "Consumption finished. Purchase: " + purchase + ", result: " + result);

            // if we were disposed of in the meantime, quit.
            if (mHelper == null) return;

            if (result.isSuccess()) {
                Log.d(TAG, "Consumption successful. Provisioning." + purchase.getSku());
            } else {
                Log.d(TAG, "Error while consuming: " + result);
            }
            Log.d(TAG, "End consumption flow.");
        }
    };
}

You can get Base64-encoded RSA public key in Google Play Console * -> APP -> Development tools -> Services & APIs*.

Compile and run the application on a physical Android device with Google Play support and click on the “Continue” button. This should cause the Google Play purchase dialog to appear listing the test item.

Read related Blogs

1 thought on “Detailed Steps to Add In App Purchase Android?”

Leave a Reply

Your email address will not be published. Required fields are marked *