|
| 1 | +package com.mobilebytelabs.paycraft.billing |
| 2 | + |
| 3 | +import android.app.Activity |
| 4 | +import android.content.Context |
| 5 | +import android.content.Intent |
| 6 | +import android.net.Uri |
| 7 | +import co.touchlab.kermit.Logger |
| 8 | +import com.android.billingclient.api.AcknowledgePurchaseParams |
| 9 | +import com.android.billingclient.api.BillingClient |
| 10 | +import com.android.billingclient.api.BillingClient.BillingResponseCode |
| 11 | +import com.android.billingclient.api.BillingClientStateListener |
| 12 | +import com.android.billingclient.api.BillingFlowParams |
| 13 | +import com.android.billingclient.api.BillingResult |
| 14 | +import com.android.billingclient.api.PendingPurchasesParams |
| 15 | +import com.android.billingclient.api.ProductDetails |
| 16 | +import com.android.billingclient.api.Purchase |
| 17 | +import com.android.billingclient.api.PurchasesUpdatedListener |
| 18 | +import com.android.billingclient.api.QueryProductDetailsParams |
| 19 | +import com.android.billingclient.api.QueryPurchasesParams |
| 20 | +import com.android.billingclient.api.acknowledgePurchase |
| 21 | +import com.android.billingclient.api.queryProductDetails |
| 22 | +import com.android.billingclient.api.queryPurchasesAsync |
| 23 | +import kotlinx.coroutines.flow.MutableSharedFlow |
| 24 | +import kotlinx.coroutines.flow.first |
| 25 | +import kotlinx.coroutines.suspendCancellableCoroutine |
| 26 | +import kotlinx.coroutines.sync.Mutex |
| 27 | +import kotlinx.coroutines.sync.withLock |
| 28 | +import kotlin.coroutines.resume |
| 29 | + |
| 30 | +/** |
| 31 | + * Android [NativeBillingClient] over **Google Play Billing Library v8** |
| 32 | + * (`com.android.billingclient:billing-ktx:8.0.0`) — the Phase-3 native IAP client (D8/D13). |
| 33 | + * |
| 34 | + * v8 is required for all new apps by 2026-08-31 (GOAL Risks). This client is a *pure store |
| 35 | + * adapter* (D5): it drives the Play purchase / query / manage flows and emits [NativePurchase] |
| 36 | + * records (product id + `purchaseToken` + order id) for the Phase-2 reconciliation engine to |
| 37 | + * validate server-side (`subscriptionsv2.get`). It NEVER decides entitlement truth. |
| 38 | + * |
| 39 | + * Flow: |
| 40 | + * - [purchase] — lazily connects, `queryProductDetails` for the SUBS product, resolves the base |
| 41 | + * offer token, `launchBillingFlow`, awaits the [PurchasesUpdatedListener] callback, then |
| 42 | + * acknowledges the purchase (a subscription left un-acknowledged for 3 days is auto-refunded). |
| 43 | + * - [queryPurchases] / [restore] — `queryPurchasesAsync(SUBS)` for the signed-in Play account. |
| 44 | + * - [sync] — Play's re-link IS `queryPurchasesAsync` (there is no separate StoreKit-style sync). |
| 45 | + * - [manageSubscription] — deep-links the Play subscription centre (stores forbid programmatic |
| 46 | + * cancel — D7); a non-null product id targets the specific plan. |
| 47 | + * |
| 48 | + * DI: bind on Android via [com.mobilebytelabs.paycraft.di.paycraftPlayBillingModule], which |
| 49 | + * overrides the default `WebCheckoutNativeBillingClient` binding from `PayCraftModule`. |
| 50 | + * |
| 51 | + * @param context application context — used to construct the [BillingClient] and to launch the |
| 52 | + * Play subscription-centre intent for [manageSubscription]. |
| 53 | + * @param activityProvider supplies the current foreground [Activity] required by |
| 54 | + * `launchBillingFlow`; returns null when no Activity is resumed (purchase then fails cleanly). |
| 55 | + */ |
| 56 | +class PlayBillingNativeClient(context: Context, private val activityProvider: () -> Activity?) : NativeBillingClient { |
| 57 | + |
| 58 | + private val appContext: Context = context.applicationContext |
| 59 | + |
| 60 | + /** Buffered so a purchase callback that arrives before [purchase] suspends is not dropped. */ |
| 61 | + private val purchaseUpdates = MutableSharedFlow<PurchasesUpdate>(extraBufferCapacity = 1) |
| 62 | + |
| 63 | + private val connectMutex = Mutex() |
| 64 | + |
| 65 | + private val purchasesListener = PurchasesUpdatedListener { billingResult, purchases -> |
| 66 | + purchaseUpdates.tryEmit(PurchasesUpdate(billingResult, purchases.orEmpty())) |
| 67 | + } |
| 68 | + |
| 69 | + private val billingClient: BillingClient = BillingClient.newBuilder(appContext) |
| 70 | + .enablePendingPurchases( |
| 71 | + PendingPurchasesParams.newBuilder() |
| 72 | + .enableOneTimeProducts() |
| 73 | + .enablePrepaidPlans() |
| 74 | + .build(), |
| 75 | + ) |
| 76 | + .setListener(purchasesListener) |
| 77 | + .build() |
| 78 | + |
| 79 | + override suspend fun purchase(productId: String): NativePurchaseResult { |
| 80 | + val connect = ensureConnected() |
| 81 | + if (connect.responseCode != BillingResponseCode.OK) { |
| 82 | + return NativePurchaseResult.Failed("Play billing connect failed: ${connect.debugMessage}") |
| 83 | + } |
| 84 | + val productDetails = queryProductDetails(productId) |
| 85 | + ?: return NativePurchaseResult.Failed("Product not found on Play: $productId") |
| 86 | + val offerToken = productDetails.subscriptionOfferDetails?.firstOrNull()?.offerToken |
| 87 | + ?: return NativePurchaseResult.Failed("No subscription offer for $productId") |
| 88 | + val activity = activityProvider() |
| 89 | + ?: return NativePurchaseResult.Failed("No foreground Activity to launch the billing flow") |
| 90 | + |
| 91 | + val flowParams = BillingFlowParams.newBuilder() |
| 92 | + .setProductDetailsParamsList( |
| 93 | + listOf( |
| 94 | + BillingFlowParams.ProductDetailsParams.newBuilder() |
| 95 | + .setProductDetails(productDetails) |
| 96 | + .setOfferToken(offerToken) |
| 97 | + .build(), |
| 98 | + ), |
| 99 | + ) |
| 100 | + .build() |
| 101 | + |
| 102 | + val launch = billingClient.launchBillingFlow(activity, flowParams) |
| 103 | + if (launch.responseCode != BillingResponseCode.OK) { |
| 104 | + return NativePurchaseResult.Failed("launchBillingFlow failed: ${launch.debugMessage}") |
| 105 | + } |
| 106 | + |
| 107 | + val update = purchaseUpdates.first() |
| 108 | + return when (update.billingResult.responseCode) { |
| 109 | + BillingResponseCode.OK -> { |
| 110 | + val purchase = update.purchases.firstOrNull { productId in it.products } |
| 111 | + ?: update.purchases.firstOrNull() |
| 112 | + ?: return NativePurchaseResult.Failed("Play reported OK with no Purchase") |
| 113 | + acknowledgeIfNeeded(purchase) |
| 114 | + NativePurchaseResult.Success(purchase.toNativePurchase()) |
| 115 | + } |
| 116 | + BillingResponseCode.USER_CANCELED -> NativePurchaseResult.Cancelled |
| 117 | + else -> NativePurchaseResult.Failed("Purchase failed: ${update.billingResult.debugMessage}") |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + override suspend fun queryPurchases(): List<NativePurchase> { |
| 122 | + ensureConnected() |
| 123 | + val params = QueryPurchasesParams.newBuilder() |
| 124 | + .setProductType(BillingClient.ProductType.SUBS) |
| 125 | + .build() |
| 126 | + val result = billingClient.queryPurchasesAsync(params) |
| 127 | + return result.purchasesList |
| 128 | + .filter { it.purchaseState == Purchase.PurchaseState.PURCHASED } |
| 129 | + .map { it.toNativePurchase() } |
| 130 | + } |
| 131 | + |
| 132 | + /** Play's receipt re-link IS `queryPurchasesAsync` — there is no separate sync endpoint (D7). */ |
| 133 | + override suspend fun sync() { |
| 134 | + queryPurchases() |
| 135 | + } |
| 136 | + |
| 137 | + override suspend fun restore(): List<NativePurchase> = queryPurchases() |
| 138 | + |
| 139 | + override suspend fun manageSubscription(productId: String?) { |
| 140 | + val url = if (productId != null) { |
| 141 | + "https://play.google.com/store/account/subscriptions" + |
| 142 | + "?sku=$productId&package=${appContext.packageName}" |
| 143 | + } else { |
| 144 | + "https://play.google.com/store/account/subscriptions" |
| 145 | + } |
| 146 | + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply { |
| 147 | + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) |
| 148 | + } |
| 149 | + appContext.startActivity(intent) |
| 150 | + } |
| 151 | + |
| 152 | + private suspend fun queryProductDetails(productId: String): ProductDetails? { |
| 153 | + val params = QueryProductDetailsParams.newBuilder() |
| 154 | + .setProductList( |
| 155 | + listOf( |
| 156 | + QueryProductDetailsParams.Product.newBuilder() |
| 157 | + .setProductId(productId) |
| 158 | + .setProductType(BillingClient.ProductType.SUBS) |
| 159 | + .build(), |
| 160 | + ), |
| 161 | + ) |
| 162 | + .build() |
| 163 | + val result = billingClient.queryProductDetails(params) |
| 164 | + return result.productDetailsList?.firstOrNull() |
| 165 | + } |
| 166 | + |
| 167 | + private suspend fun acknowledgeIfNeeded(purchase: Purchase) { |
| 168 | + if (purchase.purchaseState != Purchase.PurchaseState.PURCHASED || purchase.isAcknowledged) return |
| 169 | + val ack = billingClient.acknowledgePurchase( |
| 170 | + AcknowledgePurchaseParams.newBuilder() |
| 171 | + .setPurchaseToken(purchase.purchaseToken) |
| 172 | + .build(), |
| 173 | + ) |
| 174 | + if (ack.responseCode != BillingResponseCode.OK) { |
| 175 | + Logger.w("PlayBillingNativeClient") { |
| 176 | + "acknowledgePurchase failed (${ack.responseCode}): ${ack.debugMessage}" |
| 177 | + } |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + /** Idempotent, serialized connect — no-op when the client is already ready. */ |
| 182 | + private suspend fun ensureConnected(): BillingResult = connectMutex.withLock { |
| 183 | + if (billingClient.isReady) return@withLock okResult() |
| 184 | + suspendCancellableCoroutine { cont -> |
| 185 | + billingClient.startConnection( |
| 186 | + object : BillingClientStateListener { |
| 187 | + override fun onBillingSetupFinished(billingResult: BillingResult) { |
| 188 | + if (cont.isActive) cont.resume(billingResult) |
| 189 | + } |
| 190 | + |
| 191 | + // Next ensureConnected() reconnects lazily via the isReady guard above. |
| 192 | + override fun onBillingServiceDisconnected() = Unit |
| 193 | + }, |
| 194 | + ) |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + private fun okResult(): BillingResult = BillingResult.newBuilder().setResponseCode(BillingResponseCode.OK).build() |
| 199 | + |
| 200 | + private fun Purchase.toNativePurchase(): NativePurchase = NativePurchase( |
| 201 | + productId = products.firstOrNull().orEmpty(), |
| 202 | + purchaseToken = purchaseToken, |
| 203 | + originalTransactionId = orderId, |
| 204 | + purchaseTimeMillis = purchaseTime, |
| 205 | + isAutoRenewing = isAutoRenewing, |
| 206 | + packageName = packageName, |
| 207 | + ) |
| 208 | + |
| 209 | + private data class PurchasesUpdate(val billingResult: BillingResult, val purchases: List<Purchase>) |
| 210 | +} |
0 commit comments