HOW TO IMPLEMENT IN

In this appmobiles.info, we are going khổng lồ learn about how can we make in-app purchases in android devices using the billing library.

Bạn đang xem: How to implement in

We will build an ứng dụng in the process, which will help us understand the implementation of In-App purchases. So before any delay, let's start

We will create an tiện ích with an Empty Activity as initial activity & name it as MainActivity and its XML tệp tin as activity_main.xml. (This project will be in Kotlin)

Step 01:

Add the following line lớn the dependencies section of the build.gradle tệp tin for your app:

dependencies ... Implementation "com.android.billingclient:billing:2.0.3"Step 02:Also, you need to add the billing permission in the app's apk manifest.

And, now when we are done with setting the permission and dependency we have lớn start the implementation to lớn set up the connection with Google Play khổng lồ get started.

Step 03:

In MainActivity, we will create two variables.

class MainActivity : AppCompatActivity() { private lateinit var billingClient: BillingClient private val skuList = listOf("test_product_one", "test_product_two") ........Here, the first variable we have created is of type BillingClient, which provides the Main interface for communication between the library and user application code and we create a list of SKUs that specify the menu of sản phẩm IDs we have to be purchased.

Step 04:

Now, in the onCreate() method we will set up the billing client using,

class MainActivity : AppCompatActivity(), PurchasesUpdatedListener { //The variables we declared above override fun onCreate(savedInstanceState: Bundle?) .......... SetupBillingClient() private fun setupBillingClient() billingClient = BillingClient.newBuilder(this) .enablePendingPurchases() .setListener(this) .build() billingClient.startConnection(object : BillingClientStateListener override fun onBillingSetupFinished(billingResult: BillingResult) if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) // The BillingClient is setup successfully override fun onBillingServiceDisconnected() // Try to lớn restart the connection on the next request to lớn // Google Play by calling the startConnection() method. ) Step 05:Now Let's set up the purchasing product in our play console.

First, Login lớn your play console & click CREATE APPLICATION.Set up your ứng dụng as usual how you vì for all other apps like providing the information of app name, app description, etc.Get all required information like Store listing, Ratings etc & reach lớn point where you just need to lớn just upload the apk or AAB file.

Xem thêm:

Now, when you are done executing the above steps we need to create PRODUCTS which we can purchase. To vì chưng it,

From on the left menu,

StorePresence -> In-app products tab -> Create managed product
*

Here, sản phẩm ID has to lớn be unique và this is what we have lớn play within our code. If you remember we had a list of SKUs

private val skuList = listOf("test_product_one", "test_product_two")that string values are nothing but product ID. So now khổng lồ the thiết lập we will địa chỉ test_product_one and test_product_two as hàng hóa ID và will add rest of the details.

Now, when we are done with filling up the above info we need khổng lồ scroll down to make it active and showroom the price of the product


*

and just press Save.

You now have successfully created your first hàng hóa on play console. Showroom both the SKUs one by one & jump back khổng lồ the code.

Step 06:

In thiết đặt billing method, if we have successfully connected to lớn the Billing Client then we query all the SKUs,

private fun setupBillingClient() billingClient = BillingClient.newBuilder(this) .enablePendingPurchases() .setListener(this) .build() billingClient.startConnection(object : BillingClientStateListener override fun onBillingSetupFinished(billingResult: BillingResult) if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) // The BillingClient is thiết lập logger("Setup Billing Done") loadAllSKUs() override fun onBillingServiceDisconnected() logger("Failed") )and in loadAllSKUs(),

private fun loadAllSKUs() = if (billingClient.isReady) val params = SkuDetailsParams .newBuilder() .setSkusList(skuList) .setType(BillingClient.SkuType.INAPP) .build() billingClient.querySkuDetailsAsync(params) billingResult, skuDetailsList -> // Process the result. If (billingResult.responseCode == BillingClient.BillingResponseCode.OK && skuDetailsList.isNotEmpty()) for (skuDetails in skuDetailsList) //this will return both the SKUs from Google Play Console else println("Billing Client not ready")Here, SkuDetailsParams is used lớn query the for SKU details & in setType, we are just calling INAPP type. Then we just query the result asynchronously. & get the SKUs if the Response code is Successful & the SKUs are created successfully in the Google Console.

Step 07:

Now we will design our XML file where we will địa chỉ cửa hàng a button lớn purchase the thành tích with SKU name test_product_two. The XML looks like,

Step 08 :Now we will implement the click listener lớn set up the purchase. In the success callback of SKU fetching which we did in step 06, we will showroom

if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && skuDetailsList.isNotEmpty()) for (skuDetails in skuDetailsList) if (skuDetails.sku == "test_product_two") buttonBuyProduct.setOnClickListener val billingFlowParams = BillingFlowParams .newBuilder() .setSkuDetails(skuDetails) .build() billingClient.launchBillingFlow(this, billingFlowParams) Here, BillingFlowParams initiates the purchase flow with the specific SKU detail và when the click happens, the billingClient launches the billing flow to lớn start the purchase of specific SKU.

Step 09

When the purchase of SKU starts, we will handle the purchase using,

override fun onPurchasesUpdated( billingResult: BillingResult?, purchases: MutableList?) if (billingResult?.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) for (purchase in purchases) acknowledgePurchase(purchase.purchaseToken) else if (billingResult?.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) // Handle an error caused by a user cancelling the purchase flow. else // Handle any other error codes. Private fun acknowledgePurchase(purchaseToken: String) val params = AcknowledgePurchaseParams.newBuilder() .setPurchaseToken(purchaseToken) .build() billingClient.acknowledgePurchase(params) billingResult -> val responseCode = billingResult.responseCode val debugMessage = billingResult.debugMessage Step 10:Now, we are done. Just generate a Signed APK and upload it lớn the Play Console & wait for the app to get accepted. One done follow the next step.

Step 11

This will prompt a Bottom View like,


*

Now, we just need to lớn set up the card và purchase it. We are using Debug to test so that is the reason we have chạy thử Card.