@app-swiss-knife/react-native-sdk 0.5.0 → 0.6.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 +165 -2
- package/README.md +75 -19
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +17 -4
- package/android/vendor/GENERATED.md +1 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +4 -0
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +1 -1
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +47 -2
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +185 -33
- package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +8 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +10 -0
- package/app.plugin.js +61 -5
- package/ios/SwissKnifeJSON.swift +24 -2
- package/ios/SwissKnifePurchases.swift +9 -1
- package/ios/vendor/GENERATED.md +1 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
- package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +7 -0
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +2 -3
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementSync.swift +104 -0
- package/ios/vendor/SwissKnifeiOS/Services/IntroEligibility.swift +137 -0
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +37 -5
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +368 -52
- package/ios/vendor/SwissKnifeiOS/Services/TransactionEvents.swift +371 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +73 -8
- package/ios/vendor/SwissKnifeiOS/Types.swift +31 -1
- package/ios-notification-service/SwissKnifeNotificationService.podspec +37 -0
- package/ios-notification-service/vendor/GENERATED.md +11 -0
- package/ios-notification-service/vendor/SwissKnifeNotificationService/SwissKnifeNotificationServiceExtension.swift +177 -0
- package/lib/commonjs/internal/config.js +3 -0
- package/lib/commonjs/internal/config.js.map +1 -1
- package/lib/commonjs/native/spec.js.map +1 -1
- package/lib/commonjs/types.js.map +1 -1
- package/lib/module/internal/config.js +3 -0
- package/lib/module/internal/config.js.map +1 -1
- package/lib/module/native/spec.js.map +1 -1
- package/lib/module/types.js.map +1 -1
- package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/spec.d.ts +2 -0
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
- package/lib/typescript/commonjs/types.d.ts +13 -0
- package/lib/typescript/commonjs/types.d.ts.map +1 -1
- package/lib/typescript/module/internal/config.d.ts.map +1 -1
- package/lib/typescript/module/native/spec.d.ts +2 -0
- package/lib/typescript/module/native/spec.d.ts.map +1 -1
- package/lib/typescript/module/types.d.ts +13 -0
- package/lib/typescript/module/types.d.ts.map +1 -1
- package/package.json +3 -2
- package/src/internal/config.ts +3 -0
- package/src/native/spec.ts +4 -0
- package/src/types.ts +13 -0
|
@@ -9,9 +9,10 @@
|
|
|
9
9
|
// A purchase or restore that finds the client not ready resets that budget,
|
|
10
10
|
// reconnects, and runs once the client is connected.
|
|
11
11
|
// - Every OK setup (the first one comes from configure) reconciles: it
|
|
12
|
-
// queries SUBS and INAPP purchases and validates + acknowledges
|
|
13
|
-
// PURCHASED one that is still unacknowledged,
|
|
14
|
-
//
|
|
12
|
+
// queries SUBS and INAPP purchases and validates + acknowledges (or
|
|
13
|
+
// consumes, see below) each PURCHASED one that is still unacknowledged,
|
|
14
|
+
// and each consumable an earlier SDK left unconsumed, under the user id
|
|
15
|
+
// stamped on it at launch when there is one. Google auto-refunds an
|
|
15
16
|
// unacknowledged purchase after three days, and nothing server-side
|
|
16
17
|
// acknowledges on our behalf, so an ack lost to a network error or a
|
|
17
18
|
// process kill must be picked up here.
|
|
@@ -38,14 +39,24 @@
|
|
|
38
39
|
// - Offerings/products fetching - that's OfferingsRepository, which
|
|
39
40
|
// SwissKnife.getOfferings() reads. This gateway only queries
|
|
40
41
|
// ProductDetails on-demand for purchase.
|
|
41
|
-
// - Acknowledge
|
|
42
|
-
//
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
//
|
|
48
|
-
//
|
|
42
|
+
// - Acknowledge or consume: a purchase is consumed (consumeAsync, which also
|
|
43
|
+
// acknowledges it) only when the backend's validate answer for each of its
|
|
44
|
+
// products says `product_type: "consumable"`. That answer comes after the
|
|
45
|
+
// backend recorded the purchase in its ledger, so a crash or a failed
|
|
46
|
+
// consume never loses the credit, and the ledger is keyed on the purchase
|
|
47
|
+
// token, so validating it again never grants it twice. Anything else (a
|
|
48
|
+
// non-consumable, a subscription, an answer that names no type, a failed
|
|
49
|
+
// validate) keeps the acknowledge-only path: consuming a non-consumable
|
|
50
|
+
// would take a lifetime unlock away from the user.
|
|
51
|
+
// A consumable an earlier SDK only acknowledged is still owned on Play, so
|
|
52
|
+
// it cannot be bought again. The reconcile consumes it once the server's
|
|
53
|
+
// catalogue ([onServerProductTypes]) or an earlier validate answer says the
|
|
54
|
+
// product is a consumable, after validating it again; a restore consumes it
|
|
55
|
+
// too. Acknowledged purchases of any other product are never re-validated
|
|
56
|
+
// by the reconcile.
|
|
57
|
+
// acknowledge() and consume() check the BillingResult and retry a non-OK
|
|
58
|
+
// answer a bounded number of times; what is still unsettled after that is
|
|
59
|
+
// left to the next reconcile, and never fails the purchase call.
|
|
49
60
|
|
|
50
61
|
package com.appswissknife.purchases
|
|
51
62
|
|
|
@@ -60,6 +71,7 @@ import com.android.billingclient.api.BillingClient
|
|
|
60
71
|
import com.android.billingclient.api.BillingClientStateListener
|
|
61
72
|
import com.android.billingclient.api.BillingFlowParams
|
|
62
73
|
import com.android.billingclient.api.BillingResult
|
|
74
|
+
import com.android.billingclient.api.ConsumeParams
|
|
63
75
|
import com.android.billingclient.api.PendingPurchasesParams
|
|
64
76
|
import com.android.billingclient.api.ProductDetails
|
|
65
77
|
import com.android.billingclient.api.Purchase
|
|
@@ -151,6 +163,29 @@ class BillingClientGateway(
|
|
|
151
163
|
*/
|
|
152
164
|
private val ackClaimed: MutableSet<String> = Collections.synchronizedSet(mutableSetOf())
|
|
153
165
|
|
|
166
|
+
/** Purchase tokens whose consume is in flight or succeeded in this process (see [ackClaimed]). */
|
|
167
|
+
private val consumeClaimed: MutableSet<String> = Collections.synchronizedSet(mutableSetOf())
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The backend's product type (`auto_renewable`, `non_renewing`, `consumable`,
|
|
171
|
+
* `non_consumable`) of each product id it has described in this process: from
|
|
172
|
+
* the offerings it served ([onServerProductTypes]) and from validate answers.
|
|
173
|
+
* Only picks the acknowledged purchases a reconcile validates again; whether
|
|
174
|
+
* a purchase is consumed is decided by the validate answer itself.
|
|
175
|
+
*/
|
|
176
|
+
private val serverProductTypes = java.util.concurrent.ConcurrentHashMap<String, String>()
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Product ids a validate answer has typed in this process. The catalogue
|
|
180
|
+
* never overrides those: the validate answer is what decides a consume, and
|
|
181
|
+
* a catalogue row that disagrees with it would otherwise re-validate the
|
|
182
|
+
* purchase on every offerings read.
|
|
183
|
+
*/
|
|
184
|
+
private val typedByValidate: MutableSet<String> = java.util.concurrent.ConcurrentHashMap.newKeySet()
|
|
185
|
+
|
|
186
|
+
/** A reconcile was asked for while one was running; run another when it ends. */
|
|
187
|
+
private val reconcileAgain = AtomicBoolean(false)
|
|
188
|
+
|
|
154
189
|
private val executor: ExecutorService =
|
|
155
190
|
Executors.newSingleThreadExecutor { r -> Thread(r, "swissknife-billing").apply { isDaemon = true } }
|
|
156
191
|
|
|
@@ -375,6 +410,7 @@ class BillingClientGateway(
|
|
|
375
410
|
val launchResult = client.launchBillingFlow(activity, flowParams)
|
|
376
411
|
if (launchResult.responseCode != BillingClient.BillingResponseCode.OK) {
|
|
377
412
|
pendingPurchase = null
|
|
413
|
+
if (launchResult.responseCode == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) reconcileSoon()
|
|
378
414
|
onError(toPurchasesError(launchResult), launchResult.isUserCancelled())
|
|
379
415
|
}
|
|
380
416
|
}
|
|
@@ -430,6 +466,23 @@ class BillingClientGateway(
|
|
|
430
466
|
PRODUCT_TYPES
|
|
431
467
|
}
|
|
432
468
|
|
|
469
|
+
/**
|
|
470
|
+
* The backend's catalogue named these product types. A consumable learned
|
|
471
|
+
* here may be one an earlier SDK acknowledged and never consumed, which Play
|
|
472
|
+
* then refuses to sell again (ITEM_ALREADY_OWNED), so learning one runs a
|
|
473
|
+
* reconcile, which validates such a purchase again and consumes it if the
|
|
474
|
+
* backend confirms it is a consumable.
|
|
475
|
+
*/
|
|
476
|
+
override fun onServerProductTypes(types: Map<String, String>) {
|
|
477
|
+
var learnedConsumable = false
|
|
478
|
+
for ((productId, type) in types) {
|
|
479
|
+
if (productId.isEmpty() || type.isEmpty() || productId in typedByValidate) continue
|
|
480
|
+
val previous = serverProductTypes.put(productId, type)
|
|
481
|
+
if (type == CONSUMABLE && previous != CONSUMABLE) learnedConsumable = true
|
|
482
|
+
}
|
|
483
|
+
if (learnedConsumable) reconcileSoon()
|
|
484
|
+
}
|
|
485
|
+
|
|
433
486
|
override fun restorePurchases(
|
|
434
487
|
onSuccess: (CustomerInfo) -> Unit,
|
|
435
488
|
onError: (PurchasesError) -> Unit,
|
|
@@ -459,12 +512,9 @@ class BillingClientGateway(
|
|
|
459
512
|
for (p in purchases) {
|
|
460
513
|
// A pending payment is not a purchase yet: never validate or ack it.
|
|
461
514
|
if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
}
|
|
466
|
-
if (!p.isAcknowledged) acknowledge(p)
|
|
467
|
-
}.onFailure { errors.add(it) }
|
|
515
|
+
// Acknowledged consumables included: one the backend confirms as a
|
|
516
|
+
// consumable is consumed, so the user can buy it again.
|
|
517
|
+
runCatching { validateAndSettle(p) }.onFailure { errors.add(it) }
|
|
468
518
|
}
|
|
469
519
|
val repo = entitlementsRepo
|
|
470
520
|
val info = try {
|
|
@@ -571,6 +621,10 @@ class BillingClientGateway(
|
|
|
571
621
|
pending?.onError?.invoke(PurchasesError.PurchaseCancelled(), true); return
|
|
572
622
|
}
|
|
573
623
|
if (code != BillingClient.BillingResponseCode.OK) {
|
|
624
|
+
// Play still holds a purchase of the product. When it is a consumable an
|
|
625
|
+
// earlier SDK only acknowledged, the reconcile consumes it, so the next
|
|
626
|
+
// attempt goes through; the call still fails as before.
|
|
627
|
+
if (code == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) reconcileSoon()
|
|
574
628
|
pending?.onError?.invoke(toPurchasesError(result), false); return
|
|
575
629
|
}
|
|
576
630
|
if (purchases.isNullOrEmpty()) {
|
|
@@ -609,11 +663,11 @@ class BillingClientGateway(
|
|
|
609
663
|
// connect finds it otherwise.
|
|
610
664
|
if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
|
|
611
665
|
try {
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
666
|
+
// Consumed or acknowledged after the backend recorded it. A consume
|
|
667
|
+
// or acknowledge that fails is retried and left to the reconcile; it
|
|
668
|
+
// never fails this call.
|
|
669
|
+
validateAndSettle(p)
|
|
615
670
|
validatedAny = true
|
|
616
|
-
if (!p.isAcknowledged) acknowledge(p)
|
|
617
671
|
} catch (e: Exception) {
|
|
618
672
|
if (p === matched) {
|
|
619
673
|
matchedFailure = e
|
|
@@ -765,11 +819,25 @@ class BillingClientGateway(
|
|
|
765
819
|
* the app was not running all land here. There is no server-side
|
|
766
820
|
* acknowledge (that would be a store write from the backend).
|
|
767
821
|
*
|
|
822
|
+
* It also consumes the consumables an earlier SDK acknowledged and never
|
|
823
|
+
* consumed: an acknowledged purchase whose every product the backend has
|
|
824
|
+
* described as a consumable ([serverProductTypes]) is validated again (the
|
|
825
|
+
* backend's ledger is keyed on the token, so this grants nothing twice) and
|
|
826
|
+
* consumed when the answer confirms it. No other acknowledged purchase is
|
|
827
|
+
* validated again.
|
|
828
|
+
*
|
|
768
829
|
* When it validated anything, it then re-reads the entitlements, so the app
|
|
769
830
|
* sees what those purchases unlocked without a restore.
|
|
831
|
+
*
|
|
832
|
+
* [rerunIfBusy]: a reconcile asked for while one runs is dropped (the running
|
|
833
|
+
* one covers a new setup), unless the caller learned something the running
|
|
834
|
+
* one may have missed; then another runs when it ends.
|
|
770
835
|
*/
|
|
771
|
-
private fun reconcilePurchases(client: BillingClient) {
|
|
772
|
-
if (!reconcileInFlight.compareAndSet(false, true))
|
|
836
|
+
private fun reconcilePurchases(client: BillingClient, rerunIfBusy: Boolean = false) {
|
|
837
|
+
if (!reconcileInFlight.compareAndSet(false, true)) {
|
|
838
|
+
if (rerunIfBusy) reconcileAgain.set(true)
|
|
839
|
+
return
|
|
840
|
+
}
|
|
773
841
|
try {
|
|
774
842
|
queryOwnedPurchases(client, PRODUCT_TYPES, mutableListOf()) { owned, _ ->
|
|
775
843
|
executor.execute {
|
|
@@ -777,23 +845,22 @@ class BillingClientGateway(
|
|
|
777
845
|
try {
|
|
778
846
|
for (p in owned) {
|
|
779
847
|
if (p.purchaseState != Purchase.PurchaseState.PURCHASED) continue
|
|
780
|
-
|
|
848
|
+
val token = p.purchaseToken
|
|
849
|
+
if (token in ackClaimed || token in consumeClaimed) continue
|
|
850
|
+
if (p.isAcknowledged && !isKnownConsumable(p)) continue
|
|
781
851
|
try {
|
|
782
|
-
|
|
783
|
-
for (productId in p.products) {
|
|
784
|
-
validatePurchaseWithBackend(p.packageName, productId, p.purchaseToken, subject)
|
|
785
|
-
}
|
|
852
|
+
validateAndSettle(p, reconcileSubject(p))
|
|
786
853
|
validatedAny = true
|
|
787
|
-
acknowledge(p)
|
|
788
854
|
} catch (e: Exception) {
|
|
789
|
-
// Not
|
|
790
|
-
Log.w(TAG, "reconcile: validate failed for
|
|
855
|
+
// Not settled, so the next connect tries again.
|
|
856
|
+
Log.w(TAG, "reconcile: validate failed for a purchase left to settle", e)
|
|
791
857
|
}
|
|
792
858
|
}
|
|
793
859
|
} finally {
|
|
794
860
|
reconcileInFlight.set(false)
|
|
795
861
|
}
|
|
796
862
|
if (validatedAny) refreshEntitlements()
|
|
863
|
+
if (reconcileAgain.getAndSet(false)) reconcileSoon()
|
|
797
864
|
}
|
|
798
865
|
}
|
|
799
866
|
} catch (e: RuntimeException) {
|
|
@@ -802,6 +869,36 @@ class BillingClientGateway(
|
|
|
802
869
|
}
|
|
803
870
|
}
|
|
804
871
|
|
|
872
|
+
/** Reconcile now if Play is connected; otherwise the next OK setup reconciles anyway. */
|
|
873
|
+
private fun reconcileSoon() {
|
|
874
|
+
val client = billingClient?.takeIf { it.isReady } ?: return
|
|
875
|
+
reconcilePurchases(client, rerunIfBusy = true)
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
/** Every product of [p] is one the backend has described as a consumable. */
|
|
879
|
+
private fun isKnownConsumable(p: Purchase): Boolean =
|
|
880
|
+
p.products.isNotEmpty() && p.products.all { serverProductTypes[it] == CONSUMABLE }
|
|
881
|
+
|
|
882
|
+
/**
|
|
883
|
+
* Validate [p] with the backend under [subject], then settle it with Play:
|
|
884
|
+
* consume it when the backend answered that every one of its products is a
|
|
885
|
+
* consumable (it has recorded the purchase by then), otherwise acknowledge it
|
|
886
|
+
* if Play still holds it unacknowledged. Throws what a validate threw, and
|
|
887
|
+
* settles nothing then.
|
|
888
|
+
*/
|
|
889
|
+
@Throws(IOException::class)
|
|
890
|
+
private fun validateAndSettle(p: Purchase, subject: String = getAppUserID()) {
|
|
891
|
+
// Every product is validated before anything is settled.
|
|
892
|
+
val types = p.products.map { productId ->
|
|
893
|
+
validatePurchaseWithBackend(p.packageName, productId, p.purchaseToken, subject)
|
|
894
|
+
}
|
|
895
|
+
if (types.isNotEmpty() && types.all { it == CONSUMABLE }) {
|
|
896
|
+
consume(p)
|
|
897
|
+
} else if (!p.isAcknowledged) {
|
|
898
|
+
acknowledge(p)
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
805
902
|
/**
|
|
806
903
|
* The subject a reconciled purchase is validated under.
|
|
807
904
|
*
|
|
@@ -881,6 +978,10 @@ class BillingClientGateway(
|
|
|
881
978
|
* validates against Google's Real-Time Developer Notifications channel
|
|
882
979
|
* and the Play Developer API. Returns when the backend ack'd; throws on
|
|
883
980
|
* non-2xx.
|
|
981
|
+
*
|
|
982
|
+
* Returns the backend's `product_type` for [productId] from its answer, or
|
|
983
|
+
* null when the answer names none (or names another product). The backend
|
|
984
|
+
* answers only after it has recorded the purchase.
|
|
884
985
|
*/
|
|
885
986
|
@Throws(IOException::class)
|
|
886
987
|
private fun validatePurchaseWithBackend(
|
|
@@ -888,7 +989,7 @@ class BillingClientGateway(
|
|
|
888
989
|
productId: String,
|
|
889
990
|
purchaseToken: String,
|
|
890
991
|
userId: String = getAppUserID(),
|
|
891
|
-
) {
|
|
992
|
+
): String? {
|
|
892
993
|
val body = JSONObject().apply {
|
|
893
994
|
put("user_id", userId)
|
|
894
995
|
put("platform", "android")
|
|
@@ -899,7 +1000,7 @@ class BillingClientGateway(
|
|
|
899
1000
|
// sent `Authorization: Bearer ...` which the route ignored — every
|
|
900
1001
|
// validate POST was returning 401 in production. Aligning with the
|
|
901
1002
|
// backend contract here.
|
|
902
|
-
httpClient.post(
|
|
1003
|
+
val answer = httpClient.post(
|
|
903
1004
|
url = "$serverUrl/api/sdk/subscriptions/validate",
|
|
904
1005
|
body = body,
|
|
905
1006
|
headers = mapOf(
|
|
@@ -907,6 +1008,21 @@ class BillingClientGateway(
|
|
|
907
1008
|
"Content-Type" to "application/json",
|
|
908
1009
|
),
|
|
909
1010
|
)
|
|
1011
|
+
val type = productTypeIn(answer, productId) ?: return null
|
|
1012
|
+
typedByValidate.add(productId)
|
|
1013
|
+
serverProductTypes[productId] = type
|
|
1014
|
+
return type
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/** The `product_type` a validate answer gives [productId]; null when it names none or another product. */
|
|
1018
|
+
private fun productTypeIn(answer: String?, productId: String): String? {
|
|
1019
|
+
val json = try {
|
|
1020
|
+
JSONObject(answer ?: return null)
|
|
1021
|
+
} catch (_: org.json.JSONException) {
|
|
1022
|
+
return null
|
|
1023
|
+
}
|
|
1024
|
+
if (json.isNull("product_type") || json.optString("product_id") != productId) return null
|
|
1025
|
+
return json.optString("product_type").takeIf { it.isNotEmpty() }
|
|
910
1026
|
}
|
|
911
1027
|
|
|
912
1028
|
/**
|
|
@@ -981,6 +1097,39 @@ class BillingClientGateway(
|
|
|
981
1097
|
}
|
|
982
1098
|
}
|
|
983
1099
|
|
|
1100
|
+
/**
|
|
1101
|
+
* Consume [purchase] (which also acknowledges it), so Play sells the product
|
|
1102
|
+
* again. Called only after the backend recorded the purchase and answered
|
|
1103
|
+
* that it is a consumable. Same bounded retry as [acknowledge]; a consume
|
|
1104
|
+
* that still fails is left to the next reconcile, which finds the purchase
|
|
1105
|
+
* owned and validates it again (the backend grants it once) before consuming.
|
|
1106
|
+
*/
|
|
1107
|
+
private fun consume(purchase: Purchase) {
|
|
1108
|
+
// Consumed, or a consume is in flight, in this process.
|
|
1109
|
+
if (!consumeClaimed.add(purchase.purchaseToken)) return
|
|
1110
|
+
sendConsume(purchase, attempt = 0)
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
private fun sendConsume(purchase: Purchase, attempt: Int) {
|
|
1114
|
+
val token = purchase.purchaseToken
|
|
1115
|
+
val client = billingClient ?: run { consumeClaimed.remove(token); return }
|
|
1116
|
+
val params = ConsumeParams.newBuilder()
|
|
1117
|
+
.setPurchaseToken(token)
|
|
1118
|
+
.build()
|
|
1119
|
+
client.consumeAsync(params) { result, _ ->
|
|
1120
|
+
val code = result.responseCode
|
|
1121
|
+
if (code == BillingClient.BillingResponseCode.OK) return@consumeAsync
|
|
1122
|
+
if (attempt + 1 < MAX_ACK_ATTEMPTS && code !in TERMINAL_ACK_CODES) {
|
|
1123
|
+
reconnectScheduler.schedule(ACK_RETRY_BASE_DELAY_MS shl attempt) {
|
|
1124
|
+
sendConsume(purchase, attempt + 1)
|
|
1125
|
+
}
|
|
1126
|
+
} else {
|
|
1127
|
+
consumeClaimed.remove(token)
|
|
1128
|
+
Log.w(TAG, "consumeAsync failed (code=$code, attempts=${attempt + 1}); left for the next reconcile")
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
|
|
984
1133
|
private fun Purchase.toStoreTransaction(): StoreTransaction = object : StoreTransaction {
|
|
985
1134
|
override val productIdentifier: String = products.firstOrNull().orEmpty()
|
|
986
1135
|
override val transactionIdentifier: String = orderId.orEmpty()
|
|
@@ -1010,6 +1159,9 @@ class BillingClientGateway(
|
|
|
1010
1159
|
|
|
1011
1160
|
companion object {
|
|
1012
1161
|
private const val TAG = "SwissKnife.Billing"
|
|
1162
|
+
|
|
1163
|
+
/** The backend's `product_type` for a one-time product that is bought again and again. */
|
|
1164
|
+
private const val CONSUMABLE = "consumable"
|
|
1013
1165
|
private val ANONYMOUS_ID_PREFIXES = listOf("\$SKAnonymousID:", "\$RCAnonymousID:")
|
|
1014
1166
|
|
|
1015
1167
|
private fun newFallbackAnonymousId(): String =
|
|
@@ -18,4 +18,12 @@ package com.appswissknife.purchases
|
|
|
18
18
|
interface ProductKindHint {
|
|
19
19
|
/** True for a one-time product (Play INAPP, consumable or not), false for a subscription. */
|
|
20
20
|
val isOneTime: Boolean
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The server's product type when its catalogue names one (auto_renewable,
|
|
24
|
+
* non_renewing, consumable, non_consumable); null when unknown. The React
|
|
25
|
+
* Native bridge labels a one-time product CONSUMABLE or NON_CONSUMABLE from it.
|
|
26
|
+
*/
|
|
27
|
+
val productKind: String?
|
|
28
|
+
get() = null
|
|
21
29
|
}
|
|
@@ -87,6 +87,16 @@ interface PurchasesGateway {
|
|
|
87
87
|
*/
|
|
88
88
|
fun priceEnrichmentProvider(): PriceEnrichmentProvider? = null
|
|
89
89
|
|
|
90
|
+
/**
|
|
91
|
+
* The backend's product type for this store's products, product id to
|
|
92
|
+
* `auto_renewable`, `non_renewing`, `consumable` or `non_consumable`, as the
|
|
93
|
+
* offerings the SDK just read describe them (only the products whose type the
|
|
94
|
+
* backend named). The Play gateway uses it to find consumables an earlier SDK
|
|
95
|
+
* acknowledged without consuming; it never consumes on this alone, only after
|
|
96
|
+
* the backend's validate answer confirms the type. The default ignores it.
|
|
97
|
+
*/
|
|
98
|
+
fun onServerProductTypes(types: Map<String, String>) {}
|
|
99
|
+
|
|
90
100
|
// --- Identity -------------------------------------------------------------
|
|
91
101
|
|
|
92
102
|
fun logIn(
|
package/app.plugin.js
CHANGED
|
@@ -34,6 +34,11 @@
|
|
|
34
34
|
* app module (the SDK declares it compileOnly so non-push apps stay clean)
|
|
35
35
|
* - `defaultChannel` is written as manifest meta-data
|
|
36
36
|
* (`com.appswissknife.notifications.default_channel_{id,name}`).
|
|
37
|
+
* - store: the `swissKnifeStore` Gradle property, plus RuStore's strings and
|
|
38
|
+
* manifest entries for a RuStore build. `SWISS_KNIFE_ANDROID_STORE`
|
|
39
|
+
* (`play` | `rustore`, read at prebuild, e.g. from an EAS build profile's
|
|
40
|
+
* `env`) picks it; unset, `android.rustore` being configured means RuStore
|
|
41
|
+
* (see resolveAndroidStore).
|
|
37
42
|
*
|
|
38
43
|
* The pure mutation helpers below are exported for unit tests; `expo/config-plugins`
|
|
39
44
|
* is loaded lazily so they can be used without Expo installed.
|
|
@@ -185,20 +190,69 @@ function loadConfigPlugins() {
|
|
|
185
190
|
}
|
|
186
191
|
}
|
|
187
192
|
|
|
193
|
+
const ANDROID_STORE_ENV = "SWISS_KNIFE_ANDROID_STORE";
|
|
194
|
+
|
|
195
|
+
/** What is missing or invalid in an `android.rustore` option, by field. */
|
|
196
|
+
function ruStoreConfigProblems(rustore) {
|
|
197
|
+
const r = rustore && typeof rustore === "object" ? rustore : {};
|
|
198
|
+
const problems = [];
|
|
199
|
+
if (!/^\d+$/.test(String(r.consoleAppId ?? ""))) {
|
|
200
|
+
problems.push(r.consoleAppId === undefined ? "consoleAppId (missing)" : "consoleAppId (must be digits)");
|
|
201
|
+
}
|
|
202
|
+
if (!/^[a-z][a-z0-9+.-]*$/.test(r.scheme ?? "")) {
|
|
203
|
+
problems.push(r.scheme === undefined ? "scheme (missing)" : "scheme (not a valid deeplink scheme)");
|
|
204
|
+
}
|
|
205
|
+
return problems;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The Android store this prebuild targets: `{ store: "play" | "rustore",
|
|
210
|
+
* rustore }`, where `rustore` is the `android.rustore` option for a RuStore
|
|
211
|
+
* build and null for a Play build.
|
|
212
|
+
*
|
|
213
|
+
* `SWISS_KNIFE_ANDROID_STORE` (from `env`, normally `process.env`) chooses it,
|
|
214
|
+
* so one app config can produce both builds (set it per EAS build profile):
|
|
215
|
+
* - unset or empty: as before the variable existed, RuStore when
|
|
216
|
+
* `android.rustore` is configured, else Play;
|
|
217
|
+
* - `play`: Play, ignoring `android.rustore`;
|
|
218
|
+
* - `rustore`: RuStore, which needs `android.rustore`;
|
|
219
|
+
* - anything else: an error.
|
|
220
|
+
* A RuStore build with an incomplete `android.rustore` is an error naming the
|
|
221
|
+
* fields.
|
|
222
|
+
*/
|
|
223
|
+
function resolveAndroidStore(android, env) {
|
|
224
|
+
const rustore = android ? android.rustore : undefined;
|
|
225
|
+
const raw = env && typeof env[ANDROID_STORE_ENV] === "string" ? env[ANDROID_STORE_ENV].trim() : "";
|
|
226
|
+
if (raw !== "" && raw !== "play" && raw !== "rustore") {
|
|
227
|
+
throw new Error(
|
|
228
|
+
`[swiss-knife] ${ANDROID_STORE_ENV} must be "play" or "rustore", got ${JSON.stringify(raw)}. ` +
|
|
229
|
+
"Leave it unset to build for RuStore when android.rustore is configured and for Google Play otherwise."
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
if (raw === "play" || (raw === "" && !rustore)) return { store: "play", rustore: null };
|
|
233
|
+
const problems = ruStoreConfigProblems(rustore);
|
|
234
|
+
if (problems.length > 0) {
|
|
235
|
+
const prefix =
|
|
236
|
+
raw === "rustore"
|
|
237
|
+
? `${ANDROID_STORE_ENV}=rustore needs the plugin's android.rustore option ` +
|
|
238
|
+
'({ "consoleAppId": "<digits>", "scheme": "<deeplink scheme>" })'
|
|
239
|
+
: "android.rustore requires consoleAppId (digits) and a valid deeplink scheme";
|
|
240
|
+
throw new Error(`${prefix}; missing or invalid: ${problems.map((p) => "android.rustore." + p).join(", ")}`);
|
|
241
|
+
}
|
|
242
|
+
return { store: "rustore", rustore };
|
|
243
|
+
}
|
|
244
|
+
|
|
188
245
|
function withSwissKnifePush(config, props) {
|
|
189
246
|
const { withEntitlementsPlist, withInfoPlist, withAndroidManifest, withAppBuildGradle, withGradleProperties, withStringsXml } =
|
|
190
247
|
loadConfigPlugins();
|
|
191
248
|
const opts = normalizeProps(props);
|
|
192
|
-
const rustore = props
|
|
249
|
+
const { store, rustore } = resolveAndroidStore(props && props.android, typeof process === "undefined" ? {} : process.env);
|
|
193
250
|
config = withGradleProperties(config, (c) => {
|
|
194
251
|
c.modResults = c.modResults.filter((entry) => entry.key !== "swissKnifeStore");
|
|
195
|
-
c.modResults.push({ type: "property", key: "swissKnifeStore", value:
|
|
252
|
+
c.modResults.push({ type: "property", key: "swissKnifeStore", value: store });
|
|
196
253
|
return c;
|
|
197
254
|
});
|
|
198
255
|
if (rustore) {
|
|
199
|
-
if (!/^\d+$/.test(String(rustore.consoleAppId ?? "")) || !/^[a-z][a-z0-9+.-]*$/.test(rustore.scheme ?? "")) {
|
|
200
|
-
throw new Error("android.rustore requires consoleAppId (digits) and a valid deeplink scheme");
|
|
201
|
-
}
|
|
202
256
|
config = withStringsXml(config, (c) => {
|
|
203
257
|
c.modResults.resources.string = (c.modResults.resources.string || []).filter((entry) => entry.$?.name !== "swissknife_rustore_app_id");
|
|
204
258
|
c.modResults.resources.string.push({ $: { name: "swissknife_rustore_app_id", translatable: "false" }, _: String(rustore.consoleAppId) });
|
|
@@ -264,6 +318,8 @@ module.exports.applyAndroidManifest = applyAndroidManifest;
|
|
|
264
318
|
module.exports.detectMessagingConflict = detectMessagingConflict;
|
|
265
319
|
module.exports.applyAppBuildGradle = applyAppBuildGradle;
|
|
266
320
|
module.exports.applyGoogleServicesFile = applyGoogleServicesFile;
|
|
321
|
+
module.exports.resolveAndroidStore = resolveAndroidStore;
|
|
322
|
+
module.exports.ANDROID_STORE_ENV = ANDROID_STORE_ENV;
|
|
267
323
|
module.exports.MESSAGING_SERVICE = MESSAGING_SERVICE;
|
|
268
324
|
|
|
269
325
|
function applyRuStoreManifest(manifest, scheme) {
|
package/ios/SwissKnifeJSON.swift
CHANGED
|
@@ -102,8 +102,10 @@ enum SwissKnifeJSON {
|
|
|
102
102
|
"priceString": product.displayPrice,
|
|
103
103
|
"price": NSDecimalNumber(decimal: product.price).doubleValue,
|
|
104
104
|
"currencyCode": product.currencyCode,
|
|
105
|
-
"productCategory":
|
|
106
|
-
"productType":
|
|
105
|
+
"productCategory": productCategoryString(product.productType),
|
|
106
|
+
"productType": productTypeString(product.productType),
|
|
107
|
+
// Both nil unless the product is an auto-renewable subscription (the
|
|
108
|
+
// SDK's OfferingsService sets them only then).
|
|
107
109
|
"subscriptionPeriod": product.subscriptionPeriod.map { periodString($0) } ?? NSNull(),
|
|
108
110
|
"defaultOption": NSNull(),
|
|
109
111
|
"subscriptionOptions": NSNull(),
|
|
@@ -217,6 +219,26 @@ enum SwissKnifeJSON {
|
|
|
217
219
|
}
|
|
218
220
|
}
|
|
219
221
|
|
|
222
|
+
/// `PurchasesStoreProduct.productType` in src/types.ts. No `default:`, so a
|
|
223
|
+
/// new `StoreProductType` case fails the compile instead of mislabelling.
|
|
224
|
+
static func productTypeString(_ t: StoreProductType) -> String {
|
|
225
|
+
switch t {
|
|
226
|
+
case .autoRenewableSubscription: return "AUTO_RENEWABLE_SUBSCRIPTION"
|
|
227
|
+
case .nonRenewableSubscription: return "NON_RENEWABLE_SUBSCRIPTION"
|
|
228
|
+
case .consumable: return "CONSUMABLE"
|
|
229
|
+
case .nonConsumable: return "NON_CONSUMABLE"
|
|
230
|
+
case .unknown: return "UNKNOWN"
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/// `PurchasesStoreProduct.productCategory` in src/types.ts: SUBSCRIPTION only
|
|
235
|
+
/// for an auto-renewable subscription (RevenueCat's convention), so a
|
|
236
|
+
/// non-renewing subscription, a consumable or a lifetime unlock is
|
|
237
|
+
/// NON_SUBSCRIPTION — as the Android bridge reports a one-time product.
|
|
238
|
+
static func productCategoryString(_ t: StoreProductType) -> String {
|
|
239
|
+
t.isSubscription ? "SUBSCRIPTION" : "NON_SUBSCRIPTION"
|
|
240
|
+
}
|
|
241
|
+
|
|
220
242
|
private static func packageTypeString(_ p: PackageType) -> String {
|
|
221
243
|
switch p {
|
|
222
244
|
case .unknown: return "UNKNOWN"
|
|
@@ -121,6 +121,13 @@ class SwissKnifePurchases: RCTEventEmitter {
|
|
|
121
121
|
sendInstallOnFirstLaunch: (options["sendInstallOnFirstLaunch"] as? Bool) ?? true
|
|
122
122
|
)
|
|
123
123
|
|
|
124
|
+
// Silent entitlement sync after configure / logIn, and the user's UUID as
|
|
125
|
+
// the default appAccountToken. Both default on, as in a native app.
|
|
126
|
+
let purchases = SwissKnife.PurchasesConfiguration(
|
|
127
|
+
syncEntitlementsAutomatically: (options["syncEntitlementsAutomatically"] as? Bool) ?? true,
|
|
128
|
+
automaticAppAccountToken: (options["automaticAppAccountToken"] as? Bool) ?? true
|
|
129
|
+
)
|
|
130
|
+
|
|
124
131
|
// Phase 5: SwissKnife owns the entire native subscription stack — StoreKit 2,
|
|
125
132
|
// proxyURL, diagnostics, identity. RN + native-app paths configure identically.
|
|
126
133
|
SwissKnife.configure(
|
|
@@ -129,7 +136,8 @@ class SwissKnifePurchases: RCTEventEmitter {
|
|
|
129
136
|
proxyURL: proxyURL,
|
|
130
137
|
storeKitVersion: storeKitVersion,
|
|
131
138
|
logLevel: logLevel,
|
|
132
|
-
attribution: attribution
|
|
139
|
+
attribution: attribution,
|
|
140
|
+
purchases: purchases
|
|
133
141
|
)
|
|
134
142
|
|
|
135
143
|
// Bridge the native SDK's CustomerInfo stream to the JS event channel.
|
package/ios/vendor/GENERATED.md
CHANGED
|
@@ -4,6 +4,7 @@ Copied verbatim by packages/react-native-sdk/scripts/vendor-native.mjs from the
|
|
|
4
4
|
standalone native SDK sources in the monorepo. Edit those instead:
|
|
5
5
|
|
|
6
6
|
packages/swiss-knife-ios/Sources/SwissKnifeiOS/**
|
|
7
|
+
packages/swiss-knife-ios/Sources/SwissKnifeNotificationService/**
|
|
7
8
|
packages/swiss-knife-android/src/main/{java,res}/**
|
|
8
9
|
|
|
9
10
|
This directory is gitignored and regenerated on every `build` / `prepack`.
|
|
@@ -99,7 +99,7 @@ internal enum DeviceContextProvider {
|
|
|
99
99
|
/// Round A baseline. The build pipeline (`swiss-build`) will eventually
|
|
100
100
|
/// inject this via `-D` flag, but for now keep it in source so we don't
|
|
101
101
|
/// have to thread build settings through the SPM Package.swift.
|
|
102
|
-
static let sdkVersionConstant: String = "0.
|
|
102
|
+
static let sdkVersionConstant: String = "0.6.0"
|
|
103
103
|
|
|
104
104
|
private static let cacheLock = DispatchQueue(label: "com.swissknife.context.device")
|
|
105
105
|
private static var cached: DeviceContext?
|
|
@@ -382,6 +382,13 @@ public extension SwissKnife {
|
|
|
382
382
|
}
|
|
383
383
|
}
|
|
384
384
|
|
|
385
|
+
/// Whether a `logIn` is still resolving. The automatic entitlement
|
|
386
|
+
/// sync scheduled at configure time stands down for it: the login
|
|
387
|
+
/// syncs for its own user when it lands.
|
|
388
|
+
internal static var _hasLogInInFlight: Bool {
|
|
389
|
+
queue.sync { !inFlightLogIns.isEmpty }
|
|
390
|
+
}
|
|
391
|
+
|
|
385
392
|
/// Test seam — drop all in-memory state and observers, restore
|
|
386
393
|
/// the production network. Production code MUST NOT call this.
|
|
387
394
|
internal static func _resetForTesting() {
|
|
@@ -16,7 +16,6 @@
|
|
|
16
16
|
// `type` is one of:
|
|
17
17
|
// "error" | "error_batch" | "analytics" | "transaction" | "session"
|
|
18
18
|
// | "feedback" | "paywall" | "funnel"
|
|
19
|
-
// (`store_notification` is server-side only — webhooks land there.)
|
|
20
19
|
//
|
|
21
20
|
// Architecture:
|
|
22
21
|
// - `enqueue(_ item: IngestItem)` writes to `OfflineQueueStore<IngestItem>`
|
|
@@ -103,8 +102,8 @@ import os.log
|
|
|
103
102
|
/// `errorBatch` case wraps an array of `error` payloads — used by the
|
|
104
103
|
/// crash reporter when it has multiple buffered crashes to send.
|
|
105
104
|
///
|
|
106
|
-
///
|
|
107
|
-
///
|
|
105
|
+
/// There is no store notification type: Apple and Google notifications go
|
|
106
|
+
/// to the web app's verified webhook routes, never through `/ingest`.
|
|
108
107
|
internal enum IngestItemType: String, Codable, Sendable {
|
|
109
108
|
case error
|
|
110
109
|
case errorBatch = "error_batch"
|