How to Implement In-App Purchases in Android?
Last Updated :
26 Nov, 2021
In this article, we'll look at how to use the billing library to make in-app purchases on Android smartphones. We'll create an app as part of the process to help us learn how In-App purchases work. So, without further ado, let's get started. We'll start by creating an app with an Empty Activity as the first activity, naming it MainActivity, and naming the XML file activity main.xml.
Step by Step Implementation
Step #1
In your app's build.gradle file, add the following line to the dependencies section:
dependencies {
...
implementation 'com.android.billingclient:billing:2.0.1'
}
Step #2
You must also provide the billing permission in the Android manifest:
<uses-permission android:name="com.android.vending.BILLING" />
And now that we've finished setting up the permissions and dependencies, we must begin the implementation process by establishing a connection with Google Play.
Step #3
Two variables will be created in MainActivity.
Kotlin
class MainActivity : AppCompatActivity() {
private lateinit var myBilled: BillingClient
private val courseList = listOf("geeks_for_geeks_android_course", "geeks_for_geeks_dsa_course")
The first variable we've generated is of type BillingClient, which offers the main interface for communication between the library and user application code, and we've also established a list of courseList that defines the list of product IDs we need to buy.
Step #4
We'll now set up the billing client using the onCreate() method.
Kotlin
class MainActivity : AppCompatActivity(), PurchasesUpdatedListener {
override fun onCreate(savedInstanceState: Bundle?) {
..........
doMyBiller()
}
private fun doMyBiller() {
myBiller = MyBiller.newBuilder(this)
.enablePendingPurchases()
.setListener(this)
.build()
myBiller.startConnection(object : MyBillerStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == MyBiller.BillingResponseCode.OK) {
// The MyBiller is setup successfully
}
}
override fun onBillingServiceDisconnected() {
// Do something, like restarting the billing service
}
})
}
Step #5Â
At this point, Let's get our purchase product set up in our game console. To begin, log in to your game console and select CREATE APPLICATION from the menu. Set up your app like you would any other app, including providing information such as the App name, App description, and so on.
Image #1: Creating a new app in the play developer console
Gather all necessary information, such as store listings and ratings, and proceed to the point where you only need to submit the APK or AAB file. After you've completed the aforementioned procedures, we'll need to develop PRODUCTS that we can buy. To accomplish this, when we've finished filling out the above information, we'll need to scroll down to activate it and enter the product's pricing.
Image #2: Setting up in-app purchase
Press Save!
Step #6
When you are done with the amount and payments, the next step is to load the products, do this by:
Kotlin
private fun loadBillers() = if (myBiller.isReady) {
val params = Billers
.newBuilder()
.setSkusList(skuList)
.setType(MyBiller.SkuType.INAPP)
.build()
myBiller.queryLoadBillersAsync(params) { billingResult, loadBillersList ->
// Process the result.
if (billingResult.responseCode == MyBiller.BillingResponseCode.OK && loadBillersList.isNotEmpty()) {
for (loadBillers in loadBillersList) {
// this will return both the billers
// from Google Play Console
}
}
}
} else {
println("Something Wrong")
}
Step #7
To complete the purchase, we'll use the click listener. We'll add a success callback for SKU fetching in step 06's success callback.
Kotlin
if (myBiller.responseCode == BillingClient.BillingResponseCode.OK && myBiller.isNotEmpty()) {
for (myBillers in myBillers) {
if (myBiller.sku == "gfg_product_one")
buyCourseBtn.setOnClickListener {
val billingFlowParams = BillingFlowParams
.newBuilder()
.setSkuDetails(skuDetails)
.build()
myBiller.launchBillingFlow(this, billingFlowParams)
}
}
}
When the myBiller clicks, BillingFlowParams commences the buy flow with the precise SKU data, and the billingClient launches the billing flow to begin the purchase of the specified SKU.
Step #8
Now we create a mutable list, to get the list of all the purchasable items on the app, and then perform the in-app purchases
Kotlin
override fun onPurchasesUpdated(
myBiller: MyBiller?,
purchases: MutableList<Purchase>?
) {
if (myBiller?.replyCode == BillingClient.BillingReplyCode.OK && purchases != null) {
for (purchase in purchases) {
acknowledgePurchase(purchase.purchaseToken)
}
} else if (myBiller?.replyCode == BillingClient.BillingReplyCode.USER_CANCELED) {
// User cancelled purchase
} else {
// Some other error handling
}
}
private fun acknowledgePurchase(purchaseToken: String) {
val params = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchaseToken)
.build()
billingClient.acknowledgePurchase(params) { myBiller ->
val replyCode = myBiller.replyCode
val debugMessage = myBiller.debugMessage
}
}
We've completed our task. Simply create a Signed APK and publish it to the Play Store, then wait for it to be accepted. After that, all we have to do is set up the card and buy it. That's it for this article, hope you get the exact idea on how to implement in-app purchases in your app and start earning!
Similar Reads
How to Implement Google AdMob in Your Android App? In order to earn money from the Android app or game, there are several ways such as in-App Purchases, Sponsorship, Advertisements, and many more. But there is another conventional approach to earning money from the Android app is by integrating an advertisement which is known as Google AdMob. Google
4 min read
How to Integrate In-App Review API into Android App? Once we publish our app over the PlayStore and as it became live there, app rating and reviews become very crucial to driving audience and downloads to your app. In order to increase this, we ask our users to rate the app through a popup window and redirecting them to the PlayStore. But this nowaday
3 min read
Purchase Book : Meaning, Format, and Example What is a Purchase Book?Purchase Book is prepared by the firms to record the credit purchase of goods. Purchase of goods for cash and purchase of other things other than goods are not recorded in the purchase book. Cash purchases are recorded in Cash Book and other things are recorded in Journals an
3 min read
Firebase In-App Messaging in Android with Example Sending tailored, contextual messages to your app's active users that encourage them to use important features can help you engage them. This is possible with Firebase In-App Messaging. For instance, you may ask users to subscribe, view a video, finish a level, or make a purchase by sending them an
4 min read
Implement Google Admob Banner Ads in Android using Kotlin There are several ways to earn money from mobile applications such as selling products online through applications or simply displaying ads within applications. There are so many types of ads that we can display within our application. Google provides us a service known as Google Admob with the help
3 min read