Quick Start
Get up and running with KMP IAP in just a few minutes!
Version
This guide covers v1.0.0-rc with simplified API. For v1.0.0-rc, see the migration guide.
Choose Your Approach
KMP IAP supports two usage patterns:
Option 1: Global Instance (Simple)
Use the pre-created kmpIapInstance for convenience and simplicity.
Option 2: Create Your Own Instance (Recommended for Testing)
Create your own KmpIAP() instances for better control, testing, or dependency injection.
Basic Implementation
Using Global Instance
Here's a complete example using the global instance:
import io.github.hyochan.kmpiap.kmpIapInstance
import io.github.hyochan.kmpiap.types.*
import kotlinx.coroutines.*
class IAPManager {
private val scope = CoroutineScope(Dispatchers.Main)
suspend fun initialize() {
try {
// Initialize connection using global instance
kmpIapInstance.initConnection()
// Listen to purchase updates
scope.launch {
kmpIapInstance.purchaseUpdatedListener.collect { purchase ->
handlePurchaseUpdate(purchase)
}
}
// Listen to errors
scope.launch {
kmpIapInstance.purchaseErrorListener.collect { error ->
handlePurchaseError(error)
}
}
} catch (e: Exception) {
println("Initialization failed: ${e.message}")
}
}
suspend fun loadProducts() {
try {
// v1.0.0-rc - DSL API
val products = kmpIapInstance.fetchProducts {
skus = listOf("product_1", "product_2")
type = ProductQueryType.InApp
}
println("Loaded ${products.size} products")
} catch (e: Exception) {
println("Failed to load products: ${e.message}")
}
}
suspend fun purchaseProduct(productId: String) {
try {
// v1.0.0-rc - DSL API
kmpIapInstance.requestPurchase {
apple {
sku = productId
quantity = 1
}
android {
skus = listOf(productId)
}
}
// Purchase will be handled via purchaseUpdatedListener
} catch (e: Exception) {
println("Purchase failed: ${e.message}")
}
}
private suspend fun handlePurchaseUpdate(purchase: Purchase) {
// Verify purchase with your backend
val isValid = verifyPurchaseWithBackend(purchase)
if (isValid) {
// Grant the purchased content
grantPurchase(purchase)
// Finish the transaction
kmpIapInstance.finishTransaction(
purchase = purchase.toPurchaseInput(),
isConsumable = isConsumableProduct(purchase.productId)
)
}
}
}
