Android in-app Purchases

Introduction:

At some point, we need to earn revenue through our application. We can monetize our application for removing ads, selling physical goods, providing some enhanced functionality to users. We can follow different monetization strategies that depend upon our application.

Using Google Play Billing:

 According to android documentations-

You can use Google Play’s billing system to sell the following types of digital content:

  • One-time products: A one-time product is a content that users can purchase with a single, non-recurring charge to the user’s form of payment.
    One-time products can be either consumable or non-consumable.
  • Subscriptions: A subscription is a product that provides access to content on a recurring basis. Subscriptions renew automatically until they’re cancelled. Examples of subscriptions include access to online magazines and music streaming services.

Note: Here we will discuss One-time products.

 Using Google Play Billing in-app:

1-Add the Google Play Billing Library dependency to your app’s build.gradle file.

dependencies {

 implementation 'com.android.billingclient:billing:3.0.0'

}

And add these permission in the manifest file

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

2- In order to test or implement InApp Purchase / Subscription, we need a developer account and our app needs to be published either in alpha/beta/production level.

3-Now create a product or a subscription.   

We need to create the products which will be available for purchases on Google Play Console. We need to add Product ID, Title, and Subscription. Product ID should be unique for every product to be purchased.

4- Create an Activity and its layout file.

i-    XML file–

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical">


    <include

        android:id="@+id/toolbar"

        layout="@layout/toolbar" />


            <androidx.appcompat.widget.AppCompatButton

                android:id="@+id/proceedBtn"

                style="@style/Btn"

                android:layout_width="@dimen/button_width"

                android:layout_height="@dimen/buttom_height"

                android:layout_gravity="center"

                android:layout_marginTop="@dimen/xlarge_margin"

                android:layout_marginBottom="@dimen/xlarge_margin"

                android:background="@drawable/dark_button_selector"

                android:text="@string/proceed" />  


</LinearLayout>

ii- Activity file and steps

import android.os.Bundle;

import android.view.MenuItem;

import android.view.View;

import androidx.annotation.NonNull;

import androidx.annotation.Nullable;

import androidx.appcompat.widget.AppCompatButton;

import com.android.billingclient.api.BillingClient;

import com.android.billingclient.api.BillingClientStateListener;

import com.android.billingclient.api.BillingFlowParams;

import com.android.billingclient.api.BillingResult;

import com.android.billingclient.api.ConsumeParams;

import com.android.billingclient.api.ConsumeResponseListener;

import com.android.billingclient.api.Purchase;

import com.android.billingclient.api.PurchasesUpdatedListener;

import com.android.billingclient.api.SkuDetails;

import com.android.billingclient.api.SkuDetailsParams;

import com.android.billingclient.api.SkuDetailsResponseListener;

import com.britishcouncil.ieltsprep.R;

import com.britishcouncil.ieltsprep.util.UiUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

import java.util.List;

public class tPurchaseActivity extends BaseActivity implements PurchasesUpdatedListener, ConsumeResponseListener, View.OnClickListener {

   private BillingClient mBillingClient;

   private List<String> skusList;

   private String skuId = "product_1";

   private Purchase purchaseDetails;


   @Override

   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_test_purchase);

       iniTView();

       skusList = new ArrayList<>();

       skusList.add(skuId);

       // setting billing client for app in purchases

       setUpBillingClient();


   }


   private void iniTView() {

       AppCompatButton proceedBtn = findViewById(R.id.proceedBtn);

       proceedBtn.setOnClickListener(this);

   }


   /// 1- we setup the billing client

   private void setUpBillingClient() {

       mBillingClient = BillingClient.newBuilder(this).enablePendingPurchases().setListener(this).build();

       // 2- start the connection with Google Play

       mBillingClient.startConnection(new BillingClientStateListener() {

           @Override

           public void onBillingSetupFinished(@NotNull BillingResult billingResult) {

               /// client is ready do something

               // The BillingClient is ready. You can query purchases here.

           }

           @Override

           public void onBillingServiceDisconnected() {

               UiUtil.showToast("onBillingServiceDisconnected");

           }

       });

   }


   // 3 -  Here we can query and Show products available to buy

   // 4-   Here we can handle the different errors if any occurs.

   // Here Sku string is same as product id we have added on  Google Play Condole.

   public void prepSKUSDetails(List<String> skusList, final String skuId) {

       SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();

       params.setSkusList(skusList)

               .setType(BillingClient.SkuType.INAPP);

       mBillingClient.querySkuDetailsAsync(params.build(), new SkuDetailsResponseListener() {

           @Override

           public void onSkuDetailsResponse(@NotNull BillingResult billingResult, List<SkuDetails> skuDetailsList) {

               if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && skuDetailsList != null) {

                   for (SkuDetails skuDetails : skuDetailsList) {

                       String skuName = skuDetails.getSku();

                       if (skuName.equalsIgnoreCase(skuId)) {

                           BillingFlowParams flowParams = BillingFlowParams.newBuilder()

                                   .setSkuDetails(skuDetails)

                                   .build();

                           mBillingClient.launchBillingFlow(TestPurchaseActivity.this, flowParams);

                       }

                   }

               } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED) {

                   UiUtil.showToast("FEATURE_NOT_SUPPORTED");

               } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.SERVICE_DISCONNECTED) {

                   UiUtil.showToast("SERVICE_DISCONNECTED");

               } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE) {

                   UiUtil.showToast("BILLING_UNAVAILABLE");

               } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.ITEM_UNAVAILABLE) {

                   UiUtil.showToast("SERVICE_UNAVAILABLE");

               } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.SERVICE_TIMEOUT) {

                   UiUtil.showToast("SERVICE_TIMEOUT");

               } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.DEVELOPER_ERROR) {

                   UiUtil.showToast("DEVELOPER_ERROR");


               }

           }

       });

   }

   // 5-- we get the purchase update here, we process the purchases data according to our need.

   @Override

   public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<Purchase> purchasesList) {

       if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK

               && purchasesList != null) {

           for (Purchase purchase : purchasesList) {

               handlePurchase(purchase);

           }

       } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED) {

           // Handle an error caused by a user cancelling the purchase flow.

           UiUtil.showToast("cancelled");

       } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED && purchasesList != null) {

           for (Purchase purchase : purchasesList) {

               if (purchase.getSku().equals(skuId)) {

                   purchaseDetails = purchase;

                   ConsumeParams consumeParams =

                           ConsumeParams.newBuilder()

                                   .setPurchaseToken(purchase.getPurchaseToken())

                                   .build();

                   mBillingClient.consumeAsync(consumeParams, this);

               }

           }

       }

   }

   void handlePurchase(Purchase purchase) {

       if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {

           // Grant entitlement to the user.

           if (purchase.getSku().equalsIgnoreCase(skuId)) {

               purchaseDetails = purchase;

               // Acknowledge the purchase if it hasn't already been acknowledged.

               ConsumeParams consumeParams =

                       ConsumeParams.newBuilder()

                               .setPurchaseToken(purchase.getPurchaseToken())

                               .build();

               mBillingClient.consumeAsync(consumeParams, this);

           }

       }

   }

   @Override

   public void onConsumeResponse(@NonNull BillingResult billingResult, @NonNull String s) {

       if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {

                         // here we can save the purchases data to our usel̥

       }

   }


   @Override

   public boolean onOptionsItemSelected(MenuItem item) {

       if (item.getItemId() == android.R.id.home) {

           finish();

       }

       return super.onOptionsItemSelected(item);

   }

   @Override

   public void onClick(View view) {

       switch (view.getId()) {

           case R.id.proceedBtn:

               // query item you want to PURCHASE

               prepSKUSDetails(skusList, skuId);

       }

   }


}

 

Leave a Reply