In-App Purchase (IAP)
Integrating In-App Purchase (IAP) APIs into your Android and iOS apps allows users to purchase digital goods directly within the app. Here’s a high-level overview of how to integrate IAP for both platforms.
Android: Google Play In-App Billing
-
Set up your app in the Google Play Console:
- Go to the Google Play Console.
- Create a new application if you haven’t already.
- Navigate to "Monetize" -> "Products" -> "In-app products" and create your in-app products.
-
Add the Billing Library to your project:
- Add the following dependency to your
build.gradle
file:dependencies { implementation 'com.android.billingclient:billing:4.0.0' }
- Add the following dependency to your
-
Implement BillingClient in your app:
- Initialize
BillingClient
and establish a connection. - Query available products and handle purchases.
BillingClient billingClient = BillingClient.newBuilder(context) .setListener(new PurchasesUpdatedListener() { @Override public void onPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases) { if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchases != null) { for (Purchase purchase : purchases) { handlePurchase(purchase); } } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED) { // Handle an error caused by a user canceling the purchase flow. } else { // Handle any other error codes. } } }).enablePendingPurchases().build(); billingClient.startConnection(new BillingClientStateListener() { @Override public void onBillingSetupFinished(BillingResult billingResult) { if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { // The BillingClient is ready. You can query purchases here. } } @Override public void onBillingServiceDisconnected() { // Try to restart the connection on the next request to Google Play by calling the startConnection() method. } });
- Initialize
-
Query Products:
List<String> skuList = new ArrayList<>(); skuList.add("your_product_id"); SkuDetailsParams params = SkuDetailsParams.newBuilder() .setSkusList(skuList) .setType(BillingClient.SkuType.INAPP) .build(); billingClient.querySkuDetailsAsync(params, new SkuDetailsResponseListener() { @Override public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) { // Process the result. } });
-
Launch Purchase Flow:
BillingFlowParams flowParams = BillingFlowParams.newBuilder() .setSkuDetails(skuDetails) .build(); billingClient.launchBillingFlow(activity, flowParams);
-
Handle Purchases:
private void handlePurchase(Purchase purchase) { // Handle the purchase. }
iOS: StoreKit
-
Set up your app in App Store Connect:
- Log in to App Store Connect.
- Create a new app or select an existing one.
- Navigate to "Features" -> "In-App Purchases" and create your in-app purchases.
-
Enable In-App Purchases in Xcode:
- Go to your project settings in Xcode.
- Select your target and go to the "Signing & Capabilities" tab.
- Add the "In-App Purchase" capability.
-
Implement In-App Purchases:
- Import StoreKit and create a class to manage purchases.
import StoreKit class IAPManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver { static let shared = IAPManager() private override init() { } func startObserving() { SKPaymentQueue.default().add(self) } func stopObserving() { SKPaymentQueue.default().remove(self) } func fetchProducts() { let request = SKProductsRequest(productIdentifiers: ["your_product_id"]) request.delegate = self request.start() } func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { let products = response.products // Handle the products. } func buyProduct(product: SKProduct) { let payment = SKPayment(product: product) SKPaymentQueue.default().add(payment) } func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch transaction.transactionState { case .purchased: // Handle purchased. SKPaymentQueue.default().finishTransaction(transaction) case .failed: // Handle failed. SKPaymentQueue.default().finishTransaction(transaction) case .restored: // Handle restored. SKPaymentQueue.default().finishTransaction(transaction) default: break } } } }
-
Fetch Products:
IAPManager.shared.fetchProducts()
-
Purchase a Product:
if let product = products.first { IAPManager.shared.buyProduct(product: product) }
-
Handle Purchases:
- Implement the transaction observer methods to handle the purchase flow and complete the transaction.
Testing
- Android:
- Use test accounts and test cards provided by Google Play Console for testing IAP without actual transactions.
- iOS:
- Use sandbox accounts in App Store Connect to test IAP without real charges.
Additional Resources
-
Android Documentation:
-
iOS Documentation:
Integrating IAP can be complex, involving backend validation and additional security measures to prevent fraud. Make sure to follow best practices and refer to the official documentation for comprehensive guides and updates.