@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.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/CHANGELOG.md +385 -2
- package/LICENSE +21 -0
- package/README.md +229 -42
- package/SwissKnifePurchases.podspec +1 -1
- package/android/build.gradle +24 -2
- package/android/consumer-rules.pro +12 -0
- package/android/src/main/AndroidManifest.xml +15 -1
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
- package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
- package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
- package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
- package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
- package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
- package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
- package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
- package/android/vendor-rustore/AndroidManifest.xml +59 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
- package/app.plugin.js +287 -0
- package/ios/SwissKnifePurchases.m +20 -0
- package/ios/SwissKnifePurchases.swift +97 -3
- package/ios/SwissKnifePushBootstrap.m +34 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
- package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
- package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
- package/lib/commonjs/attribution.js +4 -3
- package/lib/commonjs/attribution.js.map +1 -1
- package/lib/commonjs/identity.js +12 -11
- package/lib/commonjs/identity.js.map +1 -1
- package/lib/commonjs/index.js +16 -5
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/internal/config.js +105 -8
- package/lib/commonjs/internal/config.js.map +1 -1
- package/lib/commonjs/internal/telemetry-context.js +70 -0
- package/lib/commonjs/internal/telemetry-context.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +18 -25
- package/lib/commonjs/modules/analytics.js.map +1 -1
- package/lib/commonjs/modules/crash-reporting.js +27 -6
- package/lib/commonjs/modules/crash-reporting.js.map +1 -1
- package/lib/commonjs/modules/log.js +1 -1
- package/lib/commonjs/modules/notifications.js +500 -0
- package/lib/commonjs/modules/notifications.js.map +1 -0
- package/lib/commonjs/modules/performance.js +57 -8
- package/lib/commonjs/modules/performance.js.map +1 -1
- package/lib/commonjs/native/module.js +6 -0
- package/lib/commonjs/native/module.js.map +1 -1
- package/lib/commonjs/native/spec.js +12 -5
- package/lib/commonjs/native/spec.js.map +1 -1
- package/lib/commonjs/purchases.js +4 -4
- package/lib/commonjs/types.js +12 -15
- package/lib/commonjs/types.js.map +1 -1
- package/lib/module/attribution.js +4 -3
- package/lib/module/attribution.js.map +1 -1
- package/lib/module/identity.js +12 -11
- package/lib/module/identity.js.map +1 -1
- package/lib/module/index.js +8 -4
- package/lib/module/index.js.map +1 -1
- package/lib/module/internal/config.js +103 -8
- package/lib/module/internal/config.js.map +1 -1
- package/lib/module/internal/telemetry-context.js +63 -0
- package/lib/module/internal/telemetry-context.js.map +1 -0
- package/lib/module/modules/analytics.js +18 -25
- package/lib/module/modules/analytics.js.map +1 -1
- package/lib/module/modules/crash-reporting.js +27 -6
- package/lib/module/modules/crash-reporting.js.map +1 -1
- package/lib/module/modules/log.js +1 -1
- package/lib/module/modules/notifications.js +491 -0
- package/lib/module/modules/notifications.js.map +1 -0
- package/lib/module/modules/performance.js +57 -8
- package/lib/module/modules/performance.js.map +1 -1
- package/lib/module/native/module.js +6 -1
- package/lib/module/native/module.js.map +1 -1
- package/lib/module/native/spec.js +11 -4
- package/lib/module/native/spec.js.map +1 -1
- package/lib/module/purchases.js +4 -4
- package/lib/module/types.js +12 -15
- package/lib/module/types.js.map +1 -1
- package/lib/typescript/commonjs/attribution.d.ts +3 -2
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
- package/lib/typescript/commonjs/identity.d.ts.map +1 -1
- package/lib/typescript/commonjs/index.d.ts +2 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/config.d.ts +16 -2
- package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
- package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/module.d.ts +2 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/spec.d.ts +33 -4
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
- package/lib/typescript/commonjs/purchases.d.ts +4 -4
- package/lib/typescript/commonjs/types.d.ts +4 -5
- package/lib/typescript/commonjs/types.d.ts.map +1 -1
- package/lib/typescript/module/attribution.d.ts +3 -2
- package/lib/typescript/module/attribution.d.ts.map +1 -1
- package/lib/typescript/module/identity.d.ts.map +1 -1
- package/lib/typescript/module/index.d.ts +2 -0
- package/lib/typescript/module/index.d.ts.map +1 -1
- package/lib/typescript/module/internal/config.d.ts +16 -2
- package/lib/typescript/module/internal/config.d.ts.map +1 -1
- package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +8 -11
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/module/modules/notifications.d.ts +110 -0
- package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +13 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -1
- package/lib/typescript/module/native/module.d.ts +2 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -1
- package/lib/typescript/module/native/spec.d.ts +33 -4
- package/lib/typescript/module/native/spec.d.ts.map +1 -1
- package/lib/typescript/module/purchases.d.ts +4 -4
- package/lib/typescript/module/types.d.ts +4 -5
- package/lib/typescript/module/types.d.ts.map +1 -1
- package/package.json +12 -4
- package/src/attribution.ts +4 -3
- package/src/identity.ts +12 -11
- package/src/index.ts +16 -4
- package/src/internal/config.ts +113 -8
- package/src/internal/telemetry-context.ts +76 -0
- package/src/modules/analytics.ts +24 -33
- package/src/modules/crash-reporting.ts +50 -9
- package/src/modules/log.ts +1 -1
- package/src/modules/notifications.ts +557 -0
- package/src/modules/performance.ts +94 -14
- package/src/native/module.ts +6 -0
- package/src/native/spec.ts +45 -10
- package/src/purchases.ts +4 -4
- package/src/types.ts +12 -15
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
|
@@ -6,23 +6,46 @@
|
|
|
6
6
|
// Architecture:
|
|
7
7
|
// - Owns a single BillingClient connected via startConnection. Connection
|
|
8
8
|
// errors trigger exponential backoff reconnect (1s/2s/4s/8s/16s, cap 5).
|
|
9
|
+
// A purchase or restore that finds the client not ready resets that budget,
|
|
10
|
+
// reconnects, and runs once the client is connected.
|
|
11
|
+
// - Every OK setup (the first one comes from configure) reconciles: it
|
|
12
|
+
// queries SUBS and INAPP purchases and validates + acknowledges each
|
|
13
|
+
// PURCHASED one that is still unacknowledged, under the user id stamped on
|
|
14
|
+
// it at launch when there is one. Google auto-refunds an
|
|
15
|
+
// unacknowledged purchase after three days, and nothing server-side
|
|
16
|
+
// acknowledges on our behalf, so an ack lost to a network error or a
|
|
17
|
+
// process kill must be picked up here.
|
|
18
|
+
// - Only purchaseState == PURCHASED is validated or acknowledged. A PENDING
|
|
19
|
+
// purchase (cash, deferred payment) is reported to the in-flight call as
|
|
20
|
+
// PaymentPending; Play re-delivers it when the payment clears.
|
|
9
21
|
// - All Play Billing callbacks are invoked on Play's executor (not main);
|
|
10
22
|
// we surface them as-is - the gateway interface contract is "callbacks
|
|
11
23
|
// may fire on any thread."
|
|
12
24
|
// - Every successful purchase round-trips through our backend at
|
|
13
25
|
// /api/sdk/subscriptions/validate before being surfaced as success. The
|
|
14
26
|
// backend is authoritative for entitlement state per the locked decision.
|
|
15
|
-
// - CustomerInfo reads delegate to EntitlementsRepository (24h cache).
|
|
27
|
+
// - CustomerInfo reads delegate to EntitlementsRepository (24h cache). Every
|
|
28
|
+
// validation the backend accepts (a purchase, a reconcile, a pending
|
|
29
|
+
// purchase that cleared, a restore) re-reads the entitlements into that
|
|
30
|
+
// cache, which tells the CustomerInfo listeners.
|
|
31
|
+
// - Subscriptions (SUBS) and one-time products (INAPP) alike: Play takes a
|
|
32
|
+
// product type on every query, so purchases and restores ask for both.
|
|
16
33
|
//
|
|
17
34
|
// What's intentionally NOT here:
|
|
18
35
|
// - logIn/logOut don't actually exist in Play Billing - the SDK identity
|
|
19
36
|
// model is ours, kept in [EntitlementsRepository.invalidate()] + a
|
|
20
37
|
// userId mutable. We honor RC parity by exposing them on the gateway.
|
|
21
|
-
// - Offerings/products fetching - that's OfferingsRepository
|
|
22
|
-
// This gateway only queries
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
//
|
|
38
|
+
// - Offerings/products fetching - that's OfferingsRepository, which
|
|
39
|
+
// SwissKnife.getOfferings() reads. This gateway only queries
|
|
40
|
+
// ProductDetails on-demand for purchase.
|
|
41
|
+
// - Acknowledge details: we acknowledge() every purchased product,
|
|
42
|
+
// consumables included, and never consume() one: the backend's product
|
|
43
|
+
// type is not known here, and consuming a non-consumable would take a
|
|
44
|
+
// lifetime unlock away from the user. An acknowledged consumable stays
|
|
45
|
+
// owned on Play until something consumes it.
|
|
46
|
+
// acknowledge() checks the BillingResult and retries a non-OK answer a
|
|
47
|
+
// bounded number of times; what is still unacknowledged after that is left
|
|
48
|
+
// to the next reconcile.
|
|
26
49
|
|
|
27
50
|
package com.appswissknife.purchases
|
|
28
51
|
|
|
@@ -62,10 +85,13 @@ import java.io.IOException
|
|
|
62
85
|
import java.util.Collections
|
|
63
86
|
import java.util.Date
|
|
64
87
|
import java.util.UUID
|
|
88
|
+
import java.util.concurrent.CountDownLatch
|
|
65
89
|
import java.util.concurrent.ExecutorService
|
|
66
90
|
import java.util.concurrent.Executors
|
|
91
|
+
import java.util.concurrent.TimeUnit
|
|
67
92
|
import java.util.concurrent.atomic.AtomicBoolean
|
|
68
93
|
import java.util.concurrent.atomic.AtomicInteger
|
|
94
|
+
import java.util.concurrent.atomic.AtomicReference
|
|
69
95
|
|
|
70
96
|
/**
|
|
71
97
|
* Production [PurchasesGateway] using Google Play Billing v8 directly. No
|
|
@@ -103,12 +129,28 @@ class BillingClientGateway(
|
|
|
103
129
|
* dies. That is precisely why it must not be the normal path; see
|
|
104
130
|
* [getAppUserID].
|
|
105
131
|
*/
|
|
106
|
-
@Volatile private var fallbackAnonymousAppUserId: String =
|
|
107
|
-
"\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
|
|
132
|
+
@Volatile private var fallbackAnonymousAppUserId: String = newFallbackAnonymousId()
|
|
108
133
|
|
|
109
134
|
private val configured = AtomicBoolean(false)
|
|
110
135
|
private val reconnectAttempt = AtomicInteger(0)
|
|
111
136
|
|
|
137
|
+
/**
|
|
138
|
+
* Calls waiting for the client to connect: a purchase or restore that found
|
|
139
|
+
* it not ready. Drained by the next setup result, or failed by a timeout.
|
|
140
|
+
*/
|
|
141
|
+
private val readyWaiters = mutableListOf<ReadyWaiter>()
|
|
142
|
+
|
|
143
|
+
/** One reconcile at a time; setups that land while one runs are covered by it. */
|
|
144
|
+
private val reconcileInFlight = AtomicBoolean(false)
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Purchase tokens whose acknowledgement is in flight or succeeded in this
|
|
148
|
+
* process. Purchase objects are snapshots, so `isAcknowledged` can be stale
|
|
149
|
+
* when the purchase listener and a reconcile see the same purchase; this
|
|
150
|
+
* keeps them from acknowledging (and re-validating) it twice.
|
|
151
|
+
*/
|
|
152
|
+
private val ackClaimed: MutableSet<String> = Collections.synchronizedSet(mutableSetOf())
|
|
153
|
+
|
|
112
154
|
private val executor: ExecutorService =
|
|
113
155
|
Executors.newSingleThreadExecutor { r -> Thread(r, "swissknife-billing").apply { isDaemon = true } }
|
|
114
156
|
|
|
@@ -153,30 +195,69 @@ class BillingClientGateway(
|
|
|
153
195
|
userIdProvider = { getAppUserID() },
|
|
154
196
|
)
|
|
155
197
|
this.entitlementsRepo = repo
|
|
198
|
+
// A listener added before configure was only kept here; the repository is
|
|
199
|
+
// what announces each refresh, so hand it over.
|
|
200
|
+
synchronized(customerInfoListeners) { customerInfoListeners.toList() }.forEach(repo::addListener)
|
|
156
201
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
PendingPurchasesParams.newBuilder()
|
|
161
|
-
.enableOneTimeProducts()
|
|
162
|
-
.enablePrepaidPlans()
|
|
163
|
-
.build()
|
|
164
|
-
)
|
|
165
|
-
.build()
|
|
166
|
-
this.billingClient = client
|
|
202
|
+
this.billingClient = billingClientFactory(appContext, this)
|
|
203
|
+
// The first OK setup reconciles purchases left unacknowledged by an
|
|
204
|
+
// earlier process (see [reconcilePurchases]).
|
|
167
205
|
connect()
|
|
168
206
|
}
|
|
169
207
|
|
|
170
|
-
/**
|
|
171
|
-
*
|
|
172
|
-
*
|
|
208
|
+
/**
|
|
209
|
+
* Test seam: builds the [BillingClient]. Production builds Play's client;
|
|
210
|
+
* JVM tests hand back a fake so connection, reconcile and acknowledge paths
|
|
211
|
+
* run without Play.
|
|
212
|
+
*/
|
|
213
|
+
@VisibleForTesting
|
|
214
|
+
internal var billingClientFactory: (Context, PurchasesUpdatedListener) -> BillingClient =
|
|
215
|
+
{ context, listener ->
|
|
216
|
+
BillingClient.newBuilder(context)
|
|
217
|
+
.setListener(listener)
|
|
218
|
+
.enablePendingPurchases(
|
|
219
|
+
PendingPurchasesParams.newBuilder()
|
|
220
|
+
.enableOneTimeProducts()
|
|
221
|
+
.enablePrepaidPlans()
|
|
222
|
+
.build()
|
|
223
|
+
)
|
|
224
|
+
.build()
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The BillingClient this gateway owns, connected or not (tests observe it). */
|
|
173
228
|
@VisibleForTesting
|
|
174
229
|
internal fun billingClientOrNull(): BillingClient? = billingClient
|
|
175
230
|
|
|
176
231
|
/** Play Billing price enrichment for OfferingsRepository (Play types stay in
|
|
177
|
-
* [PlayPriceEnrichmentProvider]).
|
|
232
|
+
* [PlayPriceEnrichmentProvider]). It waits, bounded, for a connection in
|
|
233
|
+
* progress: an app that calls getOfferings() right after configure would
|
|
234
|
+
* otherwise find Play not connected yet and get no Play prices. */
|
|
178
235
|
override fun priceEnrichmentProvider(): PriceEnrichmentProvider =
|
|
179
|
-
PlayPriceEnrichmentProvider {
|
|
236
|
+
PlayPriceEnrichmentProvider { readyClientOrNull(PRICE_CONNECT_WAIT_MS) }
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* The connected client, waiting up to [timeoutMs] for it to connect (and
|
|
240
|
+
* connecting it if it is not, as a purchase does). Null when there is no
|
|
241
|
+
* client, the setup fails, or it does not finish in time. Blocks: call it
|
|
242
|
+
* off the main thread, as the offerings fetch does.
|
|
243
|
+
*/
|
|
244
|
+
@VisibleForTesting
|
|
245
|
+
internal fun readyClientOrNull(timeoutMs: Long): BillingClient? {
|
|
246
|
+
val client = billingClient ?: return null
|
|
247
|
+
if (client.isReady) return client
|
|
248
|
+
val ready = AtomicReference<BillingClient?>(null)
|
|
249
|
+
val done = CountDownLatch(1)
|
|
250
|
+
withReadyClient(
|
|
251
|
+
onReady = { ready.set(it); done.countDown() },
|
|
252
|
+
onUnavailable = { done.countDown() },
|
|
253
|
+
)
|
|
254
|
+
try {
|
|
255
|
+
done.await(timeoutMs, TimeUnit.MILLISECONDS)
|
|
256
|
+
} catch (_: InterruptedException) {
|
|
257
|
+
Thread.currentThread().interrupt()
|
|
258
|
+
}
|
|
259
|
+
return ready.get()
|
|
260
|
+
}
|
|
180
261
|
|
|
181
262
|
override fun isConfigured(): Boolean = configured.get()
|
|
182
263
|
|
|
@@ -239,11 +320,12 @@ class BillingClientGateway(
|
|
|
239
320
|
onSuccess: (Offerings) -> Unit,
|
|
240
321
|
onError: (PurchasesError) -> Unit,
|
|
241
322
|
) {
|
|
242
|
-
//
|
|
243
|
-
//
|
|
244
|
-
//
|
|
245
|
-
onError(PurchasesError
|
|
246
|
-
|
|
323
|
+
// SwissKnife.getOfferings() reads offerings through the OfferingsRepository
|
|
324
|
+
// that configurePurchases wires for this gateway, so this is reached only
|
|
325
|
+
// when nothing is configured yet.
|
|
326
|
+
onError(PurchasesError(
|
|
327
|
+
PurchasesErrorCode.ConfigurationError,
|
|
328
|
+
"Offerings are available once SwissKnife.configure has run",
|
|
247
329
|
))
|
|
248
330
|
}
|
|
249
331
|
|
|
@@ -262,38 +344,25 @@ class BillingClientGateway(
|
|
|
262
344
|
onSuccess: (StoreTransactionResult) -> Unit,
|
|
263
345
|
onError: (PurchasesError, userCancelled: Boolean) -> Unit,
|
|
264
346
|
) {
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
347
|
+
withReadyClient(
|
|
348
|
+
onReady = { client -> launchPurchase(client, activity, product, onSuccess, onError) },
|
|
349
|
+
onUnavailable = { onError(it, false) },
|
|
350
|
+
)
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private fun launchPurchase(
|
|
354
|
+
client: BillingClient,
|
|
355
|
+
activity: Activity,
|
|
356
|
+
product: StoreProduct,
|
|
357
|
+
onSuccess: (StoreTransactionResult) -> Unit,
|
|
358
|
+
onError: (PurchasesError, userCancelled: Boolean) -> Unit,
|
|
359
|
+
) {
|
|
269
360
|
// Translate product into a Play Billing ProductDetails by re-querying.
|
|
270
361
|
// We pay a roundtrip cost per purchase but the alternative (caching
|
|
271
362
|
// ProductDetails graphs across the gateway boundary) leaks Play types.
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
// branch here on `product.subscriptionPeriod`, but for Phase 6 SUBS is
|
|
276
|
-
// the only path exercised; INAPP is left for follow-up.
|
|
277
|
-
val params = QueryProductDetailsParams.newBuilder()
|
|
278
|
-
.setProductList(
|
|
279
|
-
listOf(
|
|
280
|
-
QueryProductDetailsParams.Product.newBuilder()
|
|
281
|
-
.setProductId(product.id)
|
|
282
|
-
.setProductType(productType)
|
|
283
|
-
.build()
|
|
284
|
-
)
|
|
285
|
-
)
|
|
286
|
-
.build()
|
|
287
|
-
client.queryProductDetailsAsync(params) { result, productDetailsResult ->
|
|
288
|
-
if (result.responseCode != BillingClient.BillingResponseCode.OK) {
|
|
289
|
-
onError(toPurchasesError(result), result.isUserCancelled()); return@queryProductDetailsAsync
|
|
290
|
-
}
|
|
291
|
-
val productDetailsList = productDetailsResult.productDetailsList
|
|
292
|
-
val pd = productDetailsList.firstOrNull()
|
|
293
|
-
if (pd == null) {
|
|
294
|
-
onError(PurchasesError.ProductNotAvailable("No ProductDetails for ${product.id}"), false)
|
|
295
|
-
return@queryProductDetailsAsync
|
|
296
|
-
}
|
|
363
|
+
findProductDetails(client, product.id, productTypesFor(product), onError) { pd ->
|
|
364
|
+
// A subscription is bought through one of its offers. A one-time product
|
|
365
|
+
// needs no token: Play then sells its default purchase option.
|
|
297
366
|
val offerToken = pd.subscriptionOfferDetails?.firstOrNull()?.offerToken
|
|
298
367
|
val flowParamsBuilder = BillingFlowParams.ProductDetailsParams.newBuilder()
|
|
299
368
|
.setProductDetails(pd)
|
|
@@ -311,30 +380,90 @@ class BillingClientGateway(
|
|
|
311
380
|
}
|
|
312
381
|
}
|
|
313
382
|
|
|
383
|
+
/**
|
|
384
|
+
* Find [productId]'s ProductDetails, asking Play for it as each of [types]
|
|
385
|
+
* in turn. Play answers a query for the wrong product type with no details,
|
|
386
|
+
* not an error, so the next type is asked only then; a Play error ends the
|
|
387
|
+
* search.
|
|
388
|
+
*/
|
|
389
|
+
private fun findProductDetails(
|
|
390
|
+
client: BillingClient,
|
|
391
|
+
productId: String,
|
|
392
|
+
types: List<String>,
|
|
393
|
+
onError: (PurchasesError, userCancelled: Boolean) -> Unit,
|
|
394
|
+
onFound: (ProductDetails) -> Unit,
|
|
395
|
+
) {
|
|
396
|
+
val params = QueryProductDetailsParams.newBuilder()
|
|
397
|
+
.setProductList(
|
|
398
|
+
listOf(
|
|
399
|
+
QueryProductDetailsParams.Product.newBuilder()
|
|
400
|
+
.setProductId(productId)
|
|
401
|
+
.setProductType(types.first())
|
|
402
|
+
.build()
|
|
403
|
+
)
|
|
404
|
+
)
|
|
405
|
+
.build()
|
|
406
|
+
client.queryProductDetailsAsync(params) { result, productDetailsResult ->
|
|
407
|
+
if (result.responseCode != BillingClient.BillingResponseCode.OK) {
|
|
408
|
+
onError(toPurchasesError(result), result.isUserCancelled()); return@queryProductDetailsAsync
|
|
409
|
+
}
|
|
410
|
+
val pd = productDetailsResult.productDetailsList.firstOrNull { it.productId == productId }
|
|
411
|
+
when {
|
|
412
|
+
pd != null -> onFound(pd)
|
|
413
|
+
types.size > 1 -> findProductDetails(client, productId, types.drop(1), onError, onFound)
|
|
414
|
+
else -> onError(PurchasesError.ProductNotAvailable("No ProductDetails for $productId"), false)
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* The Play product types to ask for [product] as, the likelier first. A
|
|
421
|
+
* product the SDK priced knows whether it is one-time ([ProductKindHint]);
|
|
422
|
+
* any other (a host's own, or one the React Native bridge built from an id)
|
|
423
|
+
* is asked for as a subscription first, as before one-time products were
|
|
424
|
+
* supported, so a subscription costs no extra query.
|
|
425
|
+
*/
|
|
426
|
+
private fun productTypesFor(product: StoreProduct): List<String> =
|
|
427
|
+
if ((product as? ProductKindHint)?.isOneTime == true) {
|
|
428
|
+
listOf(BillingClient.ProductType.INAPP, BillingClient.ProductType.SUBS)
|
|
429
|
+
} else {
|
|
430
|
+
PRODUCT_TYPES
|
|
431
|
+
}
|
|
432
|
+
|
|
314
433
|
override fun restorePurchases(
|
|
315
434
|
onSuccess: (CustomerInfo) -> Unit,
|
|
316
435
|
onError: (PurchasesError) -> Unit,
|
|
317
436
|
) {
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
client
|
|
326
|
-
|
|
327
|
-
|
|
437
|
+
withReadyClient(
|
|
438
|
+
onReady = { client -> runRestore(client, onSuccess, onError) },
|
|
439
|
+
onUnavailable = onError,
|
|
440
|
+
)
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
private fun runRestore(
|
|
444
|
+
client: BillingClient,
|
|
445
|
+
onSuccess: (CustomerInfo) -> Unit,
|
|
446
|
+
onError: (PurchasesError) -> Unit,
|
|
447
|
+
) {
|
|
448
|
+
// Subscriptions and one-time products (lifetime unlocks, and consumables
|
|
449
|
+
// nothing has consumed). A Play error on either query fails the restore
|
|
450
|
+
// rather than reporting a partial one as complete.
|
|
451
|
+
queryOwnedPurchases(client, PRODUCT_TYPES, mutableListOf()) { purchases, failure ->
|
|
452
|
+
if (failure != null) {
|
|
453
|
+
onError(toPurchasesError(failure)); return@queryOwnedPurchases
|
|
328
454
|
}
|
|
329
455
|
executor.execute {
|
|
330
456
|
// Validate each purchase against the backend; the backend reconciles
|
|
331
457
|
// entitlement state. Then refresh CustomerInfo from the repo.
|
|
332
458
|
val errors = mutableListOf<Throwable>()
|
|
333
459
|
for (p in purchases) {
|
|
460
|
+
// A pending payment is not a purchase yet: never validate or ack it.
|
|
461
|
+
if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
|
|
334
462
|
runCatching {
|
|
335
463
|
for (productId in p.products) {
|
|
336
|
-
validatePurchaseWithBackend(productId, p.purchaseToken)
|
|
464
|
+
validatePurchaseWithBackend(p.packageName, productId, p.purchaseToken)
|
|
337
465
|
}
|
|
466
|
+
if (!p.isAcknowledged) acknowledge(p)
|
|
338
467
|
}.onFailure { errors.add(it) }
|
|
339
468
|
}
|
|
340
469
|
val repo = entitlementsRepo
|
|
@@ -344,7 +473,7 @@ class BillingClientGateway(
|
|
|
344
473
|
repo?.current() ?: emptyCustomerInfo()
|
|
345
474
|
}
|
|
346
475
|
if (errors.isNotEmpty() && purchases.isNotEmpty()) {
|
|
347
|
-
onError(
|
|
476
|
+
onError(toPurchasesError(errors.first()))
|
|
348
477
|
} else {
|
|
349
478
|
onSuccess(info)
|
|
350
479
|
}
|
|
@@ -365,9 +494,11 @@ class BillingClientGateway(
|
|
|
365
494
|
val repo = entitlementsRepo
|
|
366
495
|
repo?.invalidate()
|
|
367
496
|
executor.execute {
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
497
|
+
// The new user's entitlements. A read that fails does not fail the
|
|
498
|
+
// logIn (the identify call already went through): it answers with no
|
|
499
|
+
// entitlements, as it always did, and the next getCustomerInfo() reads
|
|
500
|
+
// them again.
|
|
501
|
+
onSuccess(refreshEntitlements() ?: emptyCustomerInfo(), false)
|
|
371
502
|
}
|
|
372
503
|
}
|
|
373
504
|
|
|
@@ -385,13 +516,36 @@ class BillingClientGateway(
|
|
|
385
516
|
// analytics stay continuous for the same physical install — same as iOS,
|
|
386
517
|
// where logOut also returns to the stable device anonymous id rather than
|
|
387
518
|
// inventing a new one.
|
|
388
|
-
fallbackAnonymousAppUserId =
|
|
389
|
-
"\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
|
|
519
|
+
fallbackAnonymousAppUserId = newFallbackAnonymousId()
|
|
390
520
|
val repo = entitlementsRepo
|
|
391
521
|
repo?.invalidate()
|
|
392
522
|
onSuccess(emptyCustomerInfo())
|
|
393
523
|
}
|
|
394
524
|
|
|
525
|
+
/**
|
|
526
|
+
* Back to the anonymous user after `Identity.reset()` / `Identity.wipe()`
|
|
527
|
+
* (see [PurchasesGateway.resetToAnonymous]). Unlike [logOut] it answers no
|
|
528
|
+
* call and has no "already anonymous" error: Identity has already moved on,
|
|
529
|
+
* and this makes the gateway agree. Play is not contacted.
|
|
530
|
+
*/
|
|
531
|
+
override fun resetToAnonymous() {
|
|
532
|
+
val droppedUser = explicitAppUserId
|
|
533
|
+
explicitAppUserId = null
|
|
534
|
+
fallbackAnonymousAppUserId = newFallbackAnonymousId()
|
|
535
|
+
entitlementsRepo?.invalidate()
|
|
536
|
+
if (droppedUser == null) return
|
|
537
|
+
// Taken now, while the subject is the anonymous id. Announced on the
|
|
538
|
+
// executor, after any entitlement read already running there, so the
|
|
539
|
+
// listeners hear the reset after that read's answer, never before it.
|
|
540
|
+
val anonymous = emptyCustomerInfo()
|
|
541
|
+
executor.execute { notifyCustomerInfoListeners(anonymous) }
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
private fun notifyCustomerInfoListeners(info: CustomerInfo) {
|
|
545
|
+
synchronized(customerInfoListeners) { customerInfoListeners.toList() }
|
|
546
|
+
.forEach { runCatching { it(info) } }
|
|
547
|
+
}
|
|
548
|
+
|
|
395
549
|
override fun setLogLevel(level: LogLevel) {
|
|
396
550
|
// Play Billing doesn't expose a log-level knob (it logs to logcat
|
|
397
551
|
// unconditionally). We retain the call for parity but do nothing.
|
|
@@ -446,11 +600,19 @@ class BillingClientGateway(
|
|
|
446
600
|
// out-of-band ones would be its own bug. What must never happen is
|
|
447
601
|
// attributing one of them to a request that did not produce it.
|
|
448
602
|
var matchedFailure: Exception? = null
|
|
603
|
+
var validatedAny = false
|
|
449
604
|
for (p in purchases) {
|
|
605
|
+
// PENDING (cash, deferred payment) means the user has not paid yet and
|
|
606
|
+
// may never pay. Validating it would record a purchase that does not
|
|
607
|
+
// exist, and Play refuses to acknowledge it. Play delivers it again
|
|
608
|
+
// through this listener once it clears, and the reconcile on the next
|
|
609
|
+
// connect finds it otherwise.
|
|
610
|
+
if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
|
|
450
611
|
try {
|
|
451
612
|
for (productId in p.products) {
|
|
452
|
-
validatePurchaseWithBackend(productId, p.purchaseToken)
|
|
613
|
+
validatePurchaseWithBackend(p.packageName, productId, p.purchaseToken)
|
|
453
614
|
}
|
|
615
|
+
validatedAny = true
|
|
454
616
|
if (!p.isAcknowledged) acknowledge(p)
|
|
455
617
|
} catch (e: Exception) {
|
|
456
618
|
if (p === matched) {
|
|
@@ -464,6 +626,14 @@ class BillingClientGateway(
|
|
|
464
626
|
}
|
|
465
627
|
}
|
|
466
628
|
|
|
629
|
+
// The backend now holds every purchase validated above, including the
|
|
630
|
+
// ones no call is waiting for: a pending payment that cleared, a promo
|
|
631
|
+
// code, a purchase made in the Play Store app. Re-read the entitlements
|
|
632
|
+
// once, so the cache and every CustomerInfo listener see what they
|
|
633
|
+
// unlocked, as iOS does after a Transaction.updates delivery. The call in
|
|
634
|
+
// flight, if any, is answered with the same read.
|
|
635
|
+
val refreshed = if (validatedAny) refreshEntitlements() else null
|
|
636
|
+
|
|
467
637
|
if (pending == null) return@execute
|
|
468
638
|
|
|
469
639
|
if (matched == null) {
|
|
@@ -478,15 +648,18 @@ class BillingClientGateway(
|
|
|
478
648
|
)
|
|
479
649
|
return@execute
|
|
480
650
|
}
|
|
651
|
+
if (matched.purchaseState != Purchase.PurchaseState.PURCHASED) {
|
|
652
|
+
// iOS parity (`.pending` -> paymentPending): the flow finished but the
|
|
653
|
+
// money has not moved. Not a success, not a cancellation.
|
|
654
|
+
pending.onError(PurchasesError.PaymentPending(), false)
|
|
655
|
+
return@execute
|
|
656
|
+
}
|
|
481
657
|
if (matchedFailure != null) {
|
|
482
658
|
pending.onError(toPurchasesError(matchedFailure), false)
|
|
483
659
|
return@execute
|
|
484
660
|
}
|
|
485
661
|
|
|
486
|
-
val
|
|
487
|
-
val info = runCatching { repo?.refresh(emptySet()) }.getOrNull()
|
|
488
|
-
?: repo?.current()
|
|
489
|
-
?: emptyCustomerInfo()
|
|
662
|
+
val info = refreshed ?: entitlementsRepo?.current() ?: emptyCustomerInfo()
|
|
490
663
|
pending.onSuccess(
|
|
491
664
|
StoreTransactionResult(
|
|
492
665
|
transaction = matched.toStoreTransaction(),
|
|
@@ -501,11 +674,18 @@ class BillingClientGateway(
|
|
|
501
674
|
@VisibleForTesting
|
|
502
675
|
internal fun connect() {
|
|
503
676
|
val client = billingClient ?: return
|
|
677
|
+
// A second startConnection while one is in flight is answered with
|
|
678
|
+
// DEVELOPER_ERROR, which would fail the waiters and burn a reconnect.
|
|
679
|
+
// The in-flight setup drains them anyway.
|
|
680
|
+
if (client.connectionState == BillingClient.ConnectionState.CONNECTING) return
|
|
504
681
|
client.startConnection(object : BillingClientStateListener {
|
|
505
682
|
override fun onBillingSetupFinished(result: BillingResult) {
|
|
506
683
|
if (result.responseCode == BillingClient.BillingResponseCode.OK) {
|
|
507
684
|
reconnectAttempt.set(0)
|
|
685
|
+
drainReadyWaiters(client)
|
|
686
|
+
reconcilePurchases(client)
|
|
508
687
|
} else {
|
|
688
|
+
failReadyWaiters(toPurchasesError(result))
|
|
509
689
|
scheduleReconnect()
|
|
510
690
|
}
|
|
511
691
|
}
|
|
@@ -516,6 +696,174 @@ class BillingClientGateway(
|
|
|
516
696
|
})
|
|
517
697
|
}
|
|
518
698
|
|
|
699
|
+
/**
|
|
700
|
+
* Run [onReady] with a connected client. When the client is not ready —
|
|
701
|
+
* mid-reconnect, or dead after [MAX_RECONNECT_ATTEMPTS] failed attempts —
|
|
702
|
+
* this resets the reconnect budget, connects, and runs [onReady] on the
|
|
703
|
+
* next OK setup. A failed setup, or no answer within
|
|
704
|
+
* [CONNECT_WAIT_TIMEOUT_MS], ends the call through [onUnavailable] instead.
|
|
705
|
+
*
|
|
706
|
+
* Before this the call simply failed "Billing client not ready", and after
|
|
707
|
+
* the fifth failed connect nothing ever connected again, so every purchase
|
|
708
|
+
* failed until the app was restarted.
|
|
709
|
+
*/
|
|
710
|
+
private fun withReadyClient(
|
|
711
|
+
onReady: (BillingClient) -> Unit,
|
|
712
|
+
onUnavailable: (PurchasesError) -> Unit,
|
|
713
|
+
) {
|
|
714
|
+
val client = billingClient
|
|
715
|
+
if (client == null) {
|
|
716
|
+
onUnavailable(PurchasesError.StoreProblem("Billing client not ready")); return
|
|
717
|
+
}
|
|
718
|
+
if (client.isReady) {
|
|
719
|
+
onReady(client); return
|
|
720
|
+
}
|
|
721
|
+
val waiter = ReadyWaiter(onReady, onUnavailable)
|
|
722
|
+
synchronized(readyWaiters) { readyWaiters.add(waiter) }
|
|
723
|
+
// The setup may have finished between the isReady check and the add.
|
|
724
|
+
if (client.isReady) {
|
|
725
|
+
drainReadyWaiters(client); return
|
|
726
|
+
}
|
|
727
|
+
reconnectScheduler.schedule(CONNECT_WAIT_TIMEOUT_MS) {
|
|
728
|
+
synchronized(readyWaiters) { readyWaiters.remove(waiter) }
|
|
729
|
+
waiter.fail(PurchasesError.StoreProblem("Billing client not ready"))
|
|
730
|
+
}
|
|
731
|
+
reconnectAttempt.set(0)
|
|
732
|
+
connect()
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
private fun takeReadyWaiters(): List<ReadyWaiter> = synchronized(readyWaiters) {
|
|
736
|
+
readyWaiters.toList().also { readyWaiters.clear() }
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
private fun drainReadyWaiters(client: BillingClient) {
|
|
740
|
+
for (w in takeReadyWaiters()) w.ready(client)
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
private fun failReadyWaiters(error: PurchasesError) {
|
|
744
|
+
for (w in takeReadyWaiters()) w.fail(error)
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/** Completes exactly once: ready, failed setup, or timeout, whichever is first. */
|
|
748
|
+
private class ReadyWaiter(
|
|
749
|
+
private val onReady: (BillingClient) -> Unit,
|
|
750
|
+
private val onUnavailable: (PurchasesError) -> Unit,
|
|
751
|
+
) {
|
|
752
|
+
private val done = AtomicBoolean(false)
|
|
753
|
+
fun ready(client: BillingClient) { if (done.compareAndSet(false, true)) onReady(client) }
|
|
754
|
+
fun fail(error: PurchasesError) { if (done.compareAndSet(false, true)) onUnavailable(error) }
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* Validate and acknowledge every PURCHASED purchase Play still holds
|
|
759
|
+
* unacknowledged, SUBS and INAPP. Runs on every OK setup, so on configure
|
|
760
|
+
* and after each reconnect.
|
|
761
|
+
*
|
|
762
|
+
* This is the only retry an acknowledgement gets beyond [acknowledge]'s own
|
|
763
|
+
* bounded one: a process killed between validate and acknowledge, an ack
|
|
764
|
+
* that failed on a bad connection, or a pending purchase that cleared while
|
|
765
|
+
* the app was not running all land here. There is no server-side
|
|
766
|
+
* acknowledge (that would be a store write from the backend).
|
|
767
|
+
*
|
|
768
|
+
* When it validated anything, it then re-reads the entitlements, so the app
|
|
769
|
+
* sees what those purchases unlocked without a restore.
|
|
770
|
+
*/
|
|
771
|
+
private fun reconcilePurchases(client: BillingClient) {
|
|
772
|
+
if (!reconcileInFlight.compareAndSet(false, true)) return
|
|
773
|
+
try {
|
|
774
|
+
queryOwnedPurchases(client, PRODUCT_TYPES, mutableListOf()) { owned, _ ->
|
|
775
|
+
executor.execute {
|
|
776
|
+
var validatedAny = false
|
|
777
|
+
try {
|
|
778
|
+
for (p in owned) {
|
|
779
|
+
if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
|
|
780
|
+
if (p.isAcknowledged || p.purchaseToken in ackClaimed) continue
|
|
781
|
+
try {
|
|
782
|
+
val subject = reconcileSubject(p)
|
|
783
|
+
for (productId in p.products) {
|
|
784
|
+
validatePurchaseWithBackend(p.packageName, productId, p.purchaseToken, subject)
|
|
785
|
+
}
|
|
786
|
+
validatedAny = true
|
|
787
|
+
acknowledge(p)
|
|
788
|
+
} catch (e: Exception) {
|
|
789
|
+
// Not acknowledged, so the next connect tries again.
|
|
790
|
+
Log.w(TAG, "reconcile: validate failed for an unacknowledged purchase", e)
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
} finally {
|
|
794
|
+
reconcileInFlight.set(false)
|
|
795
|
+
}
|
|
796
|
+
if (validatedAny) refreshEntitlements()
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
} catch (e: RuntimeException) {
|
|
800
|
+
reconcileInFlight.set(false)
|
|
801
|
+
Log.w(TAG, "reconcile: queryPurchasesAsync failed", e)
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/**
|
|
806
|
+
* The subject a reconciled purchase is validated under.
|
|
807
|
+
*
|
|
808
|
+
* [launchPurchase] stamps [getAppUserID] on every purchase as its
|
|
809
|
+
* obfuscatedAccountId. A reconcile mostly runs at configure, before the host
|
|
810
|
+
* has called logIn again ([Identity] keeps the user id in memory only), so
|
|
811
|
+
* the current subject there is the device's anonymous id. Posting that for a
|
|
812
|
+
* purchase a signed-in user made would let the backend move the purchase onto
|
|
813
|
+
* the anonymous id, or refuse it and leave it to be refunded. A purchase
|
|
814
|
+
* stamped with a user id is therefore validated under that user.
|
|
815
|
+
*
|
|
816
|
+
* An anonymous stamp, or none (promo codes, the Play Store app), uses the
|
|
817
|
+
* current subject, as before: older SDKs stamped a per-process anonymous id
|
|
818
|
+
* (`${'$'}SKAnonymousID:` or, before that, `${'$'}RCAnonymousID:`) that
|
|
819
|
+
* nothing reads back, and the current one is this device's.
|
|
820
|
+
*/
|
|
821
|
+
private fun reconcileSubject(p: Purchase): String =
|
|
822
|
+
p.accountIdentifiers?.obfuscatedAccountId
|
|
823
|
+
?.takeIf { stamp -> stamp.isNotEmpty() && ANONYMOUS_ID_PREFIXES.none { stamp.startsWith(it) } }
|
|
824
|
+
?: getAppUserID()
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* The purchases Play holds of each of [productTypes], asked one type after
|
|
828
|
+
* the other. [done] gets them all, and the first non-OK answer if a query
|
|
829
|
+
* failed (its type's purchases are then missing).
|
|
830
|
+
*/
|
|
831
|
+
private fun queryOwnedPurchases(
|
|
832
|
+
client: BillingClient,
|
|
833
|
+
productTypes: List<String>,
|
|
834
|
+
found: MutableList<Purchase>,
|
|
835
|
+
failure: BillingResult? = null,
|
|
836
|
+
done: (List<Purchase>, failure: BillingResult?) -> Unit,
|
|
837
|
+
) {
|
|
838
|
+
val type = productTypes.firstOrNull() ?: run { done(found, failure); return }
|
|
839
|
+
val params = QueryPurchasesParams.newBuilder().setProductType(type).build()
|
|
840
|
+
client.queryPurchasesAsync(params) { result, purchases ->
|
|
841
|
+
var firstFailure = failure
|
|
842
|
+
if (result.responseCode == BillingClient.BillingResponseCode.OK) {
|
|
843
|
+
found.addAll(purchases)
|
|
844
|
+
} else {
|
|
845
|
+
Log.w(TAG, "queryPurchasesAsync($type) returned ${result.responseCode}")
|
|
846
|
+
if (firstFailure == null) firstFailure = result
|
|
847
|
+
}
|
|
848
|
+
queryOwnedPurchases(client, productTypes.drop(1), found, firstFailure, done)
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/**
|
|
853
|
+
* Re-read the user's entitlements from the backend into the cache, which
|
|
854
|
+
* tells every CustomerInfo listener. Null when the backend cannot be read;
|
|
855
|
+
* the cache then keeps what it had, and the next read tries again.
|
|
856
|
+
*/
|
|
857
|
+
private fun refreshEntitlements(): CustomerInfo? {
|
|
858
|
+
val repo = entitlementsRepo ?: return null
|
|
859
|
+
return try {
|
|
860
|
+
repo.refresh(emptySet())
|
|
861
|
+
} catch (e: Exception) {
|
|
862
|
+
Log.w(TAG, "entitlements refresh failed; keeping the cached entitlements", e)
|
|
863
|
+
null
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
519
867
|
private fun scheduleReconnect() {
|
|
520
868
|
val n = reconnectAttempt.getAndIncrement()
|
|
521
869
|
if (n >= MAX_RECONNECT_ATTEMPTS) {
|
|
@@ -535,12 +883,16 @@ class BillingClientGateway(
|
|
|
535
883
|
* non-2xx.
|
|
536
884
|
*/
|
|
537
885
|
@Throws(IOException::class)
|
|
538
|
-
private fun validatePurchaseWithBackend(
|
|
886
|
+
private fun validatePurchaseWithBackend(
|
|
887
|
+
packageName: String,
|
|
888
|
+
productId: String,
|
|
889
|
+
purchaseToken: String,
|
|
890
|
+
userId: String = getAppUserID(),
|
|
891
|
+
) {
|
|
539
892
|
val body = JSONObject().apply {
|
|
540
|
-
put("user_id",
|
|
541
|
-
put("
|
|
542
|
-
put("
|
|
543
|
-
put("store", "play")
|
|
893
|
+
put("user_id", userId)
|
|
894
|
+
put("platform", "android")
|
|
895
|
+
put("receipt_data", "$packageName:$productId:$purchaseToken")
|
|
544
896
|
}.toString()
|
|
545
897
|
// Round-D auth audit: the backend `/api/sdk/subscriptions/validate`
|
|
546
898
|
// route uses `withApiKeyAuth` (X-API-Key header). Pre-Round-D we
|
|
@@ -597,12 +949,36 @@ class BillingClientGateway(
|
|
|
597
949
|
|
|
598
950
|
private fun acknowledge(purchase: Purchase) {
|
|
599
951
|
acknowledgeOverrideForTesting?.let { it(purchase); return }
|
|
600
|
-
|
|
952
|
+
// Already acknowledged, or an acknowledgement is in flight, in this process.
|
|
953
|
+
if (!ackClaimed.add(purchase.purchaseToken)) return
|
|
954
|
+
sendAcknowledge(purchase, attempt = 0)
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* One acknowledgePurchase call. A non-OK answer is retried after
|
|
959
|
+
* 1 s, 2 s, ... up to [MAX_ACK_ATTEMPTS] calls in all; a terminal answer,
|
|
960
|
+
* or the last failed attempt, releases the token so the next
|
|
961
|
+
* [reconcilePurchases] tries again. Nothing else acknowledges: the backend
|
|
962
|
+
* has no acknowledge job.
|
|
963
|
+
*/
|
|
964
|
+
private fun sendAcknowledge(purchase: Purchase, attempt: Int) {
|
|
965
|
+
val token = purchase.purchaseToken
|
|
966
|
+
val client = billingClient ?: run { ackClaimed.remove(token); return }
|
|
601
967
|
val params = AcknowledgePurchaseParams.newBuilder()
|
|
602
|
-
.setPurchaseToken(
|
|
968
|
+
.setPurchaseToken(token)
|
|
603
969
|
.build()
|
|
604
|
-
client.acknowledgePurchase(params) {
|
|
605
|
-
|
|
970
|
+
client.acknowledgePurchase(params) { result ->
|
|
971
|
+
val code = result.responseCode
|
|
972
|
+
if (code == BillingClient.BillingResponseCode.OK) return@acknowledgePurchase
|
|
973
|
+
if (attempt + 1 < MAX_ACK_ATTEMPTS && code !in TERMINAL_ACK_CODES) {
|
|
974
|
+
reconnectScheduler.schedule(ACK_RETRY_BASE_DELAY_MS shl attempt) {
|
|
975
|
+
sendAcknowledge(purchase, attempt + 1)
|
|
976
|
+
}
|
|
977
|
+
} else {
|
|
978
|
+
ackClaimed.remove(token)
|
|
979
|
+
Log.w(TAG, "acknowledgePurchase failed (code=$code, attempts=${attempt + 1}); left for the next reconcile")
|
|
980
|
+
}
|
|
981
|
+
}
|
|
606
982
|
}
|
|
607
983
|
|
|
608
984
|
private fun Purchase.toStoreTransaction(): StoreTransaction = object : StoreTransaction {
|
|
@@ -634,8 +1010,39 @@ class BillingClientGateway(
|
|
|
634
1010
|
|
|
635
1011
|
companion object {
|
|
636
1012
|
private const val TAG = "SwissKnife.Billing"
|
|
1013
|
+
private val ANONYMOUS_ID_PREFIXES = listOf("\$SKAnonymousID:", "\$RCAnonymousID:")
|
|
1014
|
+
|
|
1015
|
+
private fun newFallbackAnonymousId(): String =
|
|
1016
|
+
"\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
|
|
1017
|
+
|
|
637
1018
|
@VisibleForTesting internal const val MAX_RECONNECT_ATTEMPTS = 5
|
|
638
1019
|
|
|
1020
|
+
/** Total acknowledgePurchase calls per purchase before it is left to the reconcile. */
|
|
1021
|
+
@VisibleForTesting internal const val MAX_ACK_ATTEMPTS = 3
|
|
1022
|
+
@VisibleForTesting internal const val ACK_RETRY_BASE_DELAY_MS = 1_000L
|
|
1023
|
+
|
|
1024
|
+
/** How long a purchase or restore waits for a reconnect before failing. */
|
|
1025
|
+
@VisibleForTesting internal const val CONNECT_WAIT_TIMEOUT_MS = 15_000L
|
|
1026
|
+
|
|
1027
|
+
/** How long pricing offerings waits for Play to connect before using dashboard prices. */
|
|
1028
|
+
@VisibleForTesting internal const val PRICE_CONNECT_WAIT_MS = 5_000L
|
|
1029
|
+
|
|
1030
|
+
/**
|
|
1031
|
+
* The Play product types the SDK sells and restores: subscriptions and
|
|
1032
|
+
* one-time products (consumables included). Play answers a query for one
|
|
1033
|
+
* type only, so purchases, restore and the reconcile ask for each.
|
|
1034
|
+
*/
|
|
1035
|
+
private val PRODUCT_TYPES = listOf(
|
|
1036
|
+
BillingClient.ProductType.SUBS,
|
|
1037
|
+
BillingClient.ProductType.INAPP,
|
|
1038
|
+
)
|
|
1039
|
+
|
|
1040
|
+
/** Answers a retry cannot change: the purchase is gone or the request is malformed. */
|
|
1041
|
+
private val TERMINAL_ACK_CODES = setOf(
|
|
1042
|
+
BillingClient.BillingResponseCode.ITEM_NOT_OWNED,
|
|
1043
|
+
BillingClient.BillingResponseCode.DEVELOPER_ERROR,
|
|
1044
|
+
)
|
|
1045
|
+
|
|
639
1046
|
/** Map Play Billing error codes to our [PurchasesError] hierarchy. */
|
|
640
1047
|
@VisibleForTesting
|
|
641
1048
|
internal fun toPurchasesError(result: BillingResult): PurchasesError {
|
|
@@ -659,6 +1066,8 @@ class BillingClientGateway(
|
|
|
659
1066
|
|
|
660
1067
|
private fun toPurchasesError(t: Throwable): PurchasesError = when (t) {
|
|
661
1068
|
is PurchasesError -> t
|
|
1069
|
+
is com.appswissknife.net.BillingBackendException -> PurchasesError(
|
|
1070
|
+
PurchasesErrorCode.UnexpectedBackendResponseError, t.message ?: "Purchase validation failed", t)
|
|
662
1071
|
is IOException -> PurchasesError.NetworkError(t.message ?: "Network error", t)
|
|
663
1072
|
else -> PurchasesError.Unknown(t.message ?: "Unknown error", t)
|
|
664
1073
|
}
|
|
@@ -680,6 +1089,54 @@ interface BillingHttpClient {
|
|
|
680
1089
|
fun post(url: String, body: String, headers: Map<String, String>): String
|
|
681
1090
|
}
|
|
682
1091
|
|
|
1092
|
+
/**
|
|
1093
|
+
* The SDK's unified backend transport as a [BillingHttpClient] — what the Play
|
|
1094
|
+
* gateway validates through. Public so a store add-on that lives outside this
|
|
1095
|
+
* module (the RuStore gateway) uses the same transport instead of opening its
|
|
1096
|
+
* own connection. A non-2xx answer throws an [IOException] whose message never
|
|
1097
|
+
* echoes the response body.
|
|
1098
|
+
*/
|
|
1099
|
+
fun defaultBillingHttpClient(): BillingHttpClient = com.appswissknife.net.BackendHttpClientAdapter()
|
|
1100
|
+
|
|
1101
|
+
/**
|
|
1102
|
+
* A [BillingHttpClient] that retries transient failures: transport errors,
|
|
1103
|
+
* HTTP 429 and 5xx, after 1 s, 2 s, ... ([maxRetries] retries after the first
|
|
1104
|
+
* attempt). Any other HTTP status is the backend's answer and is thrown at once.
|
|
1105
|
+
*
|
|
1106
|
+
* Safe for `/api/sdk/subscriptions/validate`: the backend keys the ledger and the
|
|
1107
|
+
* subscription row on the store's transaction id, so a retried POST cannot record
|
|
1108
|
+
* a purchase twice.
|
|
1109
|
+
*/
|
|
1110
|
+
class RetryingBillingHttpClient @JvmOverloads constructor(
|
|
1111
|
+
private val delegate: BillingHttpClient = defaultBillingHttpClient(),
|
|
1112
|
+
private val maxRetries: Int = 2,
|
|
1113
|
+
private val sleeper: (Long) -> Unit = { Thread.sleep(it) },
|
|
1114
|
+
) : BillingHttpClient {
|
|
1115
|
+
@Throws(IOException::class)
|
|
1116
|
+
override fun post(url: String, body: String, headers: Map<String, String>): String {
|
|
1117
|
+
var attempt = 0
|
|
1118
|
+
while (true) {
|
|
1119
|
+
try {
|
|
1120
|
+
return delegate.post(url, body, headers)
|
|
1121
|
+
} catch (e: IOException) {
|
|
1122
|
+
if (attempt >= maxRetries || !isTransient(e)) throw e
|
|
1123
|
+
try {
|
|
1124
|
+
sleeper(1_000L shl attempt)
|
|
1125
|
+
} catch (_: InterruptedException) {
|
|
1126
|
+
Thread.currentThread().interrupt()
|
|
1127
|
+
throw e
|
|
1128
|
+
}
|
|
1129
|
+
attempt++
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
private fun isTransient(e: IOException): Boolean {
|
|
1135
|
+
val status = (e as? com.appswissknife.net.BillingBackendException)?.httpStatus ?: return true
|
|
1136
|
+
return status == 429 || status >= 500
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
|
|
683
1140
|
/** Schedule a delayed task. Tests use a synchronous-immediate impl to
|
|
684
1141
|
* exercise reconnect logic without sleeping. */
|
|
685
1142
|
interface ReconnectScheduler {
|