@tenthbilling/expo 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/android/build.gradle +23 -0
  4. package/android/src/main/AndroidManifest.xml +2 -0
  5. package/android/src/main/java/com/tenthbilling/expo/TenthStoreModule.kt +669 -0
  6. package/app.plugin.js +3 -0
  7. package/dist/api/client.d.ts +107 -0
  8. package/dist/api/client.js +139 -0
  9. package/dist/api/types.d.ts +17 -0
  10. package/dist/api/types.js +1 -0
  11. package/dist/cache.d.ts +23 -0
  12. package/dist/cache.js +40 -0
  13. package/dist/errors.d.ts +18 -0
  14. package/dist/errors.js +42 -0
  15. package/dist/generated/openapi.d.ts +3208 -0
  16. package/dist/generated/openapi.js +1 -0
  17. package/dist/identity.d.ts +35 -0
  18. package/dist/identity.js +92 -0
  19. package/dist/index.d.ts +12 -0
  20. package/dist/index.js +10 -0
  21. package/dist/keys.d.ts +8 -0
  22. package/dist/keys.js +14 -0
  23. package/dist/native/module.d.ts +12 -0
  24. package/dist/native/module.js +14 -0
  25. package/dist/native/spec.d.ts +166 -0
  26. package/dist/native/spec.js +1 -0
  27. package/dist/products.d.ts +32 -0
  28. package/dist/products.js +213 -0
  29. package/dist/react/Paywall.d.ts +28 -0
  30. package/dist/react/Paywall.js +19 -0
  31. package/dist/react/TenthProvider.d.ts +11 -0
  32. package/dist/react/TenthProvider.js +23 -0
  33. package/dist/react/context.d.ts +4 -0
  34. package/dist/react/context.js +8 -0
  35. package/dist/react/hooks.d.ts +48 -0
  36. package/dist/react/hooks.js +68 -0
  37. package/dist/react/present.d.ts +15 -0
  38. package/dist/react/present.js +47 -0
  39. package/dist/react/usePaywall.d.ts +12 -0
  40. package/dist/react/usePaywall.js +109 -0
  41. package/dist/storage/storage.d.ts +14 -0
  42. package/dist/storage/storage.js +63 -0
  43. package/dist/storage/storage.web.d.ts +4 -0
  44. package/dist/storage/storage.web.js +35 -0
  45. package/dist/store/apple.d.ts +19 -0
  46. package/dist/store/apple.js +127 -0
  47. package/dist/store/context.d.ts +46 -0
  48. package/dist/store/context.js +21 -0
  49. package/dist/store/google.d.ts +22 -0
  50. package/dist/store/google.js +145 -0
  51. package/dist/store/preview.d.ts +16 -0
  52. package/dist/store/preview.js +68 -0
  53. package/dist/stripe/appearance.d.ts +47 -0
  54. package/dist/stripe/appearance.js +44 -0
  55. package/dist/stripe/flows.d.ts +23 -0
  56. package/dist/stripe/flows.js +145 -0
  57. package/dist/stripe/payment-sheet.d.ts +1 -0
  58. package/dist/stripe/payment-sheet.js +24 -0
  59. package/dist/stripe/sheet-registry.d.ts +16 -0
  60. package/dist/stripe/sheet-registry.js +7 -0
  61. package/dist/stripe/web-step.d.ts +10 -0
  62. package/dist/stripe/web-step.js +4 -0
  63. package/dist/stripe/web-step.web.d.ts +4 -0
  64. package/dist/stripe/web-step.web.js +55 -0
  65. package/dist/tenth.d.ts +125 -0
  66. package/dist/tenth.js +329 -0
  67. package/dist/updates.d.ts +15 -0
  68. package/dist/updates.js +30 -0
  69. package/expo-module.config.json +9 -0
  70. package/ios/CountryCodes.swift +52 -0
  71. package/ios/TenthBilling.podspec +31 -0
  72. package/ios/TenthStoreExceptions.swift +88 -0
  73. package/ios/TenthStoreMapping.swift +108 -0
  74. package/ios/TenthStoreModule.swift +213 -0
  75. package/ios/TenthStoreRecords.swift +105 -0
  76. package/package.json +94 -3
  77. package/plugin/withTenth.js +249 -0
@@ -0,0 +1,669 @@
1
+ // Tenth's Play Billing bridge. The JS side's contract is AndroidStoreModule and AndroidStoreEvents.
2
+ //
3
+ // THIS MODULE NEVER ACKNOWLEDGES OR CONSUMES A PURCHASE, and must never call Play Billing's
4
+ // acknowledge or consume APIs. Tenth's server does both, after it has recorded the purchase
5
+ // If the app finalized purchases itself, a purchase Tenth refused or never
6
+ // saw would stay paid for with nobody given access; left unacknowledged, Google refunds it.
7
+ //
8
+ // The module only talks to the store: it never decides access and never verifies anything.
9
+ // Nothing here logs. No purchase token, order ID, offer token or account ID is ever printed, and
10
+ // rejections carry only a stable code plus Play's numeric response code.
11
+
12
+ package com.tenthbilling.expo
13
+
14
+ import android.content.ActivityNotFoundException
15
+ import android.content.Intent
16
+ import android.net.Uri
17
+ import com.android.billingclient.api.BillingClient
18
+ import com.android.billingclient.api.BillingClient.BillingResponseCode
19
+ import com.android.billingclient.api.BillingClient.ProductType
20
+ import com.android.billingclient.api.BillingClientStateListener
21
+ import com.android.billingclient.api.BillingFlowParams
22
+ import com.android.billingclient.api.BillingResult
23
+ import com.android.billingclient.api.GetBillingConfigParams
24
+ import com.android.billingclient.api.PendingPurchasesParams
25
+ import com.android.billingclient.api.ProductDetails
26
+ import com.android.billingclient.api.Purchase
27
+ import com.android.billingclient.api.PurchasesUpdatedListener
28
+ import com.android.billingclient.api.QueryProductDetailsParams
29
+ import com.android.billingclient.api.QueryPurchasesParams
30
+ import expo.modules.kotlin.Promise
31
+ import expo.modules.kotlin.modules.Module
32
+ import expo.modules.kotlin.modules.ModuleDefinition
33
+ import expo.modules.kotlin.records.Field
34
+ import expo.modules.kotlin.records.Record
35
+ import java.util.Locale
36
+
37
+ private const val MODULE_NAME = "TenthStore"
38
+ private const val EVENT_PURCHASES_UPDATED = "onPurchasesUpdated"
39
+ private const val TYPE_SUBS = "subs"
40
+ private const val TYPE_INAPP = "inapp"
41
+ private const val MAX_PRODUCTS = 100
42
+
43
+ // Input checks. Everything from JS is untrusted: refused when it doesn't match, never rewritten.
44
+ private val PRODUCT_ID = Regex("^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$")
45
+ private val OPAQUE_TOKEN = Regex("^[\\x21-\\x7E]{1,4096}$")
46
+ private val OBFUSCATED_ACCOUNT_ID = Regex("^[A-Za-z0-9._-]{1,64}$")
47
+ private val PACKAGE_NAME = Regex("^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+$")
48
+ private val COUNTRY_CODE = Regex("^[A-Za-z]{2}$")
49
+
50
+ /** Play's ReplacementMode values accepted for a plan change. */
51
+ private val REPLACEMENT_MODES = setOf(
52
+ BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.WITH_TIME_PRORATION,
53
+ BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.CHARGE_PRORATED_PRICE,
54
+ BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.WITHOUT_PRORATION,
55
+ BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.CHARGE_FULL_PRICE,
56
+ BillingFlowParams.SubscriptionUpdateParams.ReplacementMode.DEFERRED
57
+ )
58
+
59
+ class ProductQuery : Record {
60
+ @Field
61
+ val productId: String = ""
62
+
63
+ @Field
64
+ val type: String = ""
65
+ }
66
+
67
+ class PurchaseInput : Record {
68
+ @Field
69
+ val productId: String = ""
70
+
71
+ @Field
72
+ val type: String = ""
73
+
74
+ @Field
75
+ val offerToken: String? = null
76
+
77
+ @Field
78
+ val obfuscatedAccountId: String = ""
79
+
80
+ @Field
81
+ val oldPurchaseToken: String? = null
82
+
83
+ @Field
84
+ val replacementMode: Int? = null
85
+ }
86
+
87
+ /** The purchase flow currently on screen. Play allows one at a time, and so does the module. */
88
+ private class InFlightPurchase(val productId: String, val type: String, val promise: Promise)
89
+
90
+ class TenthStoreModule : Module() {
91
+ private val lock = Any()
92
+ private var billingClient: BillingClient? = null
93
+ private var connecting = false
94
+ private val connectWaiters = mutableListOf<(BillingResult) -> Unit>()
95
+ private var inFlight: InFlightPurchase? = null
96
+
97
+ /** productId → "subs" | "inapp", learned from product and purchase queries. */
98
+ private val productTypes = mutableMapOf<String, String>()
99
+
100
+ private val purchasesListener = PurchasesUpdatedListener { result, purchases ->
101
+ onPurchasesUpdated(result, purchases.orEmpty())
102
+ }
103
+
104
+ override fun definition() = ModuleDefinition {
105
+ Name(MODULE_NAME)
106
+
107
+ Events(EVENT_PURCHASES_UPDATED)
108
+
109
+ OnDestroy {
110
+ val client: BillingClient?
111
+ synchronized(lock) {
112
+ client = billingClient
113
+ billingClient = null
114
+ connecting = false
115
+ connectWaiters.clear()
116
+ inFlight = null
117
+ }
118
+ client?.endConnection()
119
+ }
120
+
121
+ AsyncFunction("isReady") { promise: Promise ->
122
+ val client = client()
123
+ if (client == null) {
124
+ promise.resolve(false)
125
+ return@AsyncFunction
126
+ }
127
+ connect(client) { setup -> promise.resolve(setup.responseCode == BillingResponseCode.OK) }
128
+ }
129
+
130
+ AsyncFunction("storefrontCountry") { promise: Promise ->
131
+ val client = client()
132
+ if (client == null) {
133
+ promise.resolve(null)
134
+ return@AsyncFunction
135
+ }
136
+ connect(client) { setup ->
137
+ if (setup.responseCode != BillingResponseCode.OK) {
138
+ promise.resolve(null)
139
+ return@connect
140
+ }
141
+ client.getBillingConfigAsync(GetBillingConfigParams.newBuilder().build()) { result, config ->
142
+ val country = config?.countryCode
143
+ if (result.responseCode == BillingResponseCode.OK && country != null && COUNTRY_CODE.matches(country)) {
144
+ promise.resolve(country.uppercase(Locale.ROOT))
145
+ } else {
146
+ promise.resolve(null)
147
+ }
148
+ }
149
+ }
150
+ }
151
+
152
+ AsyncFunction("getProducts") { products: List<ProductQuery>, promise: Promise ->
153
+ if (products.size > MAX_PRODUCTS) {
154
+ rejectInvalid(promise, "products")
155
+ return@AsyncFunction
156
+ }
157
+ for (query in products) {
158
+ if (!PRODUCT_ID.matches(query.productId) || !isProductType(query.type)) {
159
+ rejectInvalid(promise, "products")
160
+ return@AsyncFunction
161
+ }
162
+ }
163
+ val subs = products.filter { it.type == TYPE_SUBS }.map { it.productId }.distinct()
164
+ val inapp = products.filter { it.type == TYPE_INAPP }.map { it.productId }.distinct()
165
+ if (subs.isEmpty() && inapp.isEmpty()) {
166
+ promise.resolve(emptyList<Any?>())
167
+ return@AsyncFunction
168
+ }
169
+ withClient(promise) { client ->
170
+ // Play refuses a query that mixes product types, so subs and inapp go separately.
171
+ queryDetails(client, subs, TYPE_SUBS) { subsResult, subsDetails ->
172
+ if (subsResult.responseCode != BillingResponseCode.OK) {
173
+ rejectBilling(promise, subsResult.responseCode)
174
+ return@queryDetails
175
+ }
176
+ queryDetails(client, inapp, TYPE_INAPP) { inappResult, inappDetails ->
177
+ if (inappResult.responseCode != BillingResponseCode.OK) {
178
+ rejectBilling(promise, inappResult.responseCode)
179
+ return@queryDetails
180
+ }
181
+ promise.resolve((subsDetails + inappDetails).mapNotNull { mapProduct(it) })
182
+ }
183
+ }
184
+ }
185
+ }
186
+
187
+ AsyncFunction("purchase") { input: PurchaseInput, promise: Promise ->
188
+ val invalid = invalidPurchaseField(input)
189
+ if (invalid != null) {
190
+ rejectInvalid(promise, invalid)
191
+ return@AsyncFunction
192
+ }
193
+ if (appContext.currentActivity == null) {
194
+ promise.reject("ui_unavailable", "No activity to show the purchase in", null)
195
+ return@AsyncFunction
196
+ }
197
+ val flight = InFlightPurchase(input.productId, input.type, promise)
198
+ synchronized(lock) {
199
+ if (inFlight != null) {
200
+ promise.reject("purchase_in_progress", "Another purchase is in progress", null)
201
+ return@AsyncFunction
202
+ }
203
+ inFlight = flight
204
+ }
205
+ startPurchase(flight, input)
206
+ }
207
+
208
+ AsyncFunction("queryPurchases") { promise: Promise ->
209
+ withClient(promise) { client ->
210
+ queryOwned(client, TYPE_SUBS) { subsResult, subs ->
211
+ if (subsResult.responseCode != BillingResponseCode.OK) {
212
+ rejectBilling(promise, subsResult.responseCode)
213
+ return@queryOwned
214
+ }
215
+ queryOwned(client, TYPE_INAPP) { inappResult, inapp ->
216
+ if (inappResult.responseCode != BillingResponseCode.OK) {
217
+ rejectBilling(promise, inappResult.responseCode)
218
+ return@queryOwned
219
+ }
220
+ promise.resolve(
221
+ subs.map { mapPurchase(it, TYPE_SUBS) } + inapp.map { mapPurchase(it, TYPE_INAPP) }
222
+ )
223
+ }
224
+ }
225
+ }
226
+ }
227
+
228
+ AsyncFunction("showManageSubscriptions") { productId: String?, packageName: String, promise: Promise ->
229
+ if (productId != null && !PRODUCT_ID.matches(productId)) {
230
+ rejectInvalid(promise, "productId")
231
+ return@AsyncFunction
232
+ }
233
+ if (packageName.length > 255 || !PACKAGE_NAME.matches(packageName)) {
234
+ rejectInvalid(promise, "packageName")
235
+ return@AsyncFunction
236
+ }
237
+ // Play's subscription center, or one subscription's page. The query values are encoded
238
+ // by Uri.Builder, and both were validated above.
239
+ val builder = Uri.parse("https://play.google.com/store/account/subscriptions").buildUpon()
240
+ if (productId != null) {
241
+ builder.appendQueryParameter("sku", productId)
242
+ builder.appendQueryParameter("package", packageName)
243
+ }
244
+ val intent = Intent(Intent.ACTION_VIEW, builder.build())
245
+ val activity = appContext.currentActivity
246
+ if (activity == null) {
247
+ promise.reject("ui_unavailable", "No activity to open the subscription center from", null)
248
+ return@AsyncFunction
249
+ }
250
+ activity.runOnUiThread {
251
+ try {
252
+ activity.startActivity(intent)
253
+ promise.resolve(null)
254
+ } catch (_: ActivityNotFoundException) {
255
+ promise.reject("ui_unavailable", "Nothing can open the subscription center", null)
256
+ }
257
+ }
258
+ }
259
+ }
260
+
261
+ // region Connection
262
+
263
+ private fun client(): BillingClient? {
264
+ synchronized(lock) {
265
+ billingClient?.let { return it }
266
+ val context = appContext.reactContext?.applicationContext ?: return null
267
+ val created = BillingClient.newBuilder(context)
268
+ .setListener(purchasesListener)
269
+ .enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build())
270
+ .enableAutoServiceReconnection()
271
+ .build()
272
+ billingClient = created
273
+ return created
274
+ }
275
+ }
276
+
277
+ /** Calls back once the client is connected (or failed to). Concurrent callers share one attempt. */
278
+ private fun connect(client: BillingClient, callback: (BillingResult) -> Unit) {
279
+ if (client.isReady) {
280
+ callback(billingResult(BillingResponseCode.OK))
281
+ return
282
+ }
283
+ val shouldStart: Boolean
284
+ synchronized(lock) {
285
+ connectWaiters.add(callback)
286
+ shouldStart = !connecting
287
+ connecting = true
288
+ }
289
+ if (!shouldStart) return
290
+ client.startConnection(object : BillingClientStateListener {
291
+ override fun onBillingSetupFinished(result: BillingResult) {
292
+ finishConnecting(result)
293
+ }
294
+
295
+ override fun onBillingServiceDisconnected() {
296
+ // With automatic service reconnection the library reconnects on the next call; anyone
297
+ // still waiting on this attempt is told it failed.
298
+ finishConnecting(billingResult(BillingResponseCode.SERVICE_DISCONNECTED))
299
+ }
300
+ })
301
+ }
302
+
303
+ private fun finishConnecting(result: BillingResult) {
304
+ val waiters: List<(BillingResult) -> Unit>
305
+ synchronized(lock) {
306
+ connecting = false
307
+ waiters = connectWaiters.toList()
308
+ connectWaiters.clear()
309
+ }
310
+ waiters.forEach { it(result) }
311
+ }
312
+
313
+ /** Connects, then runs [onReady]; rejects [promise] with Play's code if that fails. */
314
+ private fun withClient(promise: Promise, onReady: (BillingClient) -> Unit) {
315
+ val client = client()
316
+ if (client == null) {
317
+ promise.reject("store_unavailable", "Play Billing is not available", null)
318
+ return
319
+ }
320
+ connect(client) { setup ->
321
+ if (setup.responseCode == BillingResponseCode.OK) {
322
+ onReady(client)
323
+ } else {
324
+ rejectBilling(promise, setup.responseCode)
325
+ }
326
+ }
327
+ }
328
+
329
+ // endregion
330
+
331
+ // region Queries
332
+
333
+ private fun queryDetails(
334
+ client: BillingClient,
335
+ productIds: List<String>,
336
+ type: String,
337
+ callback: (BillingResult, List<ProductDetails>) -> Unit
338
+ ) {
339
+ if (productIds.isEmpty()) {
340
+ callback(billingResult(BillingResponseCode.OK), emptyList())
341
+ return
342
+ }
343
+ val playType = if (type == TYPE_SUBS) ProductType.SUBS else ProductType.INAPP
344
+ val params = QueryProductDetailsParams.newBuilder()
345
+ .setProductList(
346
+ productIds.map {
347
+ QueryProductDetailsParams.Product.newBuilder()
348
+ .setProductId(it)
349
+ .setProductType(playType)
350
+ .build()
351
+ }
352
+ )
353
+ .build()
354
+ client.queryProductDetailsAsync(params) { result, detailsResult ->
355
+ val details = detailsResult.productDetailsList
356
+ rememberTypes(details.map { it.productId }, type)
357
+ callback(result, details)
358
+ }
359
+ }
360
+
361
+ private fun queryOwned(client: BillingClient, type: String, callback: (BillingResult, List<Purchase>) -> Unit) {
362
+ val playType = if (type == TYPE_SUBS) ProductType.SUBS else ProductType.INAPP
363
+ client.queryPurchasesAsync(QueryPurchasesParams.newBuilder().setProductType(playType).build()) { result, purchases ->
364
+ if (result.responseCode == BillingResponseCode.OK) {
365
+ rememberTypes(purchases.flatMap { it.products }, type)
366
+ }
367
+ callback(result, purchases)
368
+ }
369
+ }
370
+
371
+ private fun rememberTypes(productIds: List<String>, type: String) {
372
+ synchronized(lock) {
373
+ productIds.forEach { productTypes[it] = type }
374
+ }
375
+ }
376
+
377
+ private fun cachedType(purchase: Purchase): String? {
378
+ synchronized(lock) {
379
+ return purchase.products.firstNotNullOfOrNull { productTypes[it] }
380
+ }
381
+ }
382
+
383
+ // endregion
384
+
385
+ // region Purchase flow
386
+
387
+ private fun startPurchase(flight: InFlightPurchase, input: PurchaseInput) {
388
+ val promise = flight.promise
389
+ val client = client()
390
+ if (client == null) {
391
+ failPurchase(flight) { promise.reject("store_unavailable", "Play Billing is not available", null) }
392
+ return
393
+ }
394
+ connect(client) { setup ->
395
+ if (setup.responseCode != BillingResponseCode.OK) {
396
+ failPurchase(flight) { rejectBilling(promise, setup.responseCode) }
397
+ return@connect
398
+ }
399
+ queryDetails(client, listOf(input.productId), input.type) { result, list ->
400
+ if (result.responseCode != BillingResponseCode.OK) {
401
+ failPurchase(flight) { rejectBilling(promise, result.responseCode) }
402
+ return@queryDetails
403
+ }
404
+ val details = list.firstOrNull { it.productId == input.productId }
405
+ if (details == null) {
406
+ failPurchase(flight) { promise.reject("product_unavailable", "The product is not available", null) }
407
+ return@queryDetails
408
+ }
409
+ val productParams = BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(details)
410
+ val offerToken = input.offerToken
411
+ if (input.type == TYPE_SUBS) {
412
+ // The token must be one of this product's offers for this customer.
413
+ val known = details.subscriptionOfferDetails.orEmpty().any { it.offerToken == offerToken }
414
+ if (offerToken == null || !known) {
415
+ failPurchase(flight) { rejectInvalid(promise, "offerToken") }
416
+ return@queryDetails
417
+ }
418
+ productParams.setOfferToken(offerToken)
419
+ } else if (offerToken != null) {
420
+ productParams.setOfferToken(offerToken)
421
+ }
422
+
423
+ val flowParams = BillingFlowParams.newBuilder()
424
+ .setProductDetailsParamsList(listOf(productParams.build()))
425
+ // How Tenth tells whose purchase this is.
426
+ .setObfuscatedAccountId(input.obfuscatedAccountId)
427
+ val oldToken = input.oldPurchaseToken
428
+ val mode = input.replacementMode
429
+ if (oldToken != null && mode != null) {
430
+ flowParams.setSubscriptionUpdateParams(
431
+ BillingFlowParams.SubscriptionUpdateParams.newBuilder()
432
+ .setOldPurchaseToken(oldToken)
433
+ .setSubscriptionReplacementMode(mode)
434
+ .build()
435
+ )
436
+ }
437
+
438
+ val activity = appContext.currentActivity
439
+ if (activity == null) {
440
+ failPurchase(flight) { promise.reject("ui_unavailable", "No activity to show the purchase in", null) }
441
+ return@queryDetails
442
+ }
443
+ val built = flowParams.build()
444
+ activity.runOnUiThread {
445
+ val launch = try {
446
+ client.launchBillingFlow(activity, built)
447
+ } catch (_: RuntimeException) {
448
+ null
449
+ }
450
+ val launchCode = launch?.responseCode
451
+ when (launchCode) {
452
+ null -> failPurchase(flight) {
453
+ promise.reject("store_error", "Play Billing could not start the purchase", null)
454
+ }
455
+ BillingResponseCode.OK -> Unit // The result arrives in onPurchasesUpdated.
456
+ else -> failPurchase(flight) { settleError(promise, launchCode ?: BillingResponseCode.ERROR) }
457
+ }
458
+ }
459
+ }
460
+ }
461
+ }
462
+
463
+ /** Clears the in-flight purchase if it's still [flight], then runs [settle] exactly once. */
464
+ private fun failPurchase(flight: InFlightPurchase, settle: () -> Unit) {
465
+ if (takeInFlight(flight)) settle()
466
+ }
467
+
468
+ private fun takeInFlight(flight: InFlightPurchase): Boolean {
469
+ synchronized(lock) {
470
+ if (inFlight !== flight) return false
471
+ inFlight = null
472
+ return true
473
+ }
474
+ }
475
+
476
+ private fun onPurchasesUpdated(result: BillingResult, purchases: List<Purchase>) {
477
+ val code = result.responseCode
478
+ val flight = synchronized(lock) { inFlight }
479
+
480
+ if (flight != null) {
481
+ val mine = purchases.filter { it.products.contains(flight.productId) }
482
+ val others = purchases.filter { !it.products.contains(flight.productId) }
483
+ // An update for some other product (a pending purchase completing, say) doesn't settle the
484
+ // purchase on screen. An error, or an OK with nothing in it, does.
485
+ val settles = code != BillingResponseCode.OK || mine.isNotEmpty() || purchases.isEmpty()
486
+ if (settles && takeInFlight(flight)) {
487
+ if (code == BillingResponseCode.OK) {
488
+ rememberTypes(listOf(flight.productId), flight.type)
489
+ flight.promise.resolve(successResult(mine.map { mapPurchase(it, flight.type) }, mine))
490
+ } else {
491
+ settleError(flight.promise, code)
492
+ }
493
+ if (code == BillingResponseCode.OK && others.isNotEmpty()) emitUpdate(others)
494
+ return
495
+ }
496
+ }
497
+
498
+ if (code == BillingResponseCode.OK && purchases.isNotEmpty()) {
499
+ emitUpdate(purchases)
500
+ }
501
+ }
502
+
503
+ private fun successResult(mapped: List<Map<String, Any?>>, purchases: List<Purchase>): Map<String, Any?> {
504
+ val anyPurchased = purchases.any { it.purchaseState == Purchase.PurchaseState.PURCHASED }
505
+ // Nothing paid yet (cash and other delayed payments): it completes through onPurchasesUpdated.
506
+ // An OK with no purchases at all (a deferred plan change) counts as success.
507
+ val status = if (purchases.isEmpty() || anyPurchased) "success" else "pending"
508
+ return mapOf("status" to status, "purchases" to mapped)
509
+ }
510
+
511
+ private fun settleError(promise: Promise, code: Int) {
512
+ if (code == BillingResponseCode.USER_CANCELED) {
513
+ promise.resolve(mapOf("status" to "userCancelled"))
514
+ } else {
515
+ rejectBilling(promise, code)
516
+ }
517
+ }
518
+
519
+ /**
520
+ * Sends purchases that arrived outside a purchase flow to JS. Each needs its product type:
521
+ * from the cache when known, else from queryPurchasesAsync, which lists purchased and pending
522
+ * purchases of each type. A purchase neither knows is left out; JS's launch retry
523
+ * (queryPurchases) picks it up.
524
+ */
525
+ private fun emitUpdate(purchases: List<Purchase>) {
526
+ val known = mutableListOf<Map<String, Any?>>()
527
+ val unknown = mutableListOf<Purchase>()
528
+ for (purchase in purchases) {
529
+ val type = cachedType(purchase)
530
+ if (type != null) known.add(mapPurchase(purchase, type)) else unknown.add(purchase)
531
+ }
532
+ if (unknown.isEmpty()) {
533
+ sendEvent(EVENT_PURCHASES_UPDATED, mapOf("purchases" to known))
534
+ return
535
+ }
536
+ val client = client()
537
+ if (client == null) {
538
+ if (known.isNotEmpty()) sendEvent(EVENT_PURCHASES_UPDATED, mapOf("purchases" to known))
539
+ return
540
+ }
541
+ connect(client) { setup ->
542
+ if (setup.responseCode != BillingResponseCode.OK) {
543
+ if (known.isNotEmpty()) sendEvent(EVENT_PURCHASES_UPDATED, mapOf("purchases" to known))
544
+ return@connect
545
+ }
546
+ queryOwned(client, TYPE_SUBS) { subsResult, subs ->
547
+ queryOwned(client, TYPE_INAPP) { inappResult, inapp ->
548
+ val subsTokens = if (subsResult.responseCode == BillingResponseCode.OK) subs.map { it.purchaseToken }.toSet() else emptySet()
549
+ val inappTokens = if (inappResult.responseCode == BillingResponseCode.OK) inapp.map { it.purchaseToken }.toSet() else emptySet()
550
+ for (purchase in unknown) {
551
+ when (purchase.purchaseToken) {
552
+ in subsTokens -> known.add(mapPurchase(purchase, TYPE_SUBS))
553
+ in inappTokens -> known.add(mapPurchase(purchase, TYPE_INAPP))
554
+ }
555
+ }
556
+ if (known.isNotEmpty()) sendEvent(EVENT_PURCHASES_UPDATED, mapOf("purchases" to known))
557
+ }
558
+ }
559
+ }
560
+ }
561
+
562
+ // endregion
563
+
564
+ // region Mapping
565
+
566
+ private fun mapProduct(details: ProductDetails): Map<String, Any?>? {
567
+ val type = when (details.productType) {
568
+ ProductType.SUBS -> TYPE_SUBS
569
+ ProductType.INAPP -> TYPE_INAPP
570
+ else -> return null
571
+ }
572
+ val oneTime = details.oneTimePurchaseOfferDetails?.let {
573
+ mapOf(
574
+ "formattedPrice" to it.formattedPrice,
575
+ "priceAmountMicros" to it.priceAmountMicros.toString(),
576
+ "priceCurrencyCode" to it.priceCurrencyCode
577
+ )
578
+ }
579
+ val offers = details.subscriptionOfferDetails.orEmpty().map { offer ->
580
+ mapOf(
581
+ "basePlanId" to offer.basePlanId,
582
+ "offerId" to offer.offerId,
583
+ "offerToken" to offer.offerToken,
584
+ "pricingPhases" to offer.pricingPhases.pricingPhaseList.map { phase ->
585
+ mapOf(
586
+ "formattedPrice" to phase.formattedPrice,
587
+ "priceAmountMicros" to phase.priceAmountMicros.toString(),
588
+ "priceCurrencyCode" to phase.priceCurrencyCode,
589
+ "billingPeriod" to phase.billingPeriod,
590
+ "recurrenceMode" to phase.recurrenceMode,
591
+ "billingCycleCount" to phase.billingCycleCount
592
+ )
593
+ }
594
+ )
595
+ }
596
+ return mapOf(
597
+ "productId" to details.productId,
598
+ "type" to type,
599
+ "name" to details.name,
600
+ "oneTime" to oneTime,
601
+ "subscriptionOffers" to offers
602
+ )
603
+ }
604
+
605
+ private fun mapPurchase(purchase: Purchase, type: String): Map<String, Any?> {
606
+ return mapOf(
607
+ "purchaseToken" to purchase.purchaseToken,
608
+ "productIds" to purchase.products.toList(),
609
+ "productType" to type,
610
+ "orderId" to purchase.orderId,
611
+ "purchaseState" to purchase.purchaseState,
612
+ "quantity" to purchase.quantity,
613
+ "isAcknowledged" to purchase.isAcknowledged,
614
+ "obfuscatedAccountId" to purchase.accountIdentifiers?.obfuscatedAccountId
615
+ )
616
+ }
617
+
618
+ // endregion
619
+
620
+ // region Validation and errors
621
+
622
+ private fun isProductType(type: String) = type == TYPE_SUBS || type == TYPE_INAPP
623
+
624
+ /** The first invalid field's name, or null when the input is valid. */
625
+ private fun invalidPurchaseField(input: PurchaseInput): String? {
626
+ if (!PRODUCT_ID.matches(input.productId)) return "productId"
627
+ if (!isProductType(input.type)) return "type"
628
+ if (!OBFUSCATED_ACCOUNT_ID.matches(input.obfuscatedAccountId)) return "obfuscatedAccountId"
629
+ val offerToken = input.offerToken
630
+ if (offerToken != null && !OPAQUE_TOKEN.matches(offerToken)) return "offerToken"
631
+ if (input.type == TYPE_SUBS && offerToken == null) return "offerToken"
632
+ val oldToken = input.oldPurchaseToken
633
+ val mode = input.replacementMode
634
+ if ((oldToken == null) != (mode == null)) return "oldPurchaseToken"
635
+ if (oldToken != null) {
636
+ if (input.type != TYPE_SUBS) return "oldPurchaseToken"
637
+ if (!OPAQUE_TOKEN.matches(oldToken)) return "oldPurchaseToken"
638
+ }
639
+ if (mode != null && mode !in REPLACEMENT_MODES) return "replacementMode"
640
+ return null
641
+ }
642
+
643
+ private fun rejectInvalid(promise: Promise, field: String) {
644
+ promise.reject("invalid_argument", "Invalid $field", null)
645
+ }
646
+
647
+ /**
648
+ * Rejects with a stable code for Play's response code. The message always ends with
649
+ * `responseCode=<n>` so JS can read Play's exact code.
650
+ */
651
+ private fun rejectBilling(promise: Promise, code: Int) {
652
+ val stable = when (code) {
653
+ BillingResponseCode.USER_CANCELED -> "user_cancelled"
654
+ BillingResponseCode.BILLING_UNAVAILABLE -> "purchases_unavailable"
655
+ BillingResponseCode.SERVICE_UNAVAILABLE,
656
+ BillingResponseCode.SERVICE_DISCONNECTED,
657
+ BillingResponseCode.NETWORK_ERROR -> "store_unavailable"
658
+ BillingResponseCode.ITEM_UNAVAILABLE -> "product_unavailable"
659
+ BillingResponseCode.ITEM_ALREADY_OWNED -> "item_already_owned"
660
+ else -> "store_error"
661
+ }
662
+ promise.reject(stable, "Play Billing error, responseCode=$code", null)
663
+ }
664
+
665
+ private fun billingResult(code: Int): BillingResult =
666
+ BillingResult.newBuilder().setResponseCode(code).build()
667
+
668
+ // endregion
669
+ }
package/app.plugin.js ADDED
@@ -0,0 +1,3 @@
1
+ // Expo resolves `"plugins": ["@tenthbilling/expo"]` to this file at prebuild.
2
+ // eslint-disable-next-line @typescript-eslint/no-require-imports -- CommonJS: Expo require()s config plugins
3
+ module.exports = require('./plugin/withTenth');