@capgo/native-purchases 8.8.1 → 8.9.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.
@@ -0,0 +1,108 @@
1
+ import Capacitor
2
+ import StoreKit
3
+
4
+ extension NativePurchasesPlugin {
5
+ func readAutoFinishTransactionsFromConfig() {
6
+ autoFinishTransactions = getConfig().getBoolean("autoFinishTransactions", true)
7
+ }
8
+
9
+ @objc func configure(_ call: CAPPluginCall) {
10
+ if let value = call.getBool("autoFinishTransactions") {
11
+ applyAutoFinishTransactionsSetting(value)
12
+ print("autoFinishTransactions set to \(value)")
13
+ }
14
+ call.resolve()
15
+ }
16
+
17
+ @objc func getUnfinishedTransactions(_ call: CAPPluginCall) {
18
+ Task {
19
+ do {
20
+ let transactions = try await TransactionHelpers.collectUnfinishedTransactions()
21
+ await MainActor.run {
22
+ call.resolve(["transactions": transactions])
23
+ }
24
+ } catch {
25
+ await MainActor.run {
26
+ call.reject(error.localizedDescription)
27
+ }
28
+ }
29
+ }
30
+ }
31
+
32
+ @objc func finishTransaction(_ call: CAPPluginCall) {
33
+ guard let transactionIdString = call.getString("transactionId"), !transactionIdString.isEmpty else {
34
+ call.reject("transactionId is required")
35
+ return
36
+ }
37
+
38
+ guard let transactionId = UInt64(transactionIdString) else {
39
+ call.reject("Invalid transactionId format")
40
+ return
41
+ }
42
+
43
+ Task {
44
+ do {
45
+ try await finishStoreKitTransaction(
46
+ transactionId: transactionId,
47
+ transactionIdString: transactionIdString
48
+ )
49
+ await MainActor.run { call.resolve() }
50
+ } catch let error as FinishTransactionError {
51
+ await MainActor.run { call.reject(error.message) }
52
+ } catch {
53
+ await MainActor.run { call.reject(error.localizedDescription) }
54
+ }
55
+ }
56
+ }
57
+
58
+ func finishStoreKitTransaction(transactionId: UInt64, transactionIdString: String) async throws {
59
+ for await result in Transaction.unfinished {
60
+ switch result {
61
+ case .verified(let transaction) where transaction.id == transactionId:
62
+ print("Manually finishing transaction: \(transaction.id)")
63
+ await transaction.finish()
64
+ return
65
+ case .unverified(let transaction, let error) where transaction.id == transactionId:
66
+ throw FinishTransactionError.verificationFailed(error.localizedDescription)
67
+ default:
68
+ continue
69
+ }
70
+ }
71
+
72
+ for await verificationResult in Transaction.all {
73
+ if case .verified(let transaction) = verificationResult, transaction.id == transactionId {
74
+ print("Transaction \(transactionId) already finished")
75
+ return
76
+ }
77
+ }
78
+
79
+ let finishedLegacyTransaction = await MainActor.run { () -> Bool in
80
+ for paymentTransaction in SKPaymentQueue.default().transactions {
81
+ if paymentTransaction.transactionIdentifier == transactionIdString {
82
+ SKPaymentQueue.default().finishTransaction(paymentTransaction)
83
+ return true
84
+ }
85
+ }
86
+ return false
87
+ }
88
+ if finishedLegacyTransaction {
89
+ return
90
+ }
91
+
92
+ throw FinishTransactionError.notFound(transactionId)
93
+ }
94
+ }
95
+
96
+ enum FinishTransactionError: Error {
97
+ case notFound(UInt64)
98
+ case verificationFailed(String)
99
+
100
+ var message: String {
101
+ switch self {
102
+ case .notFound(let id):
103
+ return "Transaction not found or already finished. Transaction ID: \(id)"
104
+ case .verificationFailed(let reason):
105
+ return "Transaction verification failed: \(reason)"
106
+ }
107
+ }
108
+ }
@@ -20,10 +20,14 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
20
20
  CAPPluginMethod(name: "consumePurchase", returnType: CAPPluginReturnPromise),
21
21
  CAPPluginMethod(name: "getAppTransaction", returnType: CAPPluginReturnPromise),
22
22
  CAPPluginMethod(name: "isEntitledToOldBusinessModel", returnType: CAPPluginReturnPromise),
23
- CAPPluginMethod(name: "getStorefront", returnType: CAPPluginReturnPromise)
23
+ CAPPluginMethod(name: "getStorefront", returnType: CAPPluginReturnPromise),
24
+ CAPPluginMethod(name: "configure", returnType: CAPPluginReturnPromise),
25
+ CAPPluginMethod(name: "getUnfinishedTransactions", returnType: CAPPluginReturnPromise),
26
+ CAPPluginMethod(name: "finishTransaction", returnType: CAPPluginReturnPromise)
24
27
  ]
25
28
 
26
- private let pluginVersion: String = "8.8.1"
29
+ private let pluginVersion: String = "8.9.0"
30
+ var autoFinishTransactions: Bool = true
27
31
  private var transactionUpdatesTask: Task<Void, Never>?
28
32
 
29
33
  @objc func getPluginVersion(_ call: CAPPluginCall) {
@@ -31,7 +35,9 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
31
35
  }
32
36
 
33
37
  override public func load() {
38
+ readAutoFinishTransactionsFromConfig()
34
39
  super.load()
40
+ NativePurchasesLog.configure(debugLogging: getConfig().getBoolean("debugLogging", false))
35
41
  startTransactionUpdatesListener()
36
42
  }
37
43
 
@@ -40,6 +46,10 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
40
46
  transactionUpdatesTask = nil
41
47
  }
42
48
 
49
+ func applyAutoFinishTransactionsSetting(_ value: Bool) {
50
+ autoFinishTransactions = value
51
+ }
52
+
43
53
  private func startTransactionUpdatesListener() {
44
54
  transactionUpdatesTask?.cancel()
45
55
  transactionUpdatesTask = Task.detached { [weak self] in
@@ -47,13 +57,18 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
47
57
  guard !Task.isCancelled else { break }
48
58
  switch result {
49
59
  case .verified(let transaction):
50
- let payload = await TransactionHelpers.buildTransactionResponse(
60
+ let shouldFinish = await MainActor.run { self?.autoFinishTransactions ?? true }
61
+ var payload = await TransactionHelpers.buildTransactionResponse(
51
62
  from: transaction,
52
63
  jwsRepresentation: result.jwsRepresentation,
53
64
  alwaysIncludeWillCancel: true
54
65
  )
55
- await transaction.finish()
56
- try? await Task.sleep(nanoseconds: 500_000_000)
66
+ if shouldFinish {
67
+ await transaction.finish()
68
+ try? await Task.sleep(nanoseconds: 500_000_000)
69
+ } else {
70
+ payload["needsFinish"] = true
71
+ }
57
72
  await MainActor.run {
58
73
  self?.notifyListeners("transactionUpdated", data: payload)
59
74
  }
@@ -74,7 +89,7 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
74
89
  }
75
90
 
76
91
  @objc func getStorefront(_ call: CAPPluginCall) {
77
- print("getStorefront")
92
+ NativePurchasesLog.debug("getStorefront")
78
93
  Task {
79
94
  let storefront = await Storefront.current
80
95
  await MainActor.run {
@@ -85,7 +100,7 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
85
100
  ])
86
101
  } else {
87
102
  // No storefront (e.g. alternative distribution).
88
- print("getStorefront: no storefront available")
103
+ NativePurchasesLog.debug("getStorefront: no storefront available")
89
104
  call.resolve(["countryCode": ""])
90
105
  }
91
106
  }
@@ -93,7 +108,7 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
93
108
  }
94
109
 
95
110
  @objc func purchaseProduct(_ call: CAPPluginCall) {
96
- print("purchaseProduct")
111
+ NativePurchasesLog.debug("purchaseProduct")
97
112
  let productIdentifier = call.getString("productIdentifier", "")
98
113
  let quantity = call.getInt("quantity", 1)
99
114
  let appAccountToken = call.getString("appAccountToken")
@@ -105,7 +120,7 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
105
120
  return
106
121
  }
107
122
 
108
- print("Auto-acknowledge enabled: \(autoAcknowledge)")
123
+ NativePurchasesLog.debug("Auto-acknowledge enabled: \(autoAcknowledge)")
109
124
 
110
125
  Task { @MainActor in
111
126
  do {
@@ -131,22 +146,37 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
131
146
  }
132
147
 
133
148
  let result = try await product.purchase(options: purchaseOptions)
134
- print("purchaseProduct result \(result)")
135
- await self.handlePurchaseResult(result, call: call, autoFinish: autoAcknowledge)
149
+ NativePurchasesLog.debug("purchaseProduct flow finished with result type \(String(describing: result))")
150
+ let shouldAutoFinish = self.autoFinishTransactions && autoAcknowledge
151
+ await self.handlePurchaseResult(result, call: call, autoFinish: shouldAutoFinish)
136
152
  } catch {
137
- print(error)
153
+ NativePurchasesLog.debug(error)
138
154
  call.reject(error.localizedDescription)
139
155
  }
140
156
  }
141
157
  }
142
158
 
143
159
  @objc func restorePurchases(_ call: CAPPluginCall) {
144
- print("restorePurchases")
160
+ NativePurchasesLog.debug("restorePurchases")
145
161
  Task {
146
162
  do {
147
163
  try await AppStore.sync()
148
- for transaction in SKPaymentQueue.default().transactions {
149
- SKPaymentQueue.default().finishTransaction(transaction)
164
+ let shouldAutoFinish = await MainActor.run { self.autoFinishTransactions }
165
+ await MainActor.run {
166
+ for transaction in SKPaymentQueue.default().transactions {
167
+ switch transaction.transactionState {
168
+ case .failed:
169
+ SKPaymentQueue.default().finishTransaction(transaction)
170
+ case .purchased, .restored:
171
+ if shouldAutoFinish {
172
+ SKPaymentQueue.default().finishTransaction(transaction)
173
+ }
174
+ case .purchasing, .deferred:
175
+ continue
176
+ @unknown default:
177
+ continue
178
+ }
179
+ }
150
180
  }
151
181
  await MainActor.run { call.resolve() }
152
182
  } catch {
@@ -158,16 +188,19 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
158
188
  @objc func getProducts(_ call: CAPPluginCall) {
159
189
  let productIdentifiers = call.getArray("productIdentifiers", String.self) ?? []
160
190
  let productType = call.getString("productType", "inapp")
161
- print("productIdentifiers \(productIdentifiers)")
162
- print("productType \(productType)")
191
+ NativePurchasesLog.debug("productIdentifiers \(productIdentifiers)")
192
+ NativePurchasesLog.debug("productType \(productType)")
163
193
  Task {
164
194
  do {
165
195
  let products = try await Product.products(for: productIdentifiers)
166
- print("products \(products)")
167
- let productsJson: [[String: Any]] = products.map { $0.dictionary }
196
+ NativePurchasesLog.debug("getProducts returned \(products.count) product(s)")
197
+ var productsJson: [[String: Any]] = []
198
+ for product in products {
199
+ productsJson.append(await product.pluginDictionary())
200
+ }
168
201
  await MainActor.run { call.resolve(["products": productsJson]) }
169
202
  } catch {
170
- print("error \(error)")
203
+ NativePurchasesLog.debug("error \(error)")
171
204
  await MainActor.run { call.reject(error.localizedDescription) }
172
205
  }
173
206
  }
@@ -176,8 +209,8 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
176
209
  @objc func getProduct(_ call: CAPPluginCall) {
177
210
  let productIdentifier = call.getString("productIdentifier") ?? ""
178
211
  let productType = call.getString("productType", "inapp")
179
- print("productIdentifier \(productIdentifier)")
180
- print("productType \(productType)")
212
+ NativePurchasesLog.debug("productIdentifier \(productIdentifier)")
213
+ NativePurchasesLog.debug("productType \(productType)")
181
214
  if productIdentifier.isEmpty {
182
215
  call.reject("productIdentifier is empty")
183
216
  return
@@ -186,21 +219,22 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
186
219
  Task {
187
220
  do {
188
221
  let products = try await Product.products(for: [productIdentifier])
189
- print("products \(products)")
222
+ NativePurchasesLog.debug("getProduct returned \(products.count) product(s)")
190
223
  if let product = products.first {
191
- await MainActor.run { call.resolve(["product": product.dictionary]) }
224
+ let payload = await product.pluginDictionary()
225
+ await MainActor.run { call.resolve(["product": payload]) }
192
226
  } else {
193
227
  await MainActor.run { call.reject("Product not found") }
194
228
  }
195
229
  } catch {
196
- print(error)
230
+ NativePurchasesLog.debug(error)
197
231
  await MainActor.run { call.reject(error.localizedDescription) }
198
232
  }
199
233
  }
200
234
  }
201
235
 
202
236
  @objc func getPurchases(_ call: CAPPluginCall) {
203
- print("getPurchases")
237
+ NativePurchasesLog.debug("getPurchases")
204
238
  let appAccountTokenFilter = call.getString("appAccountToken")
205
239
  let onlyCurrentEntitlements = call.getBool("onlyCurrentEntitlements") ?? false
206
240
  Task {
@@ -217,7 +251,7 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
217
251
  }
218
252
 
219
253
  @objc func manageSubscriptions(_ call: CAPPluginCall) {
220
- print("manageSubscriptions")
254
+ NativePurchasesLog.debug("manageSubscriptions")
221
255
  Task { @MainActor in
222
256
  do {
223
257
  guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
@@ -227,14 +261,14 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
227
261
  try await AppStore.showManageSubscriptions(in: windowScene)
228
262
  call.resolve()
229
263
  } catch {
230
- print("manageSubscriptions error: \(error)")
264
+ NativePurchasesLog.debug("manageSubscriptions error: \(error)")
231
265
  call.reject(error.localizedDescription)
232
266
  }
233
267
  }
234
268
  }
235
269
 
236
270
  @objc func presentOfferCodeRedeemSheet(_ call: CAPPluginCall) {
237
- print("presentOfferCodeRedeemSheet")
271
+ NativePurchasesLog.debug("presentOfferCodeRedeemSheet")
238
272
  if #available(iOS 16.0, *) {
239
273
  Task { @MainActor in
240
274
  await self.handlePresentOfferCodeRedeemSheet(call)
@@ -245,7 +279,7 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
245
279
  }
246
280
 
247
281
  @objc func acknowledgePurchase(_ call: CAPPluginCall) {
248
- print("acknowledgePurchase called on iOS")
282
+ NativePurchasesLog.debug("acknowledgePurchase called on iOS")
249
283
 
250
284
  guard let purchaseToken = call.getString("purchaseToken") else {
251
285
  call.reject("purchaseToken is required")
@@ -258,26 +292,19 @@ public class NativePurchasesPlugin: CAPPlugin, CAPBridgedPlugin {
258
292
  }
259
293
 
260
294
  Task {
261
- var foundTransaction: Transaction?
262
- for await verificationResult in Transaction.all {
263
- if case .verified(let transaction) = verificationResult, transaction.id == transactionId {
264
- foundTransaction = transaction
265
- break
266
- }
267
- }
268
-
269
- guard let transaction = foundTransaction else {
295
+ do {
296
+ try await finishStoreKitTransaction(
297
+ transactionId: transactionId,
298
+ transactionIdString: purchaseToken
299
+ )
270
300
  await MainActor.run {
271
- call.reject("Transaction not found or already finished. Transaction ID: \(transactionId)")
301
+ NativePurchasesLog.debug("Transaction finished successfully")
302
+ call.resolve()
272
303
  }
273
- return
274
- }
275
-
276
- print("Manually finishing transaction: \(transaction.id)")
277
- await transaction.finish()
278
- await MainActor.run {
279
- print("Transaction finished successfully")
280
- call.resolve()
304
+ } catch let error as FinishTransactionError {
305
+ await MainActor.run { call.reject(error.message) }
306
+ } catch {
307
+ await MainActor.run { call.reject(error.localizedDescription) }
281
308
  }
282
309
  }
283
310
  }
@@ -330,7 +357,7 @@ extension NativePurchasesPlugin {
330
357
  try await AppStore.presentOfferCodeRedeemSheet(in: windowScene)
331
358
  call.resolve()
332
359
  } catch {
333
- print("presentOfferCodeRedeemSheet error: \(error)")
360
+ NativePurchasesLog.debug("presentOfferCodeRedeemSheet error: \(error)")
334
361
  call.reject(error.localizedDescription)
335
362
  }
336
363
  }
@@ -364,7 +391,7 @@ extension NativePurchasesPlugin {
364
391
  @available(iOS 16.0, *)
365
392
  @MainActor
366
393
  private func handleGetAppTransaction(_ call: CAPPluginCall) async {
367
- print("getAppTransaction called on iOS")
394
+ NativePurchasesLog.debug("getAppTransaction called on iOS")
368
395
  do {
369
396
  let verificationResult = try await AppTransaction.shared
370
397
  switch verificationResult {
@@ -384,7 +411,7 @@ extension NativePurchasesPlugin {
384
411
  call.reject("App transaction verification failed: \(error.localizedDescription)")
385
412
  }
386
413
  } catch {
387
- print("getAppTransaction error: \(error)")
414
+ NativePurchasesLog.debug("getAppTransaction error: \(error)")
388
415
  call.reject("Failed to get app transaction: \(error.localizedDescription)")
389
416
  }
390
417
  }
@@ -395,7 +422,7 @@ extension NativePurchasesPlugin {
395
422
  _ call: CAPPluginCall,
396
423
  targetBuildNumber: String
397
424
  ) async {
398
- print("isEntitledToOldBusinessModel called with targetBuildNumber: \(targetBuildNumber)")
425
+ NativePurchasesLog.debug("isEntitledToOldBusinessModel called with targetBuildNumber: \(targetBuildNumber)")
399
426
  do {
400
427
  let verificationResult = try await AppTransaction.shared
401
428
  switch verificationResult {
@@ -411,7 +438,7 @@ extension NativePurchasesPlugin {
411
438
  call.reject("App transaction verification failed: \(error.localizedDescription)")
412
439
  }
413
440
  } catch {
414
- print("isEntitledToOldBusinessModel error: \(error)")
441
+ NativePurchasesLog.debug("isEntitledToOldBusinessModel error: \(error)")
415
442
  call.reject("Failed to get app transaction: \(error.localizedDescription)")
416
443
  }
417
444
  }
@@ -93,6 +93,21 @@ extension Product {
93
93
 
94
94
  return product
95
95
  }
96
+
97
+ func pluginDictionary() async -> [String: Any] {
98
+ var product = dictionary
99
+ if let subscription = subscription {
100
+ let hasIntroOffer = subscription.introductoryOffer != nil
101
+ let isEligible: Bool? = hasIntroOffer ? await subscription.isEligibleForIntroOffer : nil
102
+ product["introEligibility"] = IntroEligibilityMapper.status(
103
+ hasIntroOffer: hasIntroOffer,
104
+ isEligibleForIntroOffer: isEligible
105
+ )
106
+ } else {
107
+ product["introEligibility"] = IntroEligibilityMapper.status(hasIntroOffer: false, isEligibleForIntroOffer: nil)
108
+ }
109
+ return product
110
+ }
96
111
  }
97
112
 
98
113
  private extension Product.SubscriptionOffer {
@@ -146,6 +146,21 @@ internal class TransactionHelpers {
146
146
  return dictionary
147
147
  }
148
148
 
149
+ static func collectUnfinishedTransactions() async throws -> [[String: Any]] {
150
+ var unfinished: [[String: Any]] = []
151
+ for await result in Transaction.unfinished {
152
+ guard case .verified(let transaction) = result else { continue }
153
+ var payload = await buildTransactionResponse(
154
+ from: transaction,
155
+ jwsRepresentation: result.jwsRepresentation,
156
+ alwaysIncludeWillCancel: true
157
+ )
158
+ payload["needsFinish"] = true
159
+ unfinished.append(payload)
160
+ }
161
+ return unfinished
162
+ }
163
+
149
164
  static func collectAllPurchases(appAccountTokenFilter: String?, onlyCurrentEntitlements: Bool = false) async throws -> [[String: Any]] {
150
165
  var allPurchases: [[String: Any]] = []
151
166
  if onlyCurrentEntitlements {
@@ -0,0 +1,17 @@
1
+ import XCTest
2
+ @testable import NativePurchasesPlugin
3
+
4
+ final class IntroEligibilityMapperTests: XCTestCase {
5
+ func testUnknownWhenNoIntroOffer() {
6
+ XCTAssertEqual(IntroEligibilityMapper.status(hasIntroOffer: false, isEligibleForIntroOffer: true), 0)
7
+ XCTAssertEqual(IntroEligibilityMapper.status(hasIntroOffer: false, isEligibleForIntroOffer: false), 0)
8
+ }
9
+
10
+ func testEligibleWhenIntroOfferAndEligible() {
11
+ XCTAssertEqual(IntroEligibilityMapper.status(hasIntroOffer: true, isEligibleForIntroOffer: true), 2)
12
+ }
13
+
14
+ func testIneligibleWhenIntroOfferButNotEligible() {
15
+ XCTAssertEqual(IntroEligibilityMapper.status(hasIntroOffer: true, isEligibleForIntroOffer: false), 1)
16
+ }
17
+ }
@@ -1,15 +1,9 @@
1
1
  import XCTest
2
2
  @testable import NativePurchasesPlugin
3
3
 
4
- class SocialLoginTests: XCTestCase {
5
- func testEcho() {
6
- // This is an example of a functional test case for a plugin.
7
- // Use XCTAssert and related functions to verify your tests produce the correct results.
8
-
9
- let implementation = NativePurchasesPlugin()
10
- let value = "Hello, World!"
11
- let result = implementation.echo(value)
12
-
13
- XCTAssertEqual(value, result)
4
+ final class NativePurchasesPluginTests: XCTestCase {
5
+ func testPluginVersionIsNonEmpty() {
6
+ let plugin = NativePurchasesPlugin()
7
+ XCTAssertFalse(plugin.identifier.isEmpty)
14
8
  }
15
9
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/native-purchases",
3
- "version": "8.8.1",
3
+ "version": "8.9.0",
4
4
  "description": "In-app Subscriptions Made Easy",
5
5
  "main": "dist/plugin.cjs.js",
6
6
  "module": "dist/esm/index.js",