As we all are aware of purchasing an application from the Play Store and purchasing a virtual item for the application from the play store. Nowadays there is a trend of having Pro versions of the application and for that, we have to purchase the application from the play store we have to subscribe for the application after installing.
From a developer’s perspective, one needs to implement this feature in the application at the time of development of the application. So there are multiple ways for implementing this feature in Android applications. In the near past, Android Developers used third-party libraries to implement In-App purchases in their applications. But, Google wants the developer to say “Tata Bye Bye” to third-party libraries of In-App purchase by Introducing the all-new “Google Play Billing Library”. So let’s dive into the new library so you also can say Goodbye to a third-party library.
In this blog, I will explain how you can integrate and use the new “Google Play Billing Library” in your Android applications. We will discuss the topic on the basis of the following key points.
So it’s enough with the overview. Now Fasten your Seatbelts, we are going to take off with the topic.
To start working with the new library for Play Billing you need to add the following dependency in your application-level build.gradle file:
implementation 'com.android.billingclient:billing:1.0'
Note: You need to check the latest version in google and change the version number accordingly.
Now, we have integrated the Google play billing library into our project. We need to create an object of the BillingClient class. This object can be initialized by using the static newBuilder() method, with passing the reference of the activity we want to use BillingClient with. Then, we can use setListener() method to set the reference of our PurchaseUpdatedListener which is used to receive callbacks when purchases of current users are changed.
mBillingClient = BillingClient
.newBuilder(this)
.setListener(mPurchasesUpdatedListener)
.build();
Now that we have an initialized BillingClient object, we can further move to generate the connection to the in-app API. This request is asynchronous, we will pass an instance of BillingClientStateListener so we will receive a callback based on the status of the API connection.
BillingClientStateListener mBillingClientStateListener = new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(int responseCode) {
}
@Override
public void onBillingServiceDisconnected() {
}
};
mBillingClient.startConnection(mBillingClientStateListener);
When you are successfully connected to the billing service, onBillingSetupFinished() method will be triggered and you can perform all the actions like querying purchases, making purchases, and so on. However, if the connection fails then onBillingServiceDisconnected() will be triggered and you need to handle the retrying scenarios.
When working with the Google Play Billing Library, almost all request returns a response code in the object of Billing Response. There are multiple response codes where each code specifies some different actions. So now let’s discuss available response codes and see what they represent.
There are total 11 response codes which are returned by the Play Billing request. These response codes will be used to handle the error in your application in most of the cases.
1. BILLING_UNAVAILABLE – This response code is returned when the version of the Billing API is not supported for the requested type.
2. DEVELOPER_ERROR – This response code is returned when the developer has passed wrong arguments to the request.
3. ERROR – This response code is returned when there is a general error in executing the request.
4. FEATURE_NOT_SUPPORTED – This is returned when requested action is not supported by the play services on the current device.
5. ITEM_ALREADY_OWNED – This is returned when a user tries to purchase the item they already have purchased before.
6. ITEM_NOT_OWNED – This is returned when a user tries to consume the item which is not already purchased.
7. ITEM_UNAVAILABLE – This response code says that user has tried to purchase an item which is not available for purchase.
8. OK – The most awaited response code is OK. This is returned when the query is successfully executed.
9. SERVICE_DISCONNECTED – Returned when the play service is not connected when the user has tried to execute a query.
10. SERVICE_UNAVAILABLE – This response code represents that there is an error in relation to a device network connection.
11. USER_CANCELED – This response code says that the user has manually canceled the execution of the request.
Now let’s move further in the topic. Sometimes a developer needs to show the list of available items which are available for purchase. Like in some games developer shows a list of Packages available for purchase and user chooses the package to purchase based on their needs. So here we can execute a request for retrieving available items for purchasing.
For that request, we required to send the list of SKUs, and the request will return details with the list of SKU details of each. To execute the query we will use the instance of SkuDetailsParams class. We will create an instance of SkuDetailsParams object by calling newBuilder() method of the class and we will pass the list of SKUs and SKU type (INAPP, SUBSCRIPTION).
Now, after creating and preparing the instance of SkuDetailsParams class, we will execute the request by calling querySkuDetailsAsync() method on BillingClient object which we have created earlier.
SkuDetailsParams mSkuDetailsParams = SkuDetailsParams
.newBuilder()
.setSkusList(mListSkus)
.setType(BillingClient.SkuType.INAPP)
.build();
SkuDetailsResponseListener mSkuDetailsResponseListener = new SkuDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
}
};
mBillingClient.querySkuDetailsAsync(mSkuDetailsParams, mSkuDetailsResponseListener);
Here, in onSkuDetailsResponse() method callback you will get a list of SkuDetails class. And you will get all the details of each item in the SkuDetails class object.
Now, as we have talked about fetching available items which are available for purchase. The same thing applies to the available subscriptions. Sometimes we need to show a list of available subscription packages available for the application.
We can do that in the same way we have fetched available items for purchase by creating and using an instance of SkuDetailsParams class. Just we have to change the type we have passed in generating the object.
In fetching available items we have passed BillingClient.SkuType.INAPP, but in fetching available subscription we need to pass BillingClient.SkuType.SUBS. And the best thing is the same as fetching items.
SkuDetailsParams mSkuDetailsParams = SkuDetailsParams
.newBuilder()
.setSkusList(mListSkus)
.setType(BillingClient.SkuType.SUBS)
.build();
SkuDetailsResponseListener mSkuDetailsResponseListener = new SkuDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
}
};
mBillingClient.querySkuDetailsAsync(mSkuDetailsParams, mSkuDetailsResponseListener);
We have discussed listing all available purchases available in the about section. Now let’s know about how we can query and list purchased items of the current users. Sometimes developers are asked to show which all items are purchased by the user, or they have to list down the number of each item in some games or any other application. We can do this by executing a query.
We can fetch a list of purchased items by calling queryPurchaseHistoryAsync() method. If you are aware of queryPurchases() method then you must be thinking that we can fetch a list of purchased items by executing queryPurchases() method also, but let me the clear difference between these both. The queryPurchases() returns a result from the cached result.
We have to call queryPurchaseHistoryAsync() of the BillingClient instance and we have to pass item type in the request. And we have already discussed item types in the above section. We will pass BillingClient.SkuType.INAPP in request and we will give one instance of PurchasesUpdatedListener which is a listener of the request.
PurchaseHistoryResponseListener mPurchaseHistoryResponseListener = new PurchaseHistoryResponseListener() {
@Override
public void onPurchaseHistoryResponse(int responseCode, List<Purchase> purchasesList) {
}
};
Now we have created an instance of PurchaseHistoryResponseListener interface we will pass this listener along with typing in the queryPurchaseHistoryAsync() to complete the request.
mBillingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP, mPurchaseHistoryResponseListener);
We will have data in the onPurchaseHistoryResponse() of the listener. It will give us a list of Purchases which will contain a list of purchased items by the current user.
In the above section, we have talked about how to fetch the list of purchased items of the current user. Now it’s time to learn about fetching the list of purchased subscriptions of the current user. We will have to call the same function to execute the query to fetch purchased subscriptions.
Fetching the history of subscriptions will work the same as fetching the list of purchased items. We will call the same method queryPurchaseHistoryAsync() of the BillingClient class instance and in the place of the type we are passing, we will pass BillingClient.SkuType.SUBS for subscriptions.
Now, again we will have data in the onPurchaseHistoryResponse() of the listener. It will give the detail of the subscription like order Id of purchase, purchased date of subscription so that you can show pending time in the subscription or in the next payment recurring.
PurchaseHistoryResponseListener mPurchaseHistoryResponseListener = new PurchaseHistoryResponseListener() {
@Override
public void onPurchaseHistoryResponse(int responseCode, List<Purchase> purchasesList) {
}
};
mBillingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.SUBS, mPurchaseHistoryResponseListener);
We have discussed listing available items and subscriptions and listing purchased items and subscriptions. Now it’s time to discuss main the thing about the topic. In this section, we are going to discuss how to purchase the In-App item from the play store. We have done all the things in the above section like showing a list of available purchases, that too with their details like price, description, etc. So now it’s time to select the item and make payment for it.
For purchasing an item, we will use the BillingFlowParams class. We can create an instance of the BillingFlowParams class by calling the newBuilder() method. We need to set the SKU of the item we are going to purchase in the BillingFlowParams class instance by using setSku() method. Along with SKU, we have to set the type of item like BillingClient.SkuType.INAPP in the setType() method.
BillingFlowParams mBillingFlowParams = BillingFlowParams.newBuilder()
.setSku(mStringSku)
.setType(BillingClient.SkuType.INAPP)
.build();
Now we have our mBillingFlowParams object is ready with the required parameters and data. The mBillingFlowParams object is kind of weapon in the war. Now when we have our weapon ready, let’s get ready for the war. We can move further in the process of purchasing the item by using the launchBillingFlow() method to kick off the purchase process.
The first parameter that this method takes is the reference of activity you are launching the flow from, this is required for the callback reason. And another parameter is the object of BillingFlowParams that we have previously generated.
int responseCode = mBillingClient.launchBillingFlow(this, mBillingFlowParams);
That’s it. When we call the above code, a dialog opens with the details of the items you have selected to purchase with the name, description, and price of it. And you will be asked to pay the price with multiple payment options like a debit card, credit card, etc. So you can make payment from there and yeah, your item is purchased successfully.
You must be thinking about the callback of the purchase and where you will get the result when the purchase is successfully done. Keep calm, we will discuss that topic later in this blog.
Aww, aww, I am very impressed by the passion you have for learning. I was feeling that you were thinking about how can I implement purchasing subscriptions while reading the previous topic of purchasing an item. Let’s get a clear idea of this also. Now how we can implement purchasing subscriptions.
This is as simple as purchasing an item. For this, again we will use the BillingFlowParams class object to get the thing done. We can create an instance of the BillingFlowParams class by calling newBuilder() method. We need to set the SKU of the item we are going to purchase in the BillingFlowParams class instance by using setSku() method. Along with SKU, we have to set the type of item like BillingClient.SkuType.SUBS in the setType() method.
BillingFlowParams mBillingFlowParams = BillingFlowParams.newBuilder()
.setSku(mStringSku)
.setType(BillingClient.SkuType.INAPP)
.build();
We have our weapon ready one more time. Let’s dive in the ground and fire the launchBillingFlow() to win the war. We know that launchBillingFlow() takes to arguments in the request. The first parameter that this method takes is the reference of activity you are launching the flow from, this is required for the callback reason. And another parameter is the object of BillingFlowParams that we have generated.
int responseCode = mBillingClient.launchBillingFlow(this, mBillingFlowParams);
That’s it. When we call the above code, a dialog opens with the details of the subscription you have selected to purchase with the name, description, duration of subscription and price of it. And you will be asked to pay the price with multiple payment options like a debit card, credit card, etc. So you can make payment from there and yeah, your subscription is purchased successfully.
We have another feature provided by the Google Play Billing Library which is to Consume the item you have purchased. The library provides this feature for consuming the item which you have purchased in the past. This feature is useful for the items which are tangible such as a petrol tank in the car racing game.
You have purchased 3 petrol tanks at the beginning of the racing and you have to fill the petrol in the car in between racing, then you can consume the petrol tank using this feature.
Quite interesting right? Yeah, now let’s talk about implementing this. We can consume any item by using the consumeAsync() method of the BillingClient class instance. The method consumeAsync() takes two arguments.
The first one is the purchase token of the item, which is returned in the response of the purchasing the item, or you can find the token in the response of fetching the purchased list that we have discussed earlier in this blog.
And another argument is the listener ConsumeResponseListener which will be called when the request is executed. This request returns us two things, one is the response code in the form of Billing Codes (we have discussed in starting of the blog), and the purchase token which you have consumed.
ConsumeResponseListener mConsumeResponseListener = new ConsumeResponseListener() {
@Override
public void onConsumeResponse(int responseCode, String purchaseToken) {
}
};
The method onConsumeResponse() is called when the consumeAsync() method request is executed. Now let’s see how we can call the consumeAsync() method. Again we will use the instance of billing clients.
mBillingClient.consumeAsync(mPurchaseToken, mConsumeResponseListener);
That’s it, your item is successfully consumed.
The topic is like a circle. Now it’s time to join the two ends to complete the circle. I hope you remember the PurchasesUpdatedListener that we have passed while generating the instance of the BillingClient class by using the setListener() method. And I have left you thinking about the response of the purchase items and purchase subscriptions. Here your thinking ends. This is the listener which will be called when you purchase any item or purchase any subscription.
When you purchase any item or subscription the onPurchaseUpdated() of the PurchaseUpdatedListener is called with the data of the item which is updated. This method gets called when your purchases and subscriptions are updated in terms of anything.
PurchasesUpdatedListener mPurchasesUpdatedListener = new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(int responseCode, @Nullable List<Purchase> purchases) {
}
};
So, as we know everything has an end. We have covered all the key points of the topic Google Play Billing Library. We have discussed how to integrate the Google play billing library in the android studio. How to initialize the BillingClient class object. And use this for executing every query of the library. We have discussed listing the available items and available subscriptions. Also, We have listed purchased items and subscriptions. We have purchased items and subscriptions.
I am hoping that now you are able to see the benefits and features that the Google Play Billing Library can bring when it comes to implementing In-App billing into your android application. If you are already using the library or you are planning to try the Google play billing library, I’d love to hear the feedback on my blog or issues you are facing in implementing any feature. Please contact us if any query regarding this article.
Diving deep into SwiftUI This blog post drops us into…
Corporate efficiency and customization are vital in today's fast-paced world,…
Flutter Codemagic CI/CD makes your Flutter app build, test, and…
This website uses cookies.