/
BillingWrapper.kt
640 lines (592 loc) · 27.4 KB
/
BillingWrapper.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
// Purchases
//
// Copyright © 2019 RevenueCat, Inc. All rights reserved.
//
package com.revenuecat.purchases.google
import android.app.Activity
import android.content.Context
import android.os.Handler
import androidx.annotation.UiThread
import com.android.billingclient.api.AcknowledgePurchaseParams
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClient.SkuType
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.ConsumeParams
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.PurchaseHistoryRecord
import com.android.billingclient.api.PurchaseHistoryResponseListener
import com.android.billingclient.api.PurchasesUpdatedListener
import com.android.billingclient.api.SkuDetailsParams
import com.android.billingclient.api.SkuDetailsResponseListener
import com.revenuecat.purchases.ProductType
import com.revenuecat.purchases.PurchasesError
import com.revenuecat.purchases.PurchasesErrorCallback
import com.revenuecat.purchases.PurchasesErrorCode
import com.revenuecat.purchases.common.BillingAbstract
import com.revenuecat.purchases.common.LogIntent
import com.revenuecat.purchases.common.StoreProductsCallback
import com.revenuecat.purchases.common.ReplaceSkuInfo
import com.revenuecat.purchases.common.caching.DeviceCache
import com.revenuecat.purchases.common.errorLog
import com.revenuecat.purchases.common.firstSku
import com.revenuecat.purchases.common.listOfSkus
import com.revenuecat.purchases.common.log
import com.revenuecat.purchases.common.sha1
import com.revenuecat.purchases.common.sha256
import com.revenuecat.purchases.common.toHumanReadableDescription
import com.revenuecat.purchases.models.StoreProduct
import com.revenuecat.purchases.models.StoreTransaction
import com.revenuecat.purchases.models.PurchaseState
import com.revenuecat.purchases.models.skuDetails
import com.revenuecat.purchases.strings.BillingStrings
import com.revenuecat.purchases.strings.OfferingStrings
import com.revenuecat.purchases.strings.PurchaseStrings
import com.revenuecat.purchases.strings.RestoreStrings
import java.io.PrintWriter
import java.io.StringWriter
import java.util.concurrent.ConcurrentLinkedQueue
class BillingWrapper(
private val clientFactory: ClientFactory,
private val mainHandler: Handler,
private val deviceCache: DeviceCache
) : BillingAbstract(), PurchasesUpdatedListener, BillingClientStateListener {
@get:Synchronized
@set:Synchronized
@Volatile
var billingClient: BillingClient? = null
private val productTypes = mutableMapOf<String, ProductType>()
private val presentedOfferingsByProductIdentifier = mutableMapOf<String, String?>()
private val serviceRequests =
ConcurrentLinkedQueue<(connectionError: PurchasesError?) -> Unit>()
class ClientFactory(private val context: Context) {
@UiThread
fun buildClient(listener: com.android.billingclient.api.PurchasesUpdatedListener): BillingClient {
return BillingClient.newBuilder(context).enablePendingPurchases().setListener(listener)
.build()
}
}
private fun executePendingRequests() {
synchronized(this@BillingWrapper) {
while (billingClient?.isReady == true && !serviceRequests.isEmpty()) {
serviceRequests.remove().let { mainHandler.post { it(null) } }
}
}
}
override fun startConnection() {
mainHandler.post {
synchronized(this@BillingWrapper) {
if (billingClient == null) {
billingClient = clientFactory.buildClient(this)
}
billingClient?.let {
log(LogIntent.DEBUG, BillingStrings.BILLING_CLIENT_STARTING.format(it))
it.startConnection(this)
}
}
}
}
override fun endConnection() {
mainHandler.post {
synchronized(this@BillingWrapper) {
billingClient?.let {
log(LogIntent.DEBUG, BillingStrings.BILLING_CLIENT_ENDING.format(it))
it.endConnection()
}
billingClient = null
}
}
}
@Synchronized
private fun executeRequestOnUIThread(request: (PurchasesError?) -> Unit) {
if (purchasesUpdatedListener != null) {
serviceRequests.add(request)
if (billingClient?.isReady == false) {
startConnection()
} else {
executePendingRequests()
}
}
}
override fun querySkuDetailsAsync(
productType: ProductType,
skus: Set<String>,
onReceive: StoreProductsCallback,
onError: PurchasesErrorCallback
) {
val nonEmptySkus = skus.filter { it.isNotEmpty() }
if (nonEmptySkus.isEmpty()) {
log(LogIntent.DEBUG, OfferingStrings.EMPTY_SKU_LIST)
onReceive(emptyList())
return
}
log(LogIntent.DEBUG, OfferingStrings.FETCHING_PRODUCTS.format(skus.joinToString()))
executeRequestOnUIThread { connectionError ->
if (connectionError == null) {
val params = SkuDetailsParams.newBuilder()
.setType(productType.toSKUType() ?: SkuType.INAPP)
.setSkusList(nonEmptySkus).build()
withConnectedClient {
querySkuDetailsAsyncEnsuringOneResponse(params) { billingResult, skuDetailsList ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
log(
LogIntent.DEBUG, OfferingStrings.FETCHING_PRODUCTS_FINISHED
.format(skus.joinToString())
)
log(
LogIntent.PURCHASE, OfferingStrings.RETRIEVED_PRODUCTS
.format(skuDetailsList?.joinToString { it.toString() })
)
skuDetailsList?.takeUnless { it.isEmpty() }?.forEach {
log(LogIntent.PURCHASE, OfferingStrings.LIST_PRODUCTS.format(it.sku, it))
}
onReceive(skuDetailsList?.map { it.toStoreProduct() } ?: emptyList())
} else {
log(
LogIntent.GOOGLE_ERROR, OfferingStrings.FETCHING_PRODUCTS_ERROR
.format(billingResult.toHumanReadableDescription())
)
onError(
billingResult.responseCode.billingResponseToPurchasesError(
"Error when fetching products. ${billingResult.toHumanReadableDescription()}"
).also { errorLog(it) }
)
}
}
}
} else {
onError(connectionError)
}
}
}
override fun makePurchaseAsync(
activity: Activity,
appUserID: String,
storeProduct: StoreProduct,
replaceSkuInfo: ReplaceSkuInfo?,
presentedOfferingIdentifier: String?
) {
if (replaceSkuInfo != null) {
log(
LogIntent.PURCHASE, PurchaseStrings.UPGRADING_SKU
.format(replaceSkuInfo.oldPurchase.skus[0], storeProduct.sku)
)
} else {
log(LogIntent.PURCHASE, PurchaseStrings.PURCHASING_PRODUCT.format(storeProduct.sku))
}
synchronized(this@BillingWrapper) {
productTypes[storeProduct.sku] = storeProduct.type
presentedOfferingsByProductIdentifier[storeProduct.sku] = presentedOfferingIdentifier
}
executeRequestOnUIThread {
val params = BillingFlowParams.newBuilder()
.setSkuDetails(storeProduct.skuDetails)
.apply {
replaceSkuInfo?.let {
setUpgradeInfo(it)
} ?: setObfuscatedAccountId(appUserID.sha256())
// only setObfuscatedAccountId for non-upgrade/downgrades until google issue is fixed:
// https://issuetracker.google.com/issues/155005449
}.build()
launchBillingFlow(activity, params)
}
}
@UiThread
private fun launchBillingFlow(
activity: Activity,
params: BillingFlowParams
) {
if (activity.intent == null) {
log(LogIntent.WARNING, BillingStrings.NULL_ACTIVITY_INTENT)
}
withConnectedClient {
launchBillingFlow(activity, params)
.takeIf { billingResult -> billingResult.responseCode != BillingClient.BillingResponseCode.OK }
?.let { billingResult ->
log(
LogIntent.GOOGLE_ERROR, BillingStrings.BILLING_INTENT_FAILED
.format(billingResult.toHumanReadableDescription())
)
}
}
}
fun queryPurchaseHistoryAsync(
@BillingClient.SkuType skuType: String,
onReceivePurchaseHistory: (List<PurchaseHistoryRecord>) -> Unit,
onReceivePurchaseHistoryError: (PurchasesError) -> Unit
) {
log(LogIntent.DEBUG, RestoreStrings.QUERYING_PURCHASE_HISTORY.format(skuType))
executeRequestOnUIThread { connectionError ->
if (connectionError == null) {
withConnectedClient {
queryPurchaseHistoryAsyncEnsuringOneResponse(skuType) { billingResult, purchaseHistoryRecordList ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
purchaseHistoryRecordList.takeUnless { it.isNullOrEmpty() }?.forEach {
log(
LogIntent.RC_PURCHASE_SUCCESS, RestoreStrings.PURCHASE_HISTORY_RETRIEVED
.format(it.toHumanReadableDescription())
)
} ?: log(LogIntent.DEBUG, RestoreStrings.PURCHASE_HISTORY_EMPTY)
onReceivePurchaseHistory(purchaseHistoryRecordList ?: emptyList())
} else {
onReceivePurchaseHistoryError(
billingResult.responseCode.billingResponseToPurchasesError(
"Error receiving purchase history. ${billingResult.toHumanReadableDescription()}"
).also { errorLog(it) }
)
}
}
}
} else {
onReceivePurchaseHistoryError(connectionError)
}
}
}
override fun queryAllPurchases(
appUserID: String,
onReceivePurchaseHistory: (List<StoreTransaction>) -> Unit,
onReceivePurchaseHistoryError: (PurchasesError) -> Unit
) {
queryPurchaseHistoryAsync(
SkuType.SUBS,
{ subsPurchasesList ->
queryPurchaseHistoryAsync(
SkuType.INAPP,
{ inAppPurchasesList ->
onReceivePurchaseHistory(
subsPurchasesList.map {
it.toStoreTransaction(ProductType.SUBS)
} + inAppPurchasesList.map {
it.toStoreTransaction(ProductType.INAPP)
}
)
},
onReceivePurchaseHistoryError
)
},
onReceivePurchaseHistoryError
)
}
override fun consumeAndSave(
shouldTryToConsume: Boolean,
purchase: StoreTransaction
) {
if (purchase.type == ProductType.UNKNOWN) {
// Would only get here if the purchase was triggered from outside of the app and there was
// an issue getting the purchase type
return
}
if (purchase.purchaseState == PurchaseState.PENDING) {
// PENDING purchases should not be fulfilled
return
}
val originalGooglePurchase = purchase.originalGooglePurchase
val alreadyAcknowledged = originalGooglePurchase?.isAcknowledged ?: false
if (shouldTryToConsume && purchase.type == ProductType.INAPP) {
consumePurchase(purchase.purchaseToken) { billingResult, purchaseToken ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
deviceCache.addSuccessfullyPostedToken(purchaseToken)
} else {
log(
LogIntent.GOOGLE_ERROR, PurchaseStrings.CONSUMING_PURCHASE_ERROR
.format(billingResult.toHumanReadableDescription())
)
}
}
} else if (shouldTryToConsume && !alreadyAcknowledged) {
acknowledge(purchase.purchaseToken) { billingResult, purchaseToken ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
deviceCache.addSuccessfullyPostedToken(purchaseToken)
} else {
log(
LogIntent.GOOGLE_ERROR, PurchaseStrings.ACKNOWLEDGING_PURCHASE_ERROR
.format(billingResult.toHumanReadableDescription())
)
}
}
} else {
deviceCache.addSuccessfullyPostedToken(purchase.purchaseToken)
}
}
internal fun consumePurchase(
token: String,
onConsumed: (billingResult: BillingResult, purchaseToken: String) -> Unit
) {
log(LogIntent.PURCHASE, PurchaseStrings.CONSUMING_PURCHASE.format(token))
executeRequestOnUIThread { connectionError ->
if (connectionError == null) {
withConnectedClient {
consumeAsync(
ConsumeParams.newBuilder().setPurchaseToken(token).build(), onConsumed
)
}
}
}
}
internal fun acknowledge(
token: String,
onAcknowledged: (billingResult: BillingResult, purchaseToken: String) -> Unit
) {
log(LogIntent.PURCHASE, PurchaseStrings.ACKNOWLEDGING_PURCHASE.format(token))
executeRequestOnUIThread { connectionError ->
if (connectionError == null) {
withConnectedClient {
acknowledgePurchase(
AcknowledgePurchaseParams.newBuilder().setPurchaseToken(token).build()
) { billingResult ->
onAcknowledged(billingResult, token)
}
}
}
}
}
private fun Purchase.PurchasesResult.isSuccessful() = responseCode == BillingClient.BillingResponseCode.OK
override fun queryPurchases(
appUserID: String,
onSuccess: (Map<String, StoreTransaction>) -> Unit,
onError: (PurchasesError) -> Unit
) {
withConnectedClient {
log(LogIntent.DEBUG, RestoreStrings.QUERYING_PURCHASE)
val queryActiveSubscriptionsResult = this.queryPurchases(SkuType.SUBS)
if (!queryActiveSubscriptionsResult.isSuccessful()) {
val billingResult = queryActiveSubscriptionsResult.billingResult
val purchasesError = billingResult.responseCode.billingResponseToPurchasesError(
RestoreStrings.QUERYING_SUBS_ERROR.format(billingResult.toHumanReadableDescription())
)
onError(purchasesError)
return@withConnectedClient
}
val queryUnconsumedInAppsResult = this.queryPurchases(SkuType.INAPP)
if (!queryUnconsumedInAppsResult.isSuccessful()) {
val billingResult = queryUnconsumedInAppsResult.billingResult
val purchasesError = billingResult.responseCode.billingResponseToPurchasesError(
RestoreStrings.QUERYING_INAPP_ERROR.format(billingResult.toHumanReadableDescription())
)
onError(purchasesError)
return@withConnectedClient
}
val activeSubscriptionsList = queryActiveSubscriptionsResult.purchasesList ?: emptyList<Purchase>()
val mapOfActiveSubscriptions = activeSubscriptionsList.toMapOfGooglePurchaseWrapper(SkuType.SUBS)
val unconsumedInAppsList = queryUnconsumedInAppsResult.purchasesList ?: emptyList<Purchase>()
val mapOfUnconsumedInApps = unconsumedInAppsList.toMapOfGooglePurchaseWrapper(SkuType.INAPP)
onSuccess(mapOfActiveSubscriptions + mapOfUnconsumedInApps)
}
}
private fun List<Purchase>.toMapOfGooglePurchaseWrapper(
@SkuType skuType: String
): Map<String, StoreTransaction> {
return this.map { purchase ->
val hash = purchase.purchaseToken.sha1()
hash to purchase.toStoreTransaction(skuType.toProductType(), presentedOfferingIdentifier = null)
}.toMap()
}
override fun findPurchaseInPurchaseHistory(
appUserID: String,
productType: ProductType,
sku: String,
onCompletion: (StoreTransaction) -> Unit,
onError: (PurchasesError) -> Unit
) {
withConnectedClient {
log(LogIntent.DEBUG, RestoreStrings.QUERYING_PURCHASE_WITH_TYPE.format(sku, productType.name))
productType.toSKUType()?.let { skuType ->
queryPurchaseHistoryAsync(skuType) { result, purchasesList ->
if (result.isSuccessful()) {
val purchaseHistoryRecordWrapper =
purchasesList?.firstOrNull { it.listOfSkus.contains(sku) }
?.toStoreTransaction(productType)
if (purchaseHistoryRecordWrapper != null) {
onCompletion(purchaseHistoryRecordWrapper)
} else {
val message = PurchaseStrings.NO_EXISTING_PURCHASE.format(sku)
val error = PurchasesError(PurchasesErrorCode.PurchaseInvalidError, message)
onError(error)
}
} else {
val underlyingErrorMessage = PurchaseStrings.ERROR_FINDING_PURCHASE.format(sku)
val error =
result.responseCode.billingResponseToPurchasesError(underlyingErrorMessage)
onError(error)
}
}
} ?: onError(
PurchasesError(PurchasesErrorCode.PurchaseInvalidError, PurchaseStrings.NOT_RECOGNIZED_PRODUCT_TYPE)
)
}
}
internal fun getPurchaseType(purchaseToken: String): ProductType {
billingClient?.let { client ->
val querySubsResult = client.queryPurchases(SkuType.SUBS)
val subsResponseOK = querySubsResult.responseCode == BillingClient.BillingResponseCode.OK
val subFound = querySubsResult.purchasesList?.any { it.purchaseToken == purchaseToken } ?: false
if (subsResponseOK && subFound) {
return@getPurchaseType ProductType.SUBS
}
val queryInAppsResult = client.queryPurchases(SkuType.INAPP)
val inAppsResponseIsOK = queryInAppsResult.responseCode == BillingClient.BillingResponseCode.OK
val inAppFound = queryInAppsResult.purchasesList?.any { it.purchaseToken == purchaseToken } ?: false
if (inAppsResponseIsOK && inAppFound) {
return@getPurchaseType ProductType.INAPP
}
}
return ProductType.UNKNOWN
}
override fun onPurchasesUpdated(
billingResult: BillingResult,
purchases: List<Purchase>?
) {
val notNullPurchasesList = purchases ?: emptyList()
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && notNullPurchasesList.isNotEmpty()) {
notNullPurchasesList.map { purchase ->
log(
LogIntent.DEBUG, BillingStrings.BILLING_WRAPPER_PURCHASES_UPDATED
.format(purchase.toHumanReadableDescription())
)
var type: ProductType?
var presentedOffering: String?
synchronized(this@BillingWrapper) {
type = productTypes[purchase.firstSku]
presentedOffering = presentedOfferingsByProductIdentifier[purchase.firstSku]
}
purchase.toStoreTransaction(
type ?: getPurchaseType(purchase.purchaseToken),
presentedOffering
)
}.let { mappedPurchases ->
purchasesUpdatedListener?.onPurchasesUpdated(mappedPurchases)
}
} else if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
// When doing a DEFERRED downgrade, the result is OK, but the list of purchases is null
purchasesUpdatedListener?.onPurchasesUpdated(emptyList())
} else {
log(LogIntent.GOOGLE_ERROR, BillingStrings.BILLING_WRAPPER_PURCHASES_ERROR
.format(billingResult.toHumanReadableDescription()) +
"${
notNullPurchasesList.takeUnless { it.isEmpty() }?.let { purchase ->
"Purchases:" + purchase.joinToString(
", ",
transform = { it.toHumanReadableDescription() }
)
}
}"
)
val responseCode =
if (purchases == null && billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
BillingClient.BillingResponseCode.ERROR
} else {
billingResult.responseCode
}
val message = "Error updating purchases. ${billingResult.toHumanReadableDescription()}"
val purchasesError = responseCode.billingResponseToPurchasesError(message).also { errorLog(it) }
purchasesUpdatedListener?.onPurchasesFailedToUpdate(purchasesError)
}
}
override fun onBillingSetupFinished(billingResult: BillingResult) {
mainHandler.post {
when (billingResult.responseCode) {
BillingClient.BillingResponseCode.OK -> {
log(
LogIntent.DEBUG, BillingStrings.BILLING_SERVICE_SETUP_FINISHED
.format(billingClient?.toString())
)
stateListener?.onConnected()
executePendingRequests()
}
BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED,
BillingClient.BillingResponseCode.BILLING_UNAVAILABLE -> {
val message =
BillingStrings.BILLING_UNAVAILABLE.format(billingResult.toHumanReadableDescription())
log(LogIntent.GOOGLE_WARNING, message)
// The calls will fail with an error that will be surfaced. We want to surface these errors
// Can't call executePendingRequests because it will not do anything since it checks for isReady()
synchronized(this@BillingWrapper) {
while (!serviceRequests.isEmpty()) {
serviceRequests.remove().let { serviceRequest ->
mainHandler.post {
serviceRequest(
billingResult.responseCode
.billingResponseToPurchasesError(message)
.also { errorLog(it) }
)
}
}
}
}
}
BillingClient.BillingResponseCode.SERVICE_DISCONNECTED,
BillingClient.BillingResponseCode.USER_CANCELED,
BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE,
BillingClient.BillingResponseCode.ITEM_UNAVAILABLE,
BillingClient.BillingResponseCode.ERROR,
BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED,
BillingClient.BillingResponseCode.SERVICE_TIMEOUT,
BillingClient.BillingResponseCode.ITEM_NOT_OWNED -> {
log(
LogIntent.GOOGLE_WARNING, BillingStrings.BILLING_CLIENT_ERROR
.format(billingResult.toHumanReadableDescription())
)
}
BillingClient.BillingResponseCode.DEVELOPER_ERROR -> {
// Billing service is already trying to connect. Don't do anything.
}
}
}
}
override fun onBillingServiceDisconnected() {
mainHandler.post {
log(LogIntent.DEBUG, BillingStrings.BILLING_SERVICE_DISCONNECTED.format(billingClient.toString()))
}
}
override fun isConnected(): Boolean = billingClient?.isReady ?: false
private fun withConnectedClient(receivingFunction: BillingClient.() -> Unit) {
billingClient?.takeIf { it.isReady }?.let {
it.receivingFunction()
} ?: log(LogIntent.GOOGLE_WARNING, BillingStrings.BILLING_CLIENT_DISCONNECTED.format(getStackTrace()))
}
private fun getStackTrace(): String {
val stringWriter = StringWriter()
val printWriter = PrintWriter(stringWriter)
Throwable().printStackTrace(printWriter)
return stringWriter.toString()
}
private fun BillingClient.querySkuDetailsAsyncEnsuringOneResponse(
params: SkuDetailsParams,
listener: SkuDetailsResponseListener
) {
var hasResponded = false
querySkuDetailsAsync(params) { billingResult, skuDetailsList ->
synchronized(this@BillingWrapper) {
if (hasResponded) {
log(
LogIntent.GOOGLE_ERROR,
OfferingStrings.EXTRA_QUERY_SKU_DETAILS_RESPONSE.format(billingResult.responseCode)
)
return@querySkuDetailsAsync
}
hasResponded = true
}
listener.onSkuDetailsResponse(billingResult, skuDetailsList)
}
}
private fun BillingClient.queryPurchaseHistoryAsyncEnsuringOneResponse(
skuType: String,
listener: PurchaseHistoryResponseListener
) {
var hasResponded = false
queryPurchaseHistoryAsync(skuType) { billingResult, purchaseHistory ->
synchronized(this@BillingWrapper) {
if (hasResponded) {
log(
LogIntent.GOOGLE_ERROR,
RestoreStrings.EXTRA_QUERY_PURCHASE_HISTORY_RESPONSE.format(billingResult.responseCode)
)
return@queryPurchaseHistoryAsync
}
hasResponded = true
}
listener.onPurchaseHistoryResponse(billingResult, purchaseHistory)
}
}
}