-
-
Notifications
You must be signed in to change notification settings - Fork 666
/
Copy pathRNIapModule.kt
757 lines (706 loc) · 33.8 KB
/
RNIapModule.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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
package com.dooboolab.rniap
import android.util.Log
import com.android.billingclient.api.AcknowledgePurchaseParams
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.BillingFlowParams.SubscriptionUpdateParams
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.ConsumeParams
import com.android.billingclient.api.ConsumeResponseListener
import com.android.billingclient.api.ProductDetails
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.PurchaseHistoryRecord
import com.android.billingclient.api.PurchasesUpdatedListener
import com.android.billingclient.api.QueryProductDetailsParams
import com.android.billingclient.api.QueryPurchaseHistoryParams
import com.android.billingclient.api.QueryPurchasesParams
import com.android.billingclient.api.UserChoiceBillingListener
import com.android.billingclient.api.UserChoiceDetails
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.LifecycleEventListener
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.PromiseImpl
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableType
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
import com.facebook.react.bridge.WritableNativeArray
import com.facebook.react.bridge.WritableNativeMap
import com.facebook.react.module.annotations.ReactModule
import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
@ReactModule(name = RNIapModule.TAG)
class RNIapModule(
private val reactContext: ReactApplicationContext,
private val builder: BillingClient.Builder = BillingClient.newBuilder(reactContext).enablePendingPurchases(),
private val googleApiAvailability: GoogleApiAvailability = GoogleApiAvailability.getInstance(),
) : ReactContextBaseJavaModule(reactContext),
PurchasesUpdatedListener,
UserChoiceBillingListener {
private var billingClientCache: BillingClient? = null
private val skus: MutableMap<String, ProductDetails> = mutableMapOf()
override fun getName(): String = TAG
fun ensureConnection(
promise: Promise,
callback: (billingClient: BillingClient) -> Unit,
) {
val billingClient = billingClientCache
if (billingClient?.isReady == true) {
callback(billingClient)
return
} else {
val nested =
PromiseImpl(
{
if (it.isNotEmpty() && it[0] is Boolean && it[0] as Boolean) {
val connectedBillingClient = billingClientCache
if (connectedBillingClient?.isReady == true) {
callback(connectedBillingClient)
} else {
promise.safeReject(PromiseUtils.E_NOT_PREPARED, "Unable to auto-initialize connection")
}
} else {
promise.safeReject(PromiseUtils.E_UNKNOWN, "ensureConnection - incorrect parameter in resolve")
Log.i(TAG, "Incorrect parameter in resolve")
}
},
{
var errorCode: String? = null
var errorMessage: String? = null
if (it.size > 1 && it[0] is String && it[1] is String) {
errorCode = it[0] as String
errorMessage = it[1] as String
} else if (it.isNotEmpty() && it[0] is WritableNativeMap) {
val errorMap = it[0] as WritableNativeMap
errorCode = errorMap.getString("code")
errorMessage = errorMap.getString("message")
}
if (errorCode is String && errorMessage is String) {
promise.safeReject(
errorCode,
errorMessage,
)
} else {
promise.safeReject(PromiseUtils.E_UNKNOWN, "ensureConnection - incorrect parameter in reject")
Log.i(TAG, "Incorrect parameters in reject")
}
},
)
initConnection(nested)
}
}
@ReactMethod
fun isFeatureSupported(
feature: String,
promise: Promise,
) {
ensureConnection(
promise,
) { billingClient ->
val f =
when (feature) {
"IN_APP_MESSAGING" ->
BillingClient.FeatureType.IN_APP_MESSAGING
"PRICE_CHANGE_CONFIRMATION" ->
BillingClient.FeatureType.PRICE_CHANGE_CONFIRMATION
"PRODUCT_DETAILS" ->
BillingClient.FeatureType.PRODUCT_DETAILS
"SUBSCRIPTIONS" ->
BillingClient.FeatureType.SUBSCRIPTIONS
"SUBSCRIPTIONS_UPDATE" ->
BillingClient.FeatureType.SUBSCRIPTIONS_UPDATE
else -> {
promise.safeReject("Invalid Feature name")
return@ensureConnection
}
}
promise.safeResolve(billingClient.isFeatureSupported(f))
}
}
@ReactMethod
fun initConnection(promise: Promise) {
if (googleApiAvailability.isGooglePlayServicesAvailable(reactContext)
!= ConnectionResult.SUCCESS
) {
Log.i(TAG, "Google Play Services are not available on this device")
promise.safeReject(PromiseUtils.E_NOT_PREPARED, "Google Play Services are not available on this device")
return
}
if (billingClientCache?.isReady == true) {
Log.i(
TAG,
"Already initialized, you should only call initConnection() once when your app starts",
)
promise.safeResolve(true)
return
}
builder.setListener(this).enableUserChoiceBilling(this).build().also {
billingClientCache = it
it.startConnection(
object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (!isValidResult(billingResult, promise)) return
promise.safeResolve(true)
}
override fun onBillingServiceDisconnected() {
Log.i(TAG, "Billing service disconnected")
}
},
)
}
}
@ReactMethod
fun endConnection(promise: Promise) {
billingClientCache?.endConnection()
billingClientCache = null
skus.clear()
PromiseUtils.rejectAllPendingPromises()
promise.safeResolve(true)
}
private fun consumeItems(
purchases: List<Purchase>,
promise: Promise,
expectedResponseCode: Int = BillingClient.BillingResponseCode.OK,
) {
for (purchase in purchases) {
ensureConnection(
promise,
) { billingClient ->
val consumeParams =
ConsumeParams
.newBuilder()
.setPurchaseToken(purchase.purchaseToken)
.build()
val listener =
ConsumeResponseListener { billingResult: BillingResult, outToken: String? ->
if (billingResult.responseCode != expectedResponseCode) {
PlayUtils.rejectPromiseWithBillingError(
promise,
billingResult.responseCode,
)
return@ConsumeResponseListener
}
promise.safeResolve(true)
}
billingClient.consumeAsync(consumeParams, listener)
}
}
}
@ReactMethod
fun flushFailedPurchasesCachedAsPending(promise: Promise) {
ensureConnection(
promise,
) { billingClient ->
billingClient.queryPurchasesAsync(
QueryPurchasesParams
.newBuilder()
.setProductType(
BillingClient.ProductType.INAPP,
).build(),
) { billingResult: BillingResult, list: List<Purchase>? ->
if (!isValidResult(billingResult, promise)) return@queryPurchasesAsync
if (list == null) {
// No purchases found
promise.safeResolve(false)
return@queryPurchasesAsync
}
// we only want to try to consume PENDING items, in order to force cache-refresh
// for them
val pendingPurchases = list.filter { it.purchaseState == Purchase.PurchaseState.PENDING }
if (pendingPurchases.isEmpty()) {
promise.safeResolve(false)
return@queryPurchasesAsync
}
consumeItems(
pendingPurchases,
promise,
BillingClient.BillingResponseCode.ITEM_NOT_OWNED,
)
}
}
}
@ReactMethod
fun getItemsByType(
type: String,
skuArr: ReadableArray,
promise: Promise,
) {
ensureConnection(promise) { billingClient ->
val skuList = mutableListOf<QueryProductDetailsParams.Product>()
for (i in 0 until skuArr.size()) {
if (skuArr.getType(i) == ReadableType.String) {
skuArr.getString(i)?.let { sku ->
skuList.add(
QueryProductDetailsParams.Product
.newBuilder()
.setProductId(sku)
.setProductType(type)
.build(),
)
}
}
}
if (skuList.isEmpty()) {
promise.safeReject("EMPTY_SKU_LIST", "The SKU list is empty.")
return@ensureConnection
}
val params =
QueryProductDetailsParams
.newBuilder()
.setProductList(skuList)
.build()
billingClient.queryProductDetailsAsync(params) { billingResult, skuDetailsList ->
if (!isValidResult(billingResult, promise)) return@queryProductDetailsAsync
val items = Arguments.createArray()
for (skuDetails in skuDetailsList) {
skus[skuDetails.productId] = skuDetails
val item = Arguments.createMap()
item.putString("productId", skuDetails.productId)
item.putString("title", skuDetails.title)
item.putString("description", skuDetails.description)
item.putString("productType", skuDetails.productType)
item.putString("name", skuDetails.name)
skuDetails.oneTimePurchaseOfferDetails?.let {
val oneTimePurchaseOfferDetails =
Arguments.createMap().apply {
putString("priceCurrencyCode", it.priceCurrencyCode)
putString("formattedPrice", it.formattedPrice)
putString("priceAmountMicros", it.priceAmountMicros.toString())
}
item.putMap("oneTimePurchaseOfferDetails", oneTimePurchaseOfferDetails)
}
skuDetails.subscriptionOfferDetails?.let {
val subscriptionOfferDetails = Arguments.createArray()
it.forEach { subscriptionOfferDetailsItem ->
val offerDetails =
Arguments.createMap().apply {
putString("basePlanId", subscriptionOfferDetailsItem.basePlanId)
putString("offerId", subscriptionOfferDetailsItem.offerId)
putString("offerToken", subscriptionOfferDetailsItem.offerToken)
val offerTags = Arguments.createArray()
subscriptionOfferDetailsItem.offerTags.forEach { offerTag ->
offerTags.pushString(offerTag)
}
putArray("offerTags", offerTags)
val pricingPhasesList = Arguments.createArray()
subscriptionOfferDetailsItem.pricingPhases.pricingPhaseList.forEach { pricingPhaseItem ->
val pricingPhase =
Arguments.createMap().apply {
putString("formattedPrice", pricingPhaseItem.formattedPrice)
putString("priceCurrencyCode", pricingPhaseItem.priceCurrencyCode)
putString("billingPeriod", pricingPhaseItem.billingPeriod)
putInt("billingCycleCount", pricingPhaseItem.billingCycleCount)
putString("priceAmountMicros", pricingPhaseItem.priceAmountMicros.toString())
putInt("recurrenceMode", pricingPhaseItem.recurrenceMode)
}
pricingPhasesList.pushMap(pricingPhase)
}
val pricingPhases =
Arguments.createMap().apply {
putArray("pricingPhaseList", pricingPhasesList)
}
putMap("pricingPhases", pricingPhases)
}
subscriptionOfferDetails.pushMap(offerDetails)
}
item.putArray("subscriptionOfferDetails", subscriptionOfferDetails)
}
items.pushMap(item)
}
promise.safeResolve(items)
}
}
}
/**
* Rejects promise with billing code if BillingResult is not OK
*/
private fun isValidResult(
billingResult: BillingResult,
promise: Promise,
): Boolean {
Log.d(TAG, "responseCode: " + billingResult.responseCode)
if (billingResult.responseCode != BillingClient.BillingResponseCode.OK) {
PlayUtils.rejectPromiseWithBillingError(promise, billingResult.responseCode)
return false
}
return true
}
@ReactMethod
fun getAvailableItemsByType(
type: String,
promise: Promise,
) {
ensureConnection(
promise,
) { billingClient ->
val items = WritableNativeArray()
billingClient.queryPurchasesAsync(
QueryPurchasesParams
.newBuilder()
.setProductType(
if (type == "subs") BillingClient.ProductType.SUBS else BillingClient.ProductType.INAPP,
).build(),
) { billingResult: BillingResult, purchases: List<Purchase>? ->
if (!isValidResult(billingResult, promise)) return@queryPurchasesAsync
purchases?.forEach { purchase ->
val item = WritableNativeMap()
item.putString("productId", purchase.products[0]) // kept for convenience/backward-compatibility. productIds has the complete list
val products = Arguments.createArray()
purchase.products.forEach { products.pushString(it) }
item.putArray("productIds", products)
item.putString("transactionId", purchase.orderId)
item.putDouble("transactionDate", purchase.purchaseTime.toDouble())
item.putString("transactionReceipt", purchase.originalJson)
item.putString("orderId", purchase.orderId)
item.putString("purchaseToken", purchase.purchaseToken)
item.putString("developerPayloadAndroid", purchase.developerPayload)
item.putString("signatureAndroid", purchase.signature)
item.putInt("purchaseStateAndroid", purchase.purchaseState)
item.putBoolean("isAcknowledgedAndroid", purchase.isAcknowledged)
item.putString("packageNameAndroid", purchase.packageName)
item.putString(
"obfuscatedAccountIdAndroid",
purchase.accountIdentifiers?.obfuscatedAccountId,
)
item.putString(
"obfuscatedProfileIdAndroid",
purchase.accountIdentifiers?.obfuscatedProfileId,
)
if (type == BillingClient.ProductType.SUBS) {
item.putBoolean("autoRenewingAndroid", purchase.isAutoRenewing)
}
items.pushMap(item)
}
promise.safeResolve(items)
}
}
}
@ReactMethod
fun getPurchaseHistoryByType(
type: String,
promise: Promise,
) {
ensureConnection(
promise,
) { billingClient ->
billingClient.queryPurchaseHistoryAsync(
QueryPurchaseHistoryParams
.newBuilder()
.setProductType(
if (type == "subs") BillingClient.ProductType.SUBS else BillingClient.ProductType.INAPP,
).build(),
) { billingResult: BillingResult, purchaseHistoryRecordList: MutableList<PurchaseHistoryRecord>? ->
if (!isValidResult(billingResult, promise)) return@queryPurchaseHistoryAsync
Log.d(TAG, purchaseHistoryRecordList.toString())
val items = Arguments.createArray()
purchaseHistoryRecordList?.forEach { purchase ->
val item = Arguments.createMap()
item.putString("productId", purchase.products[0])
val products = Arguments.createArray()
purchase.products.forEach { products.pushString(it) }
item.putArray("productIds", products)
item.putDouble("transactionDate", purchase.purchaseTime.toDouble())
item.putString("transactionReceipt", purchase.originalJson)
item.putString("purchaseToken", purchase.purchaseToken)
item.putString("dataAndroid", purchase.originalJson)
item.putString("signatureAndroid", purchase.signature)
item.putString("developerPayload", purchase.developerPayload)
items.pushMap(item)
}
promise.safeResolve(items)
}
}
}
@ReactMethod
fun buyItemByType(
type: String,
skuArr: ReadableArray,
purchaseToken: String?,
externalTransactionID: String?,
replacementMode: Int,
obfuscatedAccountId: String?,
obfuscatedProfileId: String?,
offerTokenArr: ReadableArray, // New parameter in V5
isOfferPersonalized: Boolean, // New parameter in V5
promise: Promise,
) {
val activity = currentActivity
if (activity == null) {
promise.safeReject(PromiseUtils.E_UNKNOWN, "getCurrentActivity returned null")
return
}
ensureConnection(
promise,
) { billingClient ->
PromiseUtils.addPromiseForKey(
PROMISE_BUY_ITEM,
promise,
)
if (type == BillingClient.ProductType.SUBS && skuArr.size() != offerTokenArr.size()) {
val debugMessage =
"The number of skus (${skuArr.size()}) must match: the number of offerTokens (${offerTokenArr.size()}) for Subscriptions"
val error = Arguments.createMap()
error.putString("debugMessage", debugMessage)
error.putString("code", PROMISE_BUY_ITEM)
error.putString("message", debugMessage)
sendEvent(reactContext, "purchase-error", error)
promise.safeReject(PROMISE_BUY_ITEM, debugMessage)
return@ensureConnection
}
val productParamsList =
skuArr.toArrayList().map { it.toString() }.mapIndexed { index, sku ->
val selectedSku: ProductDetails? = skus[sku]
if (selectedSku == null) {
val debugMessage =
"The sku was not found. Please fetch products first by calling getItems"
val error = Arguments.createMap()
error.putString("debugMessage", debugMessage)
error.putString("code", PROMISE_BUY_ITEM)
error.putString("message", debugMessage)
error.putString("productId", sku)
sendEvent(reactContext, "purchase-error", error)
promise.safeReject(PROMISE_BUY_ITEM, debugMessage)
return@ensureConnection
}
var productDetailParams = BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(selectedSku)
if (type == BillingClient.ProductType.SUBS) {
offerTokenArr.getString(index)?.let { offerToken ->
// null check for older versions of RN
productDetailParams = productDetailParams.setOfferToken(offerToken)
}
}
productDetailParams.build()
}
val builder = BillingFlowParams.newBuilder()
builder.setProductDetailsParamsList(productParamsList).setIsOfferPersonalized(isOfferPersonalized)
val subscriptionUpdateParamsBuilder = SubscriptionUpdateParams.newBuilder()
if (externalTransactionID != null) {
subscriptionUpdateParamsBuilder.setOriginalExternalTransactionId(externalTransactionID)
}
if (purchaseToken != null) {
subscriptionUpdateParamsBuilder.setOldPurchaseToken(purchaseToken)
if (type == BillingClient.ProductType.SUBS && replacementMode != -1) {
val replacementMode =
when (replacementMode) {
BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.CHARGE_PRORATED_PRICE -> BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.CHARGE_PRORATED_PRICE
BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.WITHOUT_PRORATION -> BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.WITHOUT_PRORATION
BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.DEFERRED -> BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.DEFERRED
BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.WITH_TIME_PRORATION -> BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.WITH_TIME_PRORATION
BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.CHARGE_FULL_PRICE -> BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.CHARGE_FULL_PRICE
else -> BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.UNKNOWN_REPLACEMENT_MODE
}
subscriptionUpdateParamsBuilder.setSubscriptionReplacementMode(replacementMode)
}
if (purchaseToken != null) {
val subscriptionUpdateParams = subscriptionUpdateParamsBuilder.build()
builder.setSubscriptionUpdateParams(subscriptionUpdateParams)
}
}
if (obfuscatedAccountId != null) {
builder.setObfuscatedAccountId(obfuscatedAccountId)
}
if (obfuscatedProfileId != null) {
builder.setObfuscatedProfileId(obfuscatedProfileId)
}
val flowParams = builder.build()
val billingResultCode = billingClient.launchBillingFlow(activity, flowParams).responseCode
if (billingResultCode != BillingClient.BillingResponseCode.OK) {
val errorData = PlayUtils.getBillingResponseData(billingResultCode)
promise.safeReject(errorData.code, errorData.message)
}
}
}
@ReactMethod
fun acknowledgePurchase(
token: String,
developerPayLoad: String?,
promise: Promise,
) {
ensureConnection(
promise,
) { billingClient ->
val acknowledgePurchaseParams =
AcknowledgePurchaseParams
.newBuilder()
.setPurchaseToken(
token,
).build()
billingClient.acknowledgePurchase(
acknowledgePurchaseParams,
) { billingResult: BillingResult ->
if (!isValidResult(billingResult, promise)) return@acknowledgePurchase
val map = Arguments.createMap()
map.putInt("responseCode", billingResult.responseCode)
map.putString("debugMessage", billingResult.debugMessage)
val errorData = PlayUtils.getBillingResponseData(billingResult.responseCode)
map.putString("code", errorData.code)
map.putString("message", errorData.message)
promise.safeResolve(map)
}
}
}
@ReactMethod
fun consumeProduct(
token: String,
developerPayLoad: String?,
promise: Promise,
) {
val params = ConsumeParams.newBuilder().setPurchaseToken(token).build()
ensureConnection(
promise,
) { billingClient ->
billingClient.consumeAsync(
params,
) { billingResult: BillingResult, purchaseToken: String? ->
if (!isValidResult(billingResult, promise)) return@consumeAsync
val map = Arguments.createMap()
map.putInt("responseCode", billingResult.responseCode)
map.putString("debugMessage", billingResult.debugMessage)
val errorData = PlayUtils.getBillingResponseData(billingResult.responseCode)
map.putString("code", errorData.code)
map.putString("message", errorData.message)
map.putString("purchaseToken", purchaseToken)
promise.safeResolve(map)
}
}
}
override fun onPurchasesUpdated(
billingResult: BillingResult,
purchases: List<Purchase>?,
) {
val responseCode = billingResult.responseCode
if (responseCode != BillingClient.BillingResponseCode.OK) {
val error = Arguments.createMap()
error.putInt("responseCode", responseCode)
error.putString("debugMessage", billingResult.debugMessage)
val errorData = PlayUtils.getBillingResponseData(responseCode)
error.putString("code", errorData.code)
error.putString("message", errorData.message)
sendEvent(reactContext, "purchase-error", error)
PlayUtils.rejectPromisesWithBillingError(PROMISE_BUY_ITEM, responseCode)
return
}
if (purchases != null) {
val promiseItems: WritableArray = Arguments.createArray()
purchases.forEach { purchase ->
val item = Arguments.createMap()
item.putString("productId", purchase.products[0])
val products = Arguments.createArray()
purchase.products.forEach { products.pushString(it) }
item.putArray("productIds", products)
item.putString("transactionId", purchase.orderId)
item.putDouble("transactionDate", purchase.purchaseTime.toDouble())
item.putString("transactionReceipt", purchase.originalJson)
item.putString("purchaseToken", purchase.purchaseToken)
item.putString("dataAndroid", purchase.originalJson)
item.putString("signatureAndroid", purchase.signature)
item.putBoolean("autoRenewingAndroid", purchase.isAutoRenewing)
item.putBoolean("isAcknowledgedAndroid", purchase.isAcknowledged)
item.putInt("purchaseStateAndroid", purchase.purchaseState)
item.putString("packageNameAndroid", purchase.packageName)
item.putString("developerPayloadAndroid", purchase.developerPayload)
val accountIdentifiers = purchase.accountIdentifiers
if (accountIdentifiers != null) {
item.putString(
"obfuscatedAccountIdAndroid",
accountIdentifiers.obfuscatedAccountId,
)
item.putString(
"obfuscatedProfileIdAndroid",
accountIdentifiers.obfuscatedProfileId,
)
}
promiseItems.pushMap(item.copy())
sendEvent(reactContext, "purchase-updated", item)
}
PromiseUtils.resolvePromisesForKey(PROMISE_BUY_ITEM, promiseItems)
} else {
val result = Arguments.createMap()
result.putInt("responseCode", billingResult.responseCode)
result.putString("debugMessage", billingResult.debugMessage)
result.putString(
"extraMessage",
"The purchases are null. This is a normal behavior if you have requested DEFERRED" +
" proration. If not please report an issue.",
)
sendEvent(reactContext, "purchase-updated", result)
PromiseUtils.resolvePromisesForKey(PROMISE_BUY_ITEM, null)
}
}
private fun sendUnconsumedPurchases(promise: Promise) {
ensureConnection(
promise,
) { billingClient ->
val types = arrayOf(BillingClient.ProductType.INAPP, BillingClient.ProductType.SUBS)
for (type in types) {
billingClient.queryPurchasesAsync(
QueryPurchasesParams
.newBuilder()
.setProductType(
type,
).build(),
) { billingResult: BillingResult, list: List<Purchase> ->
if (!isValidResult(billingResult, promise)) return@queryPurchasesAsync
val unacknowledgedPurchases = list.filter { !it.isAcknowledged }
onPurchasesUpdated(billingResult, unacknowledgedPurchases)
}
}
promise.safeResolve(true)
}
}
@ReactMethod
fun startListening(promise: Promise) {
sendUnconsumedPurchases(promise)
}
@ReactMethod
fun addListener(eventName: String) {
// Keep: Required for RN built-in Event Emitter Calls.
}
@ReactMethod
fun removeListeners(count: Double) {
// Keep: Required for RN built-in Event Emitter Calls.
}
@ReactMethod
fun getPackageName(promise: Promise) = promise.resolve(reactApplicationContext.packageName)
private fun sendEvent(
reactContext: ReactContext,
eventName: String,
params: WritableMap?,
) {
reactContext
.getJSModule(RCTDeviceEventEmitter::class.java)
.emit(eventName, params)
}
companion object {
private const val PROMISE_BUY_ITEM = "PROMISE_BUY_ITEM"
private const val USER_ALTER_ITEM = "USER_ALTER_ITEM"
const val TAG = "RNIapModule"
}
init {
val lifecycleEventListener: LifecycleEventListener =
object : LifecycleEventListener {
override fun onHostResume() {}
override fun onHostPause() {}
override fun onHostDestroy() {
billingClientCache?.endConnection()
billingClientCache = null
}
}
reactContext.addLifecycleEventListener(lifecycleEventListener)
}
override fun userSelectedAlternativeBilling(userChoiceDetails: UserChoiceDetails) {
val products = userChoiceDetails.products
val externalToken = userChoiceDetails.externalTransactionToken
val result = Arguments.createMap()
result.putString("products", userChoiceDetails.products.toString())
result.putString("externalTransactionToken", userChoiceDetails.externalTransactionToken)
sendEvent(reactContext, "user-alternative-billing", result)
PromiseUtils.resolvePromisesForKey(USER_ALTER_ITEM, null)
}
}