How to Implement Android In App Purchases

In app purchase is one of the main monetization options for Android apps. Android in app purchase combines what used to be the “free” version and “paid” version together. With in app purchase or IAP you no longer need to have a free version of your app that users try before deciding if they should purchase your paid version, rather you deploy one app and purposeful reserve the “premium value” to be only available to paid users while letting users get a taste of the app before making a purchase decision.
Google provides the technology and the execution of IAP transactions, you the developer decides what this premium value is and more importantly at what point do you require the purchase of this premium value before continuing to use your app.

If we liken your app to an event, then you the developer decides where to place the entrance gate to the enjoyment of your app. Google sells the tickets, process the payment for the ticket, issues receipt of payment to the user, and notifies you that the user has paid.

It is your duty to programatically let the user in, and provide the premium value as advertised. At your discretion you can decide that after a certain period or after performing certain number of actions, the ticket that Google issued the user will expire requiring that the user will be sent back again to that entrance gate to purchase more ticket. When this happens it is referred to as “consume” that means the user has used the product that they purchase from you and so they are allowed to purchase it again, without consuming the product that they purchased from you, the Play Store will not allow the user to re-purchase the same product again.

Before proceeding to learn how to implement android in app purchase it is important that you understand the distinction that I just made which is that it is your responsibility to design your app, such that there is only one way to access the premium features of your app, enabling you to restrict that access to only paying users – the in app purchase technology will not do this for you.

Key terms and concepts in Android In App purchase

  1. Digital Product – this is the digital feature or access that you are selling. This must be a non ship-able product. You must create a digital product before you can enable in app purchase for your app.
  2. In-app billing – this is the Google technology that enables you to sell your digital product as one time purchase or subscription. You must add this library to your app
  3. Google Play server – this is where the purchase transaction is executed, users must have internet connection at the time of purchase
  4. Google Play app – this acts as the intermediary between your app and the Play Server, users must have Google Play installed on their device before they can buy any other Android app from the Play Store
  5. AIDL File = this defines the interface and the methods that you can invoke from your app against the in-app billing service, you need to add this file to your app
  6. TrivialDrive – the Android team was not content on just providing extensive documentation around in app purchases, they went a step further and provided sample app that includes convenience classes that you can just copy from to setup your in app purchases.

Steps to Add Android In App purchases

Step 1: Merchant Account – per Google “you must have a Google payments merchant account to create a product list” and if you do not have one, then create one through the developer console and while you are at it you may want to setup tax information. You never know, you might make a sale! and Google will not remit your $0.99 unless you setup tax information.

Step 2: Upload apk file – you need to add a signed apk of your app to the developer console before you are allowed to create digital products. Do not worry you can add your apk file even if your app is a long way from being completed. You are not publishing it, you just have to upload a signed apk.

Step 3: Create digital product – now that you have added a signed apk file to the developer console, you can create digital products. And you create this from the In-app Products tab in the developer console, select Add new Products and then enter a Product ID such as “premium”, “unlimited_version”. Your users will not see this id, select Managed Product and click ok. You will now be able to enter title and product description which will be visible to users.

Step 4: Obtain your license key – every Android app created in the developer console has a license key, it is located in the Services & APIs tab, copy yours and save in a safe location. Google advises against hard coding this licence key string to your app, the steps to apply this security recommendation is outside the scope of this post.

Step 5: Add In-app billing service – The In-app billing service is added via a file named IInAppBillingService.aidl and to add this file you do the following:

  1. Open the SDK Manager
  2. Expand the extras section
  3. Install Google Play Billing Library
  4. Open the folder “location of Android SDK/extras/google/play_billing
  5. In another window open the folder “root of your Android Studio Project/app/src/main and in this folder create another folder called “aidl”
  6. Go back to Android Studio select the directory “aidl” you just created and create a new package called “”
  7. From the folder “play_billing” you opened above, copy and paste the file IInAppBillingService.aidl to the package you just created.

Step 6: Add permission – in your application manifest, add the following permission

<span class="tag">&lt;uses-permission</span> <span class="atn">android:name</span><span class="pun">=</span><span class="atv">""</span> <span class="tag">/&gt;</span>

Step 7: Add helper classes – Most of the code to implement Android in app purchase has already been done and provided to us in a sample project called TrivialDrive and is located at “root of your Android Studio SDK/extras/google/play_billing/sample/trivialdrive. We need to add some of the helper classes provided in this sample project to our own project.

  1. In the root of your app, create package called “Billing” or something similar
  2. Open the folder “root of your Android Studio
  3. SDK”/extras/google/play_billing/samples/TrivialDrive/src/com/example/android/trivialdrivesample/util
  4. Copy each file from this folder and paste into the “Billing” package you created above
  5. If there is a red warning in, you can just comment out the offending comment line
  6. Rebuild the project

Have you decided where to put the Paywall? At this point, your app is ready to start issuing admission tickets (sort of), however if your app is not structured to segregate ticket holders from non ticket holders, IAP will not do that for you!

Step 8: Create ServiceConnection – Next you want to initiate a connection from your app to Google Play server, this need to happen each time your app starts so we will place the code for in app purchase initialization at the onCreate method of your Activity. The logic for this step is already implemented for you in one of the helper classes you copied from the TrivialDrive sample app. Please note that at this point your app can no longer be tested with an emulator because it does not have Google Play installed, you will need physical device to test your app going forward or you will have to comment out the following line out before running in an emulator again.

IabHelper mHelper;

public void onCreate(Bundle savedInstanceState) {
   //this is variable referring to the license key string you got from the developerconsole
   String base64EncodedPublicKey; 

   // compute your public key and store it in base64EncodedPublicKey
   mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
   public void onIabSetupFinished(IabResult result) {
      if (!result.isSuccess()) {
         // Oh noes, there was a problem.
         Log.d(TAG, "Problem setting up In-app Billing: " + result);
         // Hooray, IAB is fully set up!

Step 9: Ask to be paid – in other to actually make money from your app with IAP you have to ask to be paid. Hopefully you have determined the value you want to offer to paying users of your app, and you have decided at what point to ask them to pay. For example if you have a camera app that provides awesome editing features for users. Your business rule could be that users are only allowed to edit 20 photos for free to try out the app and after that they will be prompted to purchase the “Unlimited Version” of the app. You can implement this business rule like so:

  1. Restrict the image edit features to be only called from one button, we can refer to this button as mEditButton mEditButton = (Button)findViewById(; ,
  2. Create a boolean called isPremium to determine the status of the user public boolean mIsPremium = false;
  3. We then have an int counter that keeps tracks of how many photos they edit, we only want to track photos that have been successfully edited. For this we attach a listener to another button we will call the Save button and increment the counter only if they apply save, this way if they abandon their edit without saving it will not be counted against them. We will implement this counter in the SharedPreference like this:
    mSaveButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    int counter = mPref.getInt(COUNTER, 0);
                    mEditor.putInt(COUNTER, counter + 1);
  4. Each time the user touches the mEditButton, we check if the user isPremium, if isPremium, we let them continue to edit, if is not Premium then we count how many photos they have edited, if it is less than 20 we will let them edit the image, else we show them a dialog to upgrade to unlimited version. If they cancel the dialog, we quit – no love lost. If they say yes we take them to the market place to get paid.
mEditButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!mIsPremium){
                    //non premium user check if limit has exceeded
                    //get the number of completed edits
                    int counter = mPref.getInt(COUNTER, 0);

                    if (counter > 20){

private void promptForUpgrade() {
    AlertDialog.Builder upgradeAlert = new AlertDialog.Builder(this);
    upgradeAlert.setMessage("Do you want to upgrade to unlimited version?");
    upgradeAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            //set progress dialog and start the in app purchase process
            upgradeDialog =, "Please wait", "Upgrade transaction in process", true);

              /* TODO: for security, generate your payload here for verification. See the comments on
     *        verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use
     *        an empty string, but on a production app you should carefully generate this. */
            String payload = "";

            mHelper.launchPurchaseFlow(mActivity, SKU_UNLIMITED_VERSION, RC_REQUEST,
                    mPurchaseFinishedListener, payload);
    }).setPositiveButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

5. When they return from the market place we check if they made a purchase, if they did we will let them to continue to edit as many photo as their heart desire. by setting their status as Premium so they are not prompted for purchase again.

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
            = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, Purchase purchase)
            // if we were disposed of in the meantime, quit.
            if (mHelper == null) return;

            if (result.isFailure()) {
                alert("Error purchasing: " + result);

            else if (purchase.getSku().equals(SKU_UNLIMITED_VERSION)) {
                alert("Thank you for upgrade");
                mIsPremium = true;

That is it, this covers the basics of implementing Android in app purchase. There are some problems with the configuration of the opt-in shortcode

Source Code
You can find the Source Code for this Tutorial @ Github


About the Author valokafor

I am a Software Engineer with expertise in Android Development. I am available for Android development projects.

follow me on:

Leave a Comment: