@app-swiss-knife/react-native-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +182 -0
- package/SwissKnifePurchases.podspec +40 -0
- package/android/build.gradle +89 -0
- package/android/gradle.properties +3 -0
- package/android/src/main/AndroidManifest.xml +26 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
- package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
- package/android/vendor/GENERATED.md +10 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
- package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
- package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
- package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
- package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
- package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
- package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
- package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
- package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
- package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
- package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
- package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
- package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
- package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
- package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
- package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
- package/ios/SwissKnifeCrashReporting.m +32 -0
- package/ios/SwissKnifeCrashReporting.swift +186 -0
- package/ios/SwissKnifeJSON.swift +347 -0
- package/ios/SwissKnifePurchases.m +124 -0
- package/ios/SwissKnifePurchases.swift +523 -0
- package/ios/vendor/GENERATED.md +10 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
- package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
- package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
- package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
- package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
- package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
- package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
- package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
- package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
- package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
- package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
- package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
- package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
- package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
- package/lib/commonjs/attribution.js +55 -0
- package/lib/commonjs/attribution.js.map +1 -0
- package/lib/commonjs/identity.js +126 -0
- package/lib/commonjs/identity.js.map +1 -0
- package/lib/commonjs/index.js +118 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +646 -0
- package/lib/commonjs/modules/analytics.js.map +1 -0
- package/lib/commonjs/modules/attachments.js +169 -0
- package/lib/commonjs/modules/attachments.js.map +1 -0
- package/lib/commonjs/modules/crash-reporting.js +1327 -0
- package/lib/commonjs/modules/crash-reporting.js.map +1 -0
- package/lib/commonjs/modules/ids.js +50 -0
- package/lib/commonjs/modules/ids.js.map +1 -0
- package/lib/commonjs/modules/log.js +59 -0
- package/lib/commonjs/modules/log.js.map +1 -0
- package/lib/commonjs/modules/offline-store.js +44 -0
- package/lib/commonjs/modules/offline-store.js.map +1 -0
- package/lib/commonjs/modules/performance.js +494 -0
- package/lib/commonjs/modules/performance.js.map +1 -0
- package/lib/commonjs/native/module.js +41 -0
- package/lib/commonjs/native/module.js.map +1 -0
- package/lib/commonjs/native/spec.js +26 -0
- package/lib/commonjs/native/spec.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/purchases.js +194 -0
- package/lib/commonjs/purchases.js.map +1 -0
- package/lib/commonjs/types.js +236 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/module/attribution.js +51 -0
- package/lib/module/attribution.js.map +1 -0
- package/lib/module/identity.js +122 -0
- package/lib/module/identity.js.map +1 -0
- package/lib/module/index.js +36 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/modules/analytics.js +642 -0
- package/lib/module/modules/analytics.js.map +1 -0
- package/lib/module/modules/attachments.js +162 -0
- package/lib/module/modules/attachments.js.map +1 -0
- package/lib/module/modules/crash-reporting.js +1320 -0
- package/lib/module/modules/crash-reporting.js.map +1 -0
- package/lib/module/modules/ids.js +44 -0
- package/lib/module/modules/ids.js.map +1 -0
- package/lib/module/modules/log.js +54 -0
- package/lib/module/modules/log.js.map +1 -0
- package/lib/module/modules/offline-store.js +39 -0
- package/lib/module/modules/offline-store.js.map +1 -0
- package/lib/module/modules/performance.js +491 -0
- package/lib/module/modules/performance.js.map +1 -0
- package/lib/module/native/module.js +34 -0
- package/lib/module/native/module.js.map +1 -0
- package/lib/module/native/spec.js +22 -0
- package/lib/module/native/spec.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/purchases.js +187 -0
- package/lib/module/purchases.js.map +1 -0
- package/lib/module/types.js +230 -0
- package/lib/module/types.js.map +1 -0
- package/lib/typescript/commonjs/attribution.d.ts +24 -0
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
- package/lib/typescript/commonjs/identity.d.ts +37 -0
- package/lib/typescript/commonjs/identity.d.ts.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +15 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
- package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/log.d.ts +12 -0
- package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/module.d.ts +6 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/spec.d.ts +119 -0
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/purchases.d.ts +68 -0
- package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
- package/lib/typescript/commonjs/types.d.ts +384 -0
- package/lib/typescript/commonjs/types.d.ts.map +1 -0
- package/lib/typescript/module/attribution.d.ts +24 -0
- package/lib/typescript/module/attribution.d.ts.map +1 -0
- package/lib/typescript/module/identity.d.ts +37 -0
- package/lib/typescript/module/identity.d.ts.map +1 -0
- package/lib/typescript/module/index.d.ts +15 -0
- package/lib/typescript/module/index.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +127 -0
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/module/modules/attachments.d.ts +50 -0
- package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/module/modules/ids.d.ts +17 -0
- package/lib/typescript/module/modules/ids.d.ts.map +1 -0
- package/lib/typescript/module/modules/log.d.ts +12 -0
- package/lib/typescript/module/modules/log.d.ts.map +1 -0
- package/lib/typescript/module/modules/offline-store.d.ts +9 -0
- package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +75 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -0
- package/lib/typescript/module/native/module.d.ts +6 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -0
- package/lib/typescript/module/native/spec.d.ts +119 -0
- package/lib/typescript/module/native/spec.d.ts.map +1 -0
- package/lib/typescript/module/package.json +1 -0
- package/lib/typescript/module/purchases.d.ts +68 -0
- package/lib/typescript/module/purchases.d.ts.map +1 -0
- package/lib/typescript/module/types.d.ts +384 -0
- package/lib/typescript/module/types.d.ts.map +1 -0
- package/package.json +115 -0
- package/react-native.config.js +23 -0
- package/src/attribution.ts +56 -0
- package/src/identity.ts +133 -0
- package/src/index.ts +54 -0
- package/src/modules/analytics.ts +689 -0
- package/src/modules/attachments.ts +222 -0
- package/src/modules/crash-reporting.ts +1577 -0
- package/src/modules/ids.ts +41 -0
- package/src/modules/log.ts +56 -0
- package/src/modules/offline-store.ts +51 -0
- package/src/modules/performance.ts +589 -0
- package/src/native/module.ts +47 -0
- package/src/native/spec.ts +183 -0
- package/src/purchases.ts +214 -0
- package/src/types.ts +470 -0
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/purchases/BillingClientGateway.kt
|
|
2
|
+
//
|
|
3
|
+
// Phase 6 commit 3 — direct Google Play Billing v8 gateway. Replaces
|
|
4
|
+
// PurchasesHybridCommonGateway as the production implementation.
|
|
5
|
+
//
|
|
6
|
+
// Architecture:
|
|
7
|
+
// - Owns a single BillingClient connected via startConnection. Connection
|
|
8
|
+
// errors trigger exponential backoff reconnect (1s/2s/4s/8s/16s, cap 5).
|
|
9
|
+
// - All Play Billing callbacks are invoked on Play's executor (not main);
|
|
10
|
+
// we surface them as-is - the gateway interface contract is "callbacks
|
|
11
|
+
// may fire on any thread."
|
|
12
|
+
// - Every successful purchase round-trips through our backend at
|
|
13
|
+
// /api/sdk/subscriptions/validate before being surfaced as success. The
|
|
14
|
+
// backend is authoritative for entitlement state per the locked decision.
|
|
15
|
+
// - CustomerInfo reads delegate to EntitlementsRepository (24h cache).
|
|
16
|
+
//
|
|
17
|
+
// What's intentionally NOT here:
|
|
18
|
+
// - logIn/logOut don't actually exist in Play Billing - the SDK identity
|
|
19
|
+
// model is ours, kept in [EntitlementsRepository.invalidate()] + a
|
|
20
|
+
// userId mutable. We honor RC parity by exposing them on the gateway.
|
|
21
|
+
// - Offerings/products fetching - that's OfferingsRepository (commit 4).
|
|
22
|
+
// This gateway only queries ProductDetails on-demand for purchase.
|
|
23
|
+
// - Acknowledge details: we acknowledge() non-consumed subscription /
|
|
24
|
+
// non-consumable purchases. Consumables are NOT exposed today (RC parity:
|
|
25
|
+
// RC didn't expose consume() either - those are managed by RC's backend).
|
|
26
|
+
|
|
27
|
+
package com.appswissknife.purchases
|
|
28
|
+
|
|
29
|
+
import android.app.Activity
|
|
30
|
+
import android.content.Context
|
|
31
|
+
import android.os.Handler
|
|
32
|
+
import android.os.Looper
|
|
33
|
+
import android.util.Log
|
|
34
|
+
import androidx.annotation.VisibleForTesting
|
|
35
|
+
import com.android.billingclient.api.AcknowledgePurchaseParams
|
|
36
|
+
import com.android.billingclient.api.BillingClient
|
|
37
|
+
import com.android.billingclient.api.BillingClientStateListener
|
|
38
|
+
import com.android.billingclient.api.BillingFlowParams
|
|
39
|
+
import com.android.billingclient.api.BillingResult
|
|
40
|
+
import com.android.billingclient.api.PendingPurchasesParams
|
|
41
|
+
import com.android.billingclient.api.ProductDetails
|
|
42
|
+
import com.android.billingclient.api.Purchase
|
|
43
|
+
import com.android.billingclient.api.PurchasesUpdatedListener
|
|
44
|
+
import com.android.billingclient.api.QueryProductDetailsParams
|
|
45
|
+
import com.android.billingclient.api.QueryPurchasesParams
|
|
46
|
+
import com.appswissknife.StoreTransactionResult
|
|
47
|
+
import com.appswissknife.entitlements.EntitlementsRepository
|
|
48
|
+
import com.appswissknife.entitlements.SimpleCustomerInfo
|
|
49
|
+
import com.appswissknife.entitlements.SimpleEntitlementInfos
|
|
50
|
+
import com.appswissknife.models.CustomerInfo
|
|
51
|
+
import com.appswissknife.models.LogLevel
|
|
52
|
+
import com.appswissknife.models.Offerings
|
|
53
|
+
import com.appswissknife.models.Package
|
|
54
|
+
import com.appswissknife.models.PurchasesError
|
|
55
|
+
import com.appswissknife.models.PurchasesErrorCode
|
|
56
|
+
import com.appswissknife.models.StoreProduct
|
|
57
|
+
import com.appswissknife.models.StoreTransaction
|
|
58
|
+
import com.appswissknife.models.VerificationResult
|
|
59
|
+
import org.json.JSONObject
|
|
60
|
+
import java.io.IOException
|
|
61
|
+
import java.util.Collections
|
|
62
|
+
import java.util.Date
|
|
63
|
+
import java.util.UUID
|
|
64
|
+
import java.util.concurrent.ExecutorService
|
|
65
|
+
import java.util.concurrent.Executors
|
|
66
|
+
import java.util.concurrent.atomic.AtomicBoolean
|
|
67
|
+
import java.util.concurrent.atomic.AtomicInteger
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Production [PurchasesGateway] using Google Play Billing v8 directly. No
|
|
71
|
+
* PHC, no RevenueCat — every purchase round-trips through our own
|
|
72
|
+
* `/api/sdk/subscriptions/validate` and entitlement reads come from the
|
|
73
|
+
* cached [EntitlementsRepository].
|
|
74
|
+
*
|
|
75
|
+
* Instances are bound to a single [Context] (the application) at [configure].
|
|
76
|
+
* The gateway owns its own background executor for HTTP work; Play Billing
|
|
77
|
+
* runs callbacks on its own thread pool.
|
|
78
|
+
*/
|
|
79
|
+
class BillingClientGateway(
|
|
80
|
+
// Pluggable backend HTTP for tests. Default routes through the unified
|
|
81
|
+
// Round-D net layer — see net/BackendHttpClient.kt (single transport
|
|
82
|
+
// for every SDK HTTP call).
|
|
83
|
+
private val httpClient: BillingHttpClient = com.appswissknife.net.BackendHttpClientAdapter(),
|
|
84
|
+
private val reconnectScheduler: ReconnectScheduler = HandlerReconnectScheduler(),
|
|
85
|
+
) : PurchasesGateway, PurchasesUpdatedListener {
|
|
86
|
+
|
|
87
|
+
// --- State -------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
@Volatile private var billingClient: BillingClient? = null
|
|
90
|
+
@Volatile private var entitlementsRepo: EntitlementsRepository? = null
|
|
91
|
+
@Volatile private var serverUrl: String = ""
|
|
92
|
+
@Volatile private var apiKey: String = ""
|
|
93
|
+
@Volatile private var explicitAppUserId: String? = null
|
|
94
|
+
// Wave 1: unified `$SKAnonymousID:` prefix across iOS / Android / RN.
|
|
95
|
+
// Was `$RCAnonymousID:` (RC legacy) before the audit. Per the
|
|
96
|
+
// user-locked decision we do NOT backfill on-device caches with the
|
|
97
|
+
// new prefix — whatever's already there stays; only fresh installs
|
|
98
|
+
// and logOut() rotations pick it up.
|
|
99
|
+
@Volatile private var anonymousAppUserId: String = "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
|
|
100
|
+
|
|
101
|
+
private val configured = AtomicBoolean(false)
|
|
102
|
+
private val reconnectAttempt = AtomicInteger(0)
|
|
103
|
+
|
|
104
|
+
private val executor: ExecutorService =
|
|
105
|
+
Executors.newSingleThreadExecutor { r -> Thread(r, "swissknife-billing").apply { isDaemon = true } }
|
|
106
|
+
|
|
107
|
+
private val customerInfoListeners = Collections.synchronizedSet(mutableSetOf<(CustomerInfo) -> Unit>())
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* In-flight purchase tracker. Play Billing's [PurchasesUpdatedListener] is
|
|
111
|
+
* a single global callback - we route the result back to whichever
|
|
112
|
+
* purchasePackage/purchaseStoreProduct call started the flow. Single-entry
|
|
113
|
+
* because Play does not support concurrent in-flight purchases.
|
|
114
|
+
*/
|
|
115
|
+
@Volatile private var pendingPurchase: PendingPurchase? = null
|
|
116
|
+
|
|
117
|
+
// --- PurchasesGateway -------------------------------------------------
|
|
118
|
+
|
|
119
|
+
override fun configure(
|
|
120
|
+
context: Context,
|
|
121
|
+
apiKey: String,
|
|
122
|
+
appUserID: String?,
|
|
123
|
+
proxyURL: String?,
|
|
124
|
+
useAmazon: Boolean,
|
|
125
|
+
) {
|
|
126
|
+
if (!configured.compareAndSet(false, true)) {
|
|
127
|
+
// Idempotent - PHC threw on second configure, we just no-op. Matches
|
|
128
|
+
// the parity expectation tested in SwissKnifeConfigureRobolectricTest.
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
require(proxyURL?.isNotEmpty() == true || serverUrl.isNotEmpty()) {
|
|
132
|
+
// proxyURL is the backend host (e.g. https://api.example.test). Without
|
|
133
|
+
// it we don't know where to validate purchases. RC's hardening reused
|
|
134
|
+
// proxyURL for the same purpose.
|
|
135
|
+
}
|
|
136
|
+
val appContext = context.applicationContext
|
|
137
|
+
this.serverUrl = proxyURL?.trimEnd('/').orEmpty()
|
|
138
|
+
this.apiKey = apiKey
|
|
139
|
+
this.explicitAppUserId = appUserID
|
|
140
|
+
|
|
141
|
+
val repo = EntitlementsRepository.get(
|
|
142
|
+
context = appContext,
|
|
143
|
+
serverUrl = serverUrl,
|
|
144
|
+
apiKey = apiKey,
|
|
145
|
+
userIdProvider = { getAppUserID() },
|
|
146
|
+
)
|
|
147
|
+
this.entitlementsRepo = repo
|
|
148
|
+
|
|
149
|
+
val client = BillingClient.newBuilder(appContext)
|
|
150
|
+
.setListener(this)
|
|
151
|
+
.enablePendingPurchases(
|
|
152
|
+
PendingPurchasesParams.newBuilder()
|
|
153
|
+
.enableOneTimeProducts()
|
|
154
|
+
.enablePrepaidPlans()
|
|
155
|
+
.build()
|
|
156
|
+
)
|
|
157
|
+
.build()
|
|
158
|
+
this.billingClient = client
|
|
159
|
+
connect()
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Internal accessor for [PlayPriceEnrichmentProvider] - so it can issue
|
|
163
|
+
* queryProductDetailsAsync calls via the same BillingClient this gateway
|
|
164
|
+
* owns. */
|
|
165
|
+
@VisibleForTesting
|
|
166
|
+
internal fun billingClientOrNull(): BillingClient? = billingClient
|
|
167
|
+
|
|
168
|
+
/** Play Billing price enrichment for OfferingsRepository (Play types stay in
|
|
169
|
+
* [PlayPriceEnrichmentProvider]). */
|
|
170
|
+
override fun priceEnrichmentProvider(): PriceEnrichmentProvider =
|
|
171
|
+
PlayPriceEnrichmentProvider { billingClientOrNull() }
|
|
172
|
+
|
|
173
|
+
override fun isConfigured(): Boolean = configured.get()
|
|
174
|
+
|
|
175
|
+
override fun getAppUserID(): String = explicitAppUserId ?: anonymousAppUserId
|
|
176
|
+
|
|
177
|
+
override fun isAnonymous(): Boolean = explicitAppUserId == null
|
|
178
|
+
|
|
179
|
+
override fun getCustomerInfo(
|
|
180
|
+
onSuccess: (CustomerInfo) -> Unit,
|
|
181
|
+
onError: (PurchasesError) -> Unit,
|
|
182
|
+
) {
|
|
183
|
+
val repo = entitlementsRepo
|
|
184
|
+
val cached = repo?.current()
|
|
185
|
+
if (cached != null && repo.isFresh()) {
|
|
186
|
+
onSuccess(cached); return
|
|
187
|
+
}
|
|
188
|
+
// Stale or empty - refresh from backend on the executor.
|
|
189
|
+
executor.execute {
|
|
190
|
+
runCatching { repo?.refresh(emptySet()) ?: emptyCustomerInfo() }
|
|
191
|
+
.onSuccess { onSuccess(it) }
|
|
192
|
+
.onFailure {
|
|
193
|
+
// On network failure, fall back to whatever cache we have. Better
|
|
194
|
+
// to serve stale than to error users out of access.
|
|
195
|
+
cached?.let(onSuccess) ?: onError(toPurchasesError(it))
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
override fun getOfferings(
|
|
201
|
+
onSuccess: (Offerings) -> Unit,
|
|
202
|
+
onError: (PurchasesError) -> Unit,
|
|
203
|
+
) {
|
|
204
|
+
// Offerings fetching lives in OfferingsRepository (commit 4). This
|
|
205
|
+
// gateway intentionally returns an empty offerings set; SwissKnife will
|
|
206
|
+
// be rewired in commit 5 to consult the OfferingsRepository directly.
|
|
207
|
+
onError(PurchasesError.Unknown(
|
|
208
|
+
"BillingClientGateway does not own offerings; use OfferingsRepository"
|
|
209
|
+
))
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
override fun purchasePackage(
|
|
213
|
+
activity: Activity,
|
|
214
|
+
packageToPurchase: Package,
|
|
215
|
+
onSuccess: (StoreTransactionResult) -> Unit,
|
|
216
|
+
onError: (PurchasesError, userCancelled: Boolean) -> Unit,
|
|
217
|
+
) {
|
|
218
|
+
purchaseStoreProduct(activity, packageToPurchase.product, onSuccess, onError)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
override fun purchaseStoreProduct(
|
|
222
|
+
activity: Activity,
|
|
223
|
+
product: StoreProduct,
|
|
224
|
+
onSuccess: (StoreTransactionResult) -> Unit,
|
|
225
|
+
onError: (PurchasesError, userCancelled: Boolean) -> Unit,
|
|
226
|
+
) {
|
|
227
|
+
val client = billingClient
|
|
228
|
+
if (client == null || !client.isReady) {
|
|
229
|
+
onError(PurchasesError.StoreProblem("Billing client not ready"), false); return
|
|
230
|
+
}
|
|
231
|
+
// Translate product into a Play Billing ProductDetails by re-querying.
|
|
232
|
+
// We pay a roundtrip cost per purchase but the alternative (caching
|
|
233
|
+
// ProductDetails graphs across the gateway boundary) leaks Play types.
|
|
234
|
+
val productType = BillingClient.ProductType.SUBS // assume subscription;
|
|
235
|
+
// for non-subs (one-time), the caller routes through purchaseStoreProduct
|
|
236
|
+
// with a StoreProduct whose subscriptionPeriod is null - we'd ideally
|
|
237
|
+
// branch here on `product.subscriptionPeriod`, but for Phase 6 SUBS is
|
|
238
|
+
// the only path exercised; INAPP is left for follow-up.
|
|
239
|
+
val params = QueryProductDetailsParams.newBuilder()
|
|
240
|
+
.setProductList(
|
|
241
|
+
listOf(
|
|
242
|
+
QueryProductDetailsParams.Product.newBuilder()
|
|
243
|
+
.setProductId(product.id)
|
|
244
|
+
.setProductType(productType)
|
|
245
|
+
.build()
|
|
246
|
+
)
|
|
247
|
+
)
|
|
248
|
+
.build()
|
|
249
|
+
client.queryProductDetailsAsync(params) { result, productDetailsResult ->
|
|
250
|
+
if (result.responseCode != BillingClient.BillingResponseCode.OK) {
|
|
251
|
+
onError(toPurchasesError(result), result.isUserCancelled()); return@queryProductDetailsAsync
|
|
252
|
+
}
|
|
253
|
+
val productDetailsList = productDetailsResult.productDetailsList
|
|
254
|
+
val pd = productDetailsList.firstOrNull()
|
|
255
|
+
if (pd == null) {
|
|
256
|
+
onError(PurchasesError.ProductNotAvailable("No ProductDetails for ${product.id}"), false)
|
|
257
|
+
return@queryProductDetailsAsync
|
|
258
|
+
}
|
|
259
|
+
val offerToken = pd.subscriptionOfferDetails?.firstOrNull()?.offerToken
|
|
260
|
+
val flowParamsBuilder = BillingFlowParams.ProductDetailsParams.newBuilder()
|
|
261
|
+
.setProductDetails(pd)
|
|
262
|
+
if (offerToken != null) flowParamsBuilder.setOfferToken(offerToken)
|
|
263
|
+
val flowParams = BillingFlowParams.newBuilder()
|
|
264
|
+
.setProductDetailsParamsList(listOf(flowParamsBuilder.build()))
|
|
265
|
+
.setObfuscatedAccountId(getAppUserID())
|
|
266
|
+
.build()
|
|
267
|
+
pendingPurchase = PendingPurchase(product.id, onSuccess, onError)
|
|
268
|
+
val launchResult = client.launchBillingFlow(activity, flowParams)
|
|
269
|
+
if (launchResult.responseCode != BillingClient.BillingResponseCode.OK) {
|
|
270
|
+
pendingPurchase = null
|
|
271
|
+
onError(toPurchasesError(launchResult), launchResult.isUserCancelled())
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
override fun restorePurchases(
|
|
277
|
+
onSuccess: (CustomerInfo) -> Unit,
|
|
278
|
+
onError: (PurchasesError) -> Unit,
|
|
279
|
+
) {
|
|
280
|
+
val client = billingClient
|
|
281
|
+
if (client == null || !client.isReady) {
|
|
282
|
+
onError(PurchasesError.StoreProblem("Billing client not ready")); return
|
|
283
|
+
}
|
|
284
|
+
val params = QueryPurchasesParams.newBuilder()
|
|
285
|
+
.setProductType(BillingClient.ProductType.SUBS)
|
|
286
|
+
.build()
|
|
287
|
+
client.queryPurchasesAsync(params) { result, purchases ->
|
|
288
|
+
if (result.responseCode != BillingClient.BillingResponseCode.OK) {
|
|
289
|
+
onError(toPurchasesError(result)); return@queryPurchasesAsync
|
|
290
|
+
}
|
|
291
|
+
executor.execute {
|
|
292
|
+
// Validate each purchase against the backend; the backend reconciles
|
|
293
|
+
// entitlement state. Then refresh CustomerInfo from the repo.
|
|
294
|
+
val errors = mutableListOf<Throwable>()
|
|
295
|
+
for (p in purchases) {
|
|
296
|
+
runCatching {
|
|
297
|
+
for (productId in p.products) {
|
|
298
|
+
validatePurchaseWithBackend(productId, p.purchaseToken)
|
|
299
|
+
}
|
|
300
|
+
}.onFailure { errors.add(it) }
|
|
301
|
+
}
|
|
302
|
+
val repo = entitlementsRepo
|
|
303
|
+
val info = try {
|
|
304
|
+
repo?.refresh(emptySet()) ?: emptyCustomerInfo()
|
|
305
|
+
} catch (e: Exception) {
|
|
306
|
+
repo?.current() ?: emptyCustomerInfo()
|
|
307
|
+
}
|
|
308
|
+
if (errors.isNotEmpty() && purchases.isNotEmpty()) {
|
|
309
|
+
onError(PurchasesError.NetworkError("restore: ${errors.size}/${purchases.size} validate calls failed"))
|
|
310
|
+
} else {
|
|
311
|
+
onSuccess(info)
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
override fun logIn(
|
|
318
|
+
appUserID: String,
|
|
319
|
+
onSuccess: (CustomerInfo, created: Boolean) -> Unit,
|
|
320
|
+
onError: (PurchasesError) -> Unit,
|
|
321
|
+
) {
|
|
322
|
+
// RC parity: logIn switches the appUserID and pulls fresh state. The
|
|
323
|
+
// "created" flag is best-effort; without the RC-side user-map we mark
|
|
324
|
+
// it false (existing user). Backend identify endpoints can be added
|
|
325
|
+
// later if needed.
|
|
326
|
+
explicitAppUserId = appUserID
|
|
327
|
+
val repo = entitlementsRepo
|
|
328
|
+
repo?.invalidate()
|
|
329
|
+
executor.execute {
|
|
330
|
+
runCatching { repo?.refresh(emptySet()) ?: emptyCustomerInfo() }
|
|
331
|
+
.onSuccess { onSuccess(it, false) }
|
|
332
|
+
.onFailure { onError(toPurchasesError(it)) }
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
override fun logOut(
|
|
337
|
+
onSuccess: (CustomerInfo) -> Unit,
|
|
338
|
+
onError: (PurchasesError) -> Unit,
|
|
339
|
+
) {
|
|
340
|
+
if (explicitAppUserId == null) {
|
|
341
|
+
onError(PurchasesError(PurchasesErrorCode.LogOutAnonymousUserError, "Already anonymous"))
|
|
342
|
+
return
|
|
343
|
+
}
|
|
344
|
+
explicitAppUserId = null
|
|
345
|
+
anonymousAppUserId = "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
|
|
346
|
+
val repo = entitlementsRepo
|
|
347
|
+
repo?.invalidate()
|
|
348
|
+
onSuccess(emptyCustomerInfo())
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
override fun setLogLevel(level: LogLevel) {
|
|
352
|
+
// Play Billing doesn't expose a log-level knob (it logs to logcat
|
|
353
|
+
// unconditionally). We retain the call for parity but do nothing.
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
override fun addCustomerInfoListener(listener: (CustomerInfo) -> Unit) {
|
|
357
|
+
customerInfoListeners.add(listener)
|
|
358
|
+
entitlementsRepo?.addListener(listener)
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
override fun removeCustomerInfoListener(listener: (CustomerInfo) -> Unit) {
|
|
362
|
+
customerInfoListeners.remove(listener)
|
|
363
|
+
entitlementsRepo?.removeListener(listener)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// --- PurchasesUpdatedListener -----------------------------------------
|
|
367
|
+
|
|
368
|
+
override fun onPurchasesUpdated(result: BillingResult, purchases: MutableList<Purchase>?) {
|
|
369
|
+
val pending = pendingPurchase
|
|
370
|
+
pendingPurchase = null
|
|
371
|
+
val code = result.responseCode
|
|
372
|
+
if (code == BillingClient.BillingResponseCode.USER_CANCELED) {
|
|
373
|
+
pending?.onError?.invoke(PurchasesError.PurchaseCancelled(), true); return
|
|
374
|
+
}
|
|
375
|
+
if (code != BillingClient.BillingResponseCode.OK) {
|
|
376
|
+
pending?.onError?.invoke(toPurchasesError(result), false); return
|
|
377
|
+
}
|
|
378
|
+
if (purchases.isNullOrEmpty()) {
|
|
379
|
+
pending?.onError?.invoke(PurchasesError.PurchaseInvalid("Empty purchases list"), false); return
|
|
380
|
+
}
|
|
381
|
+
val purchase = purchases.firstOrNull { p ->
|
|
382
|
+
pending != null && pending.productId in p.products
|
|
383
|
+
} ?: purchases.first()
|
|
384
|
+
executor.execute {
|
|
385
|
+
try {
|
|
386
|
+
validatePurchaseWithBackend(pending?.productId ?: purchase.products.first(), purchase.purchaseToken)
|
|
387
|
+
if (!purchase.isAcknowledged) acknowledge(purchase)
|
|
388
|
+
val repo = entitlementsRepo
|
|
389
|
+
val info = runCatching { repo?.refresh(emptySet()) }.getOrNull()
|
|
390
|
+
?: repo?.current()
|
|
391
|
+
?: emptyCustomerInfo()
|
|
392
|
+
pending?.onSuccess?.invoke(
|
|
393
|
+
StoreTransactionResult(
|
|
394
|
+
transaction = purchase.toStoreTransaction(),
|
|
395
|
+
customerInfo = info,
|
|
396
|
+
)
|
|
397
|
+
)
|
|
398
|
+
} catch (e: Exception) {
|
|
399
|
+
pending?.onError?.invoke(toPurchasesError(e), false)
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// --- Connection management ---------------------------------------------
|
|
405
|
+
|
|
406
|
+
@VisibleForTesting
|
|
407
|
+
internal fun connect() {
|
|
408
|
+
val client = billingClient ?: return
|
|
409
|
+
client.startConnection(object : BillingClientStateListener {
|
|
410
|
+
override fun onBillingSetupFinished(result: BillingResult) {
|
|
411
|
+
if (result.responseCode == BillingClient.BillingResponseCode.OK) {
|
|
412
|
+
reconnectAttempt.set(0)
|
|
413
|
+
} else {
|
|
414
|
+
scheduleReconnect()
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
override fun onBillingServiceDisconnected() {
|
|
419
|
+
scheduleReconnect()
|
|
420
|
+
}
|
|
421
|
+
})
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
private fun scheduleReconnect() {
|
|
425
|
+
val n = reconnectAttempt.getAndIncrement()
|
|
426
|
+
if (n >= MAX_RECONNECT_ATTEMPTS) {
|
|
427
|
+
Log.w(TAG, "BillingClient reconnect cap reached after $n attempts")
|
|
428
|
+
return
|
|
429
|
+
}
|
|
430
|
+
val delayMs = 1000L shl n // 1s, 2s, 4s, 8s, 16s
|
|
431
|
+
reconnectScheduler.schedule(delayMs) { connect() }
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// --- Backend HTTP ------------------------------------------------------
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* POST /api/sdk/subscriptions/validate with the Play purchase. Backend
|
|
438
|
+
* validates against Google's Real-Time Developer Notifications channel
|
|
439
|
+
* and the Play Developer API. Returns when the backend ack'd; throws on
|
|
440
|
+
* non-2xx.
|
|
441
|
+
*/
|
|
442
|
+
@Throws(IOException::class)
|
|
443
|
+
private fun validatePurchaseWithBackend(productId: String, purchaseToken: String) {
|
|
444
|
+
val body = JSONObject().apply {
|
|
445
|
+
put("user_id", getAppUserID())
|
|
446
|
+
put("product_id", productId)
|
|
447
|
+
put("purchase_token", purchaseToken)
|
|
448
|
+
put("store", "play")
|
|
449
|
+
}.toString()
|
|
450
|
+
// Round-D auth audit: the backend `/api/sdk/subscriptions/validate`
|
|
451
|
+
// route uses `withApiKeyAuth` (X-API-Key header). Pre-Round-D we
|
|
452
|
+
// sent `Authorization: Bearer ...` which the route ignored — every
|
|
453
|
+
// validate POST was returning 401 in production. Aligning with the
|
|
454
|
+
// backend contract here.
|
|
455
|
+
httpClient.post(
|
|
456
|
+
url = "$serverUrl/api/sdk/subscriptions/validate",
|
|
457
|
+
body = body,
|
|
458
|
+
headers = mapOf(
|
|
459
|
+
"X-API-Key" to apiKey,
|
|
460
|
+
"Content-Type" to "application/json",
|
|
461
|
+
),
|
|
462
|
+
)
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
private fun acknowledge(purchase: Purchase) {
|
|
466
|
+
val client = billingClient ?: return
|
|
467
|
+
val params = AcknowledgePurchaseParams.newBuilder()
|
|
468
|
+
.setPurchaseToken(purchase.purchaseToken)
|
|
469
|
+
.build()
|
|
470
|
+
client.acknowledgePurchase(params) { /* fire-and-forget; failures will
|
|
471
|
+
be re-tried on next purchase or via the backend's pull job */ }
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
private fun Purchase.toStoreTransaction(): StoreTransaction = object : StoreTransaction {
|
|
475
|
+
override val productIdentifier: String = products.firstOrNull().orEmpty()
|
|
476
|
+
override val transactionIdentifier: String = orderId.orEmpty()
|
|
477
|
+
override val purchaseDate: Date = Date(purchaseTime)
|
|
478
|
+
override val purchaseToken: String = this@toStoreTransaction.purchaseToken
|
|
479
|
+
override val quantity: Int = this@toStoreTransaction.quantity
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
private fun emptyCustomerInfo(): CustomerInfo = SimpleCustomerInfo(
|
|
483
|
+
entitlements = SimpleEntitlementInfos(emptyMap(), emptyMap(), VerificationResult.NOT_REQUESTED),
|
|
484
|
+
originalAppUserId = getAppUserID(),
|
|
485
|
+
firstSeen = Date(),
|
|
486
|
+
originalPurchaseDate = null,
|
|
487
|
+
latestExpirationDate = null,
|
|
488
|
+
allPurchaseDates = emptyMap(),
|
|
489
|
+
activeSubscriptions = emptySet(),
|
|
490
|
+
allPurchasedProductIds = emptySet(),
|
|
491
|
+
managementURL = null,
|
|
492
|
+
requestDate = Date(),
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
private data class PendingPurchase(
|
|
496
|
+
val productId: String,
|
|
497
|
+
val onSuccess: (StoreTransactionResult) -> Unit,
|
|
498
|
+
val onError: (PurchasesError, Boolean) -> Unit,
|
|
499
|
+
)
|
|
500
|
+
|
|
501
|
+
companion object {
|
|
502
|
+
private const val TAG = "SwissKnife.Billing"
|
|
503
|
+
@VisibleForTesting internal const val MAX_RECONNECT_ATTEMPTS = 5
|
|
504
|
+
|
|
505
|
+
/** Map Play Billing error codes to our [PurchasesError] hierarchy. */
|
|
506
|
+
@VisibleForTesting
|
|
507
|
+
internal fun toPurchasesError(result: BillingResult): PurchasesError {
|
|
508
|
+
val msg = result.debugMessage.ifEmpty { "Play Billing error" }
|
|
509
|
+
return when (result.responseCode) {
|
|
510
|
+
BillingClient.BillingResponseCode.USER_CANCELED -> PurchasesError.PurchaseCancelled(msg)
|
|
511
|
+
BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE,
|
|
512
|
+
BillingClient.BillingResponseCode.SERVICE_DISCONNECTED,
|
|
513
|
+
BillingClient.BillingResponseCode.NETWORK_ERROR -> PurchasesError.NetworkError(msg)
|
|
514
|
+
BillingClient.BillingResponseCode.ITEM_UNAVAILABLE -> PurchasesError.ProductNotAvailable(msg)
|
|
515
|
+
BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED -> PurchasesError.ReceiptAlreadyInUse(msg)
|
|
516
|
+
BillingClient.BillingResponseCode.DEVELOPER_ERROR -> PurchasesError(PurchasesErrorCode.ConfigurationError, msg)
|
|
517
|
+
BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED -> PurchasesError(PurchasesErrorCode.UnsupportedError, msg)
|
|
518
|
+
BillingClient.BillingResponseCode.BILLING_UNAVAILABLE -> PurchasesError(PurchasesErrorCode.PurchaseNotAllowedError, msg)
|
|
519
|
+
else -> PurchasesError.StoreProblem(msg)
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
private fun BillingResult.isUserCancelled() =
|
|
524
|
+
responseCode == BillingClient.BillingResponseCode.USER_CANCELED
|
|
525
|
+
|
|
526
|
+
private fun toPurchasesError(t: Throwable): PurchasesError = when (t) {
|
|
527
|
+
is PurchasesError -> t
|
|
528
|
+
is IOException -> PurchasesError.NetworkError(t.message ?: "Network error", t)
|
|
529
|
+
else -> PurchasesError.Unknown(t.message ?: "Unknown error", t)
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// --- HTTP + reconnect pluggable seams (for tests) -------------------------
|
|
535
|
+
|
|
536
|
+
/** HTTP backend abstraction so tests can inject a fake without spinning up
|
|
537
|
+
* MockWebServer for every gateway test.
|
|
538
|
+
*
|
|
539
|
+
* Round-D: the default impl is [com.appswissknife.net.BackendHttpClientAdapter]
|
|
540
|
+
* which routes through the unified [com.appswissknife.net.BackendHttpClient]
|
|
541
|
+
* transport. The previous direct-connection impl was removed so the only
|
|
542
|
+
* file that touches the low-level transport is the unified Net layer
|
|
543
|
+
* itself (single transport invariant). */
|
|
544
|
+
interface BillingHttpClient {
|
|
545
|
+
@Throws(IOException::class)
|
|
546
|
+
fun post(url: String, body: String, headers: Map<String, String>): String
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Schedule a delayed task. Tests use a synchronous-immediate impl to
|
|
550
|
+
* exercise reconnect logic without sleeping. */
|
|
551
|
+
interface ReconnectScheduler {
|
|
552
|
+
fun schedule(delayMs: Long, block: () -> Unit)
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
internal class HandlerReconnectScheduler : ReconnectScheduler {
|
|
556
|
+
private val handler = Handler(Looper.getMainLooper())
|
|
557
|
+
override fun schedule(delayMs: Long, block: () -> Unit) {
|
|
558
|
+
handler.postDelayed(block, delayMs)
|
|
559
|
+
}
|
|
560
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt
|
|
2
|
+
//
|
|
3
|
+
// Play Billing implementation of [PriceEnrichmentProvider]. All Play Billing
|
|
4
|
+
// types (BillingClient, ProductDetails, QueryProductDetailsParams) are confined
|
|
5
|
+
// to this file + BillingClientGateway, so OfferingsRepository stays store-
|
|
6
|
+
// agnostic. Extracted from OfferingsRepository in the store-abstraction refactor.
|
|
7
|
+
package com.appswissknife.purchases
|
|
8
|
+
|
|
9
|
+
import android.util.Log
|
|
10
|
+
import com.android.billingclient.api.BillingClient
|
|
11
|
+
import com.android.billingclient.api.ProductDetails
|
|
12
|
+
import com.android.billingclient.api.QueryProductDetailsParams
|
|
13
|
+
import com.appswissknife.models.Price
|
|
14
|
+
import com.appswissknife.models.StoreProduct
|
|
15
|
+
import com.appswissknife.models.StoreProductDiscount
|
|
16
|
+
import com.appswissknife.models.SubscriptionPeriod
|
|
17
|
+
import com.appswissknife.offerings.SimplePrice
|
|
18
|
+
|
|
19
|
+
class PlayPriceEnrichmentProvider(
|
|
20
|
+
private val billingClientProvider: () -> BillingClient?,
|
|
21
|
+
) : PriceEnrichmentProvider {
|
|
22
|
+
|
|
23
|
+
override fun platformTags(): Set<String> = setOf("play", "android")
|
|
24
|
+
|
|
25
|
+
override fun enrich(products: Map<String, String>): Map<String, StoreProduct> {
|
|
26
|
+
if (products.isEmpty()) return emptyMap()
|
|
27
|
+
val details = loadProductDetails(products.keys.toList())
|
|
28
|
+
return details.mapValues { (id, pd) -> StoreProductFromPlayBilling(pd, products[id].orEmpty()) }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Query live [ProductDetails] for [productIds]. Blocks (≤5s) on Play's async
|
|
33
|
+
* callback via a latch — the caller is already on a background thread
|
|
34
|
+
* (OfferingsRepository fetch thread), matching the pre-refactor contract.
|
|
35
|
+
*/
|
|
36
|
+
private fun loadProductDetails(productIds: List<String>): Map<String, ProductDetails> {
|
|
37
|
+
val client = billingClientProvider() ?: return emptyMap()
|
|
38
|
+
if (!client.isReady) return emptyMap()
|
|
39
|
+
if (productIds.isEmpty()) return emptyMap()
|
|
40
|
+
val params = QueryProductDetailsParams.newBuilder()
|
|
41
|
+
.setProductList(productIds.map { pid ->
|
|
42
|
+
QueryProductDetailsParams.Product.newBuilder()
|
|
43
|
+
.setProductId(pid)
|
|
44
|
+
.setProductType(BillingClient.ProductType.SUBS)
|
|
45
|
+
.build()
|
|
46
|
+
})
|
|
47
|
+
.build()
|
|
48
|
+
val latch = java.util.concurrent.CountDownLatch(1)
|
|
49
|
+
var result: Map<String, ProductDetails> = emptyMap()
|
|
50
|
+
client.queryProductDetailsAsync(params) { billingResult, productDetailsResult ->
|
|
51
|
+
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
|
|
52
|
+
result = productDetailsResult.productDetailsList.associateBy { it.productId }
|
|
53
|
+
} else {
|
|
54
|
+
Log.w(TAG, "queryProductDetailsAsync returned ${billingResult.responseCode}: ${billingResult.debugMessage}")
|
|
55
|
+
}
|
|
56
|
+
latch.countDown()
|
|
57
|
+
}
|
|
58
|
+
runCatching { latch.await(5, java.util.concurrent.TimeUnit.SECONDS) }
|
|
59
|
+
return result
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
companion object {
|
|
63
|
+
private const val TAG = "SwissKnife.Offerings"
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** StoreProduct sourced from a Play Billing ProductDetails — used whenever the
|
|
68
|
+
* BillingClient returned live data. */
|
|
69
|
+
private class StoreProductFromPlayBilling(
|
|
70
|
+
private val pd: ProductDetails,
|
|
71
|
+
private val backendName: String,
|
|
72
|
+
) : StoreProduct {
|
|
73
|
+
override val id: String = pd.productId
|
|
74
|
+
override val localizedTitle: String = pd.title.ifEmpty { backendName }
|
|
75
|
+
override val localizedDescription: String = pd.description
|
|
76
|
+
override val price: Price by lazy {
|
|
77
|
+
val phase = pd.subscriptionOfferDetails?.firstOrNull()?.pricingPhases?.pricingPhaseList?.lastOrNull()
|
|
78
|
+
if (phase != null) {
|
|
79
|
+
SimplePrice(
|
|
80
|
+
formatted = phase.formattedPrice,
|
|
81
|
+
currencyCode = phase.priceCurrencyCode,
|
|
82
|
+
amountMicros = phase.priceAmountMicros,
|
|
83
|
+
)
|
|
84
|
+
} else {
|
|
85
|
+
val one = pd.oneTimePurchaseOfferDetails
|
|
86
|
+
if (one != null) {
|
|
87
|
+
SimplePrice(
|
|
88
|
+
formatted = one.formattedPrice,
|
|
89
|
+
currencyCode = one.priceCurrencyCode,
|
|
90
|
+
amountMicros = one.priceAmountMicros,
|
|
91
|
+
)
|
|
92
|
+
} else {
|
|
93
|
+
SimplePrice(formatted = "", currencyCode = "", amountMicros = 0L)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
override val subscriptionPeriod: SubscriptionPeriod? = null
|
|
98
|
+
override val introductoryDiscount: StoreProductDiscount? = null
|
|
99
|
+
override val discounts: List<StoreProductDiscount> = emptyList()
|
|
100
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt
|
|
2
|
+
package com.appswissknife.purchases
|
|
3
|
+
|
|
4
|
+
import com.appswissknife.models.StoreProduct
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Store-agnostic seam for enriching backend paywall products with live,
|
|
8
|
+
* store-sourced pricing. Lets [com.appswissknife.offerings.OfferingsRepository]
|
|
9
|
+
* stay free of any concrete store SDK (Play Billing, RuStore, …): the
|
|
10
|
+
* repository knows the backend product set; a per-store provider supplies the
|
|
11
|
+
* live prices and tells the repository which backend `platform` rows belong to
|
|
12
|
+
* the active store.
|
|
13
|
+
*
|
|
14
|
+
* The Play implementation is [PlayPriceEnrichmentProvider] (Play types confined
|
|
15
|
+
* there). The optional RuStore add-on ships its own implementation.
|
|
16
|
+
*
|
|
17
|
+
* All types crossing this interface are own `com.appswissknife.models.*` types —
|
|
18
|
+
* no store SDK types leak.
|
|
19
|
+
*/
|
|
20
|
+
interface PriceEnrichmentProvider {
|
|
21
|
+
/**
|
|
22
|
+
* The backend `platform` tag(s) whose products belong to this store, matched
|
|
23
|
+
* case-insensitively. Play → {"play","android"}; RuStore → {"rustore"}.
|
|
24
|
+
*/
|
|
25
|
+
fun platformTags(): Set<String>
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Enrich the given products with live store pricing.
|
|
29
|
+
* @param products productId → fallback display name (used when the store
|
|
30
|
+
* returns no localized title).
|
|
31
|
+
* @return enriched [StoreProduct]s keyed by productId, for the ids this
|
|
32
|
+
* provider could resolve. Ids it can't resolve are omitted; the caller
|
|
33
|
+
* falls back to the backend-priced product.
|
|
34
|
+
*/
|
|
35
|
+
fun enrich(products: Map<String, String>): Map<String, StoreProduct>
|
|
36
|
+
}
|