Skip to Content
In-App Purchases

In-App Purchases

In-app purchases (IAPs) are additional features, content, or services that you can buy within a mobile app. They essentially allow app developers to offer a base version of their app for free, while giving users the option to unlock more functionalities or enhance their experience through paid purchases.

Usage

Dependencies

Within your app module’s build.gradle.kts file, incorporate the following dependencies:

implementation(project(":billing"))

Example

The BillingManager class provides a simplified interface for common billing operations.

Setting up BillingManager

val products = listOf( BillingProduct( productId = "product_1", type = BillingProductType.IN_APP, isConsumable = true ) )
  • Replace “product_1” with your actual product IDs from Google Play Developer Console.
  • Set isConsumable to true for consumable products (like extra lives) and false for non-consumable products (like ad-removal).
  • Implement the PurchaseCallback interface to handle billing events.

Handling Billing Events

The PurchaseCallback interface provides methods for handling different billing events:

  • onBillingConnected(): Called when the connection to Google Play Billing is successful.
  • onBillingDisconnected(): Called when the connection to Google Play Billing is lost.
  • onPurchaseSuccess(purchases: List<Purchase>): Called when a purchase is successful.
  • onPurchaseCancelled(): Called when a purchase is cancelled by the user.
  • onPurchaseError(code: Int): Called when a purchase fails with an error code.

Interacting with Billing

The BillingManager class offers several methods for interacting with Google Play Billing:

  • getProducts(): Retrieves product details for the configured product IDs.
  • getPurchases(type: BillingProductType?): Gets a list of active purchases for the given product type (or all purchases if no type is provided).
  • getPurchaseHistory(type: BillingProductType?): Retrieves the purchase history for the given product type (or all purchases if no type is provided).
  • startPurchaseFlow(activity: Activity, varargs product: ProductDetails): Starts the purchase flow for the specified product(s).
  • handlePurchase(purchase: Purchase): Handles a purchase by acknowledging it (consumable or non-consumable).

Acknowledging Purchases

By default the handlePurchase method acknowledges the purchase on the client-side, though if you want to manually handle the acknowledgement then you can use the following methods:

  • acknowledgeConsumablePurchase(purchase: Purchase) to acknowledge the purchase and consume the consumable product.
  • acknowledgeNonConsumablePurchase(purchase: Purchase) to acknowledge the purchase and unlock the non-consumable product.

More information on Google Play Billing can be found in the official documentation.