Click here to Skip to main content
15,886,006 members
Articles / Mobile Apps / Android

How to Implement Android In App Purchases

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
13 Jul 2015CPOL8 min read 36.3K   4   6
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.

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.admission_ticket_resized

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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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 “com.android.vending.billing”
    7. From the folder “play_billing” you opened above, copy and paste the file IInAppBillingService.aidl to the com.android.vending.billing package you just created.
  6. 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">"com.android.vending.BILLING"</span> <span class="tag">/&gt;</span>
  7. 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 SDK”/extras/google/play_billing/samples/TrivialDrive/src/com/example/android/trivialdrivesample/util
    3. Copy each file from this folder and paste into the “Billing” package you created above
    4. If there is a red warning in Base64.java, you can just comment out the offending comment line
    5. Rebuild the project

      Paywall

      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!

  8. 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;
    
    @Override
    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!
       }
    });
  9. 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(R.id.demo_edit_button);
       ,
    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() {
                  @Override
                  public void onClick(View v) {
                      int counter = mPref.getInt(COUNTER, 0);
                      mEditor.putInt(COUNTER, counter + 1);
                      mEditor.apply();
                  }
              });
    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() {
                  @Override
                  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){
                              promptForUpgrade();
                          }
                      }
                  }
              });
      private void promptForUpgrade() {
          AlertDialog.Builder upgradeAlert = new AlertDialog.Builder(this);
          upgradeAlert.setTitle("Upgrade?");
          upgradeAlert.setMessage("Do you want to upgrade to unlimited version?");
          upgradeAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                  //set progress dialog and start the in app purchase process
                  upgradeDialog = ProgressDialog.show(mActivity, "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() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                  dialog.cancel();
              }
          });
          upgradeAlert.show();
      }
    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);
                      upgradeDialog.dismiss();
                  }
      
                  else if (purchase.getSku().equals(SKU_UNLIMITED_VERSION)) {
                      alert("Thank you for upgrade");
                      mIsPremium = true;
                      setUserStatus(true);
                      upgradeDialog.dismiss();
                  }
              }
          };
      private void setUserStatus(boolean status){
          mEditor.putBoolean(IS_PREMIUM_USER, status);
          mEditor.apply();
      }

That is it, this covers the basics of implementing Android in app purchase.

<form action='//valokafor.us4.list-manage.com/subscribe/post?u=0600ce94a59d7720819aa3dd8&id=6e5492cf7d' class='frm' method='post'><input type='text' placeholder='Email Address' name='EMAIL' /><input type='text' placeholder='First Name' name='FNAME' /><input type='hidden' name='b_0600ce94a59d7720819aa3dd8_6e5492cf7d' value='' />
<input type='submit' value="Send Me New Tutorials">
</form>

Follow Me

<script>jQuery(window).load(function() { ThriveApp.load_script('twitter'); });</script>
<script>jQuery(window).load(function() { ThriveApp.load_script('google'); });</script>
<script type='IN/MemberProfile' data-format='inline' data-id='https://www.linkedin.com/in/valokafor'></script>
<script>jQuery(window).load(function() { ThriveApp.load_script('linkedin'); });</script>

Source Code

You can find the Source Code for this Tutorial @ Github

 

The post How to Implement Android In App Purchases appeared first on Val Okafor.

This article was originally posted at http://valokafor.com/android-in-app-purchases

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) ValOkafor.com
United States United States
My name is Val Okafor, I am a Senior Software Engineer with specialization in Android Development. Learning and problem solving is my passion and I share my Android development knowledge through my blog ValOkafor.com.

My Android courses are the courses I wish I had when I started. I teach Android development in the context of a fully developed Android app. I believe that new Android concepts are better understood if they are presented in the context of creating an app from scratch to finish.

I focus on creating Productivity Android apps and besides Android development I have 7 years’ experience as System Administrator supporting Enterprise applications and 2 years’ experience as a Web Developer building websites using PHP and ASP.Net.

I have worked for corporations such as The Home Depot, American Council on Exercise, Legend3D and HD Supply, Inc. I have a bachelor's degree in Information Technology from National University San Diego, California and a master's degree in Software Engineering from Regis University Denver, Colorado.

I enjoy sharing my extensive work experience through my blog, social media.

Comments and Discussions

 
QuestionIn-app BIlling Pin
Member 1146655124-Oct-16 20:29
Member 1146655124-Oct-16 20:29 
QuestionTime Frame Pin
Member 126222906-Jul-16 19:22
Member 126222906-Jul-16 19:22 
QuestionHow to check purchase status? Pin
Sujith S Manjavana11-Jan-16 4:08
Sujith S Manjavana11-Jan-16 4:08 
QuestionHow to proceed for just one paid app? Pin
Shekha Sohel8-Oct-15 22:35
Shekha Sohel8-Oct-15 22:35 
QuestionProblem with HTML tags Pin
Zamrony P. Juhara13-Jul-15 20:05
professionalZamrony P. Juhara13-Jul-15 20:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.