This repository was archived by the owner on Oct 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathOpenIapModule.swift
More file actions
1021 lines (901 loc) · 38 KB
/
OpenIapModule.swift
File metadata and controls
1021 lines (901 loc) · 38 KB
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
import StoreKit
#if canImport(UIKit)
import UIKit
#endif
@available(iOS 15.0, macOS 14.0, *)
public final class OpenIapModule: NSObject, OpenIapModuleProtocol {
public static let shared = OpenIapModule()
private var updateListenerTask: Task<Void, Error>?
private var productManager: ProductManager?
private let state = IapState()
private var initTask: Task<Bool, Error>?
#if os(iOS)
private var didRegisterPaymentQueueObserver = false
#endif
private override init() {
super.init()
}
deinit { updateListenerTask?.cancel() }
// MARK: - Connection Management
public func initConnection() async throws -> Bool {
if let task = initTask {
return try await task.value
}
let task = Task<Bool, Error> { [weak self] () -> Bool in
guard let self else { return false }
await self.cleanupExistingState()
self.productManager = ProductManager()
#if os(iOS)
if !self.didRegisterPaymentQueueObserver {
await MainActor.run {
SKPaymentQueue.default().add(self)
}
self.didRegisterPaymentQueueObserver = true
}
#endif
guard AppStore.canMakePayments else {
self.emitPurchaseError(self.makePurchaseError(code: .iapNotAvailable))
await self.state.setInitialized(false)
return false
}
await self.state.setInitialized(true)
self.startTransactionListener()
await self.processUnfinishedTransactions()
return true
}
initTask = task
do {
let value = try await task.value
initTask = nil
return value
} catch {
initTask = nil
throw error
}
}
public func endConnection() async throws -> Bool {
initTask?.cancel()
initTask = nil
await cleanupExistingState()
return true
}
// MARK: - Product Management
public func fetchProducts(_ params: ProductRequest) async throws -> FetchProductsResult {
guard !params.skus.isEmpty else {
let error = makePurchaseError(code: .emptySkuList)
emitPurchaseError(error)
throw error
}
try await ensureConnection()
guard let productManager else {
let error = makePurchaseError(code: .notPrepared)
emitPurchaseError(error)
throw error
}
let fetchedProducts: [StoreKit.Product]
do {
fetchedProducts = try await StoreKit.Product.products(for: params.skus)
for product in fetchedProducts {
await productManager.addProduct(product)
}
} catch {
let purchaseError = makePurchaseError(code: .queryProduct, message: error.localizedDescription)
emitPurchaseError(purchaseError)
throw purchaseError
}
// Only process products that were actually requested, not all cached products
var productEntries: [OpenIAP.Product] = []
var subscriptionEntries: [OpenIAP.ProductSubscription] = []
for product in fetchedProducts {
productEntries.append(await StoreKitTypesBridge.product(from: product))
if let subscription = await StoreKitTypesBridge.productSubscription(from: product) {
subscriptionEntries.append(subscription)
}
}
switch params.type ?? .all {
case .subs:
// Only return products that are actually subscriptions
let validSubs = subscriptionEntries.filter { sub in
fetchedProducts.contains { product in
product.id == sub.id && product.subscription != nil
}
}
return .subscriptions(validSubs.isEmpty ? nil : validSubs)
case .inApp:
let inApp = productEntries.compactMap { entry -> OpenIAP.Product? in
guard case let .productIos(value) = entry, value.type == .inApp else { return nil }
return entry
}
return .products(inApp.isEmpty ? nil : inApp)
case .all:
return .products(productEntries.isEmpty ? nil : productEntries)
}
}
public func getPromotedProductIOS() async throws -> ProductIOS? {
#if os(iOS)
let sku = await state.promotedProductIdentifier()
guard let sku else { return nil }
do {
try await ensureConnection()
} catch let purchaseError as PurchaseError {
throw purchaseError
}
await state.setPromotedProductId(sku)
do {
let product = try await storeProduct(for: sku)
return await StoreKitTypesBridge.productIOS(from: product)
} catch let purchaseError as PurchaseError {
await state.setPromotedProductId(nil)
throw purchaseError
} catch {
let wrapped = makePurchaseError(code: .queryProduct, productId: sku, message: error.localizedDescription)
emitPurchaseError(wrapped)
await state.setPromotedProductId(nil)
throw wrapped
}
#else
return nil
#endif
}
// MARK: - Purchase Management
public func requestPurchase(_ params: RequestPurchaseProps) async throws -> RequestPurchaseResult? {
try await ensureConnection()
let iosProps = try resolveIosPurchaseProps(from: params)
let sku = iosProps.sku
let product = try await storeProduct(for: sku)
let options = try StoreKitTypesBridge.purchaseOptions(from: iosProps)
let result: StoreKit.Product.PurchaseResult
do {
#if canImport(UIKit)
if #available(iOS 17.0, *) {
let scene: UIWindowScene? = await MainActor.run {
UIApplication.shared.connectedScenes.first as? UIWindowScene
}
guard let scene else {
let error = makePurchaseError(code: .purchaseError, message: "Could not find window scene")
emitPurchaseError(error)
throw error
}
result = try await product.purchase(confirmIn: scene, options: options)
} else {
result = try await product.purchase(options: options)
}
#else
result = try await product.purchase(options: options)
#endif
} catch {
// Enhanced error handling for promotional offers
if iosProps.withOffer != nil {
OpenIapLog.error("Purchase with promotional offer failed: \(error.localizedDescription)")
let enhancedMessage = """
Promotional offer purchase failed: \(error.localizedDescription)
Common causes:
1. Invalid signature - verify server generates correct signature with exact parameter order
2. Empty appAccountToken - ensure empty string ('') is used in signature, not null
3. Sandbox testing - ensure current subscription has expired before testing offers
4. Offer eligibility - user may not be eligible for this promotional offer
"""
let purchaseError = makePurchaseError(
code: .purchaseError,
productId: sku,
message: enhancedMessage
)
emitPurchaseError(purchaseError)
throw purchaseError
}
// Re-throw original error for non-promotional purchases
throw error
}
switch result {
case .success(let verification):
let transaction = try checkVerified(verification)
let purchase = await StoreKitTypesBridge.purchase(from: transaction, jwsRepresentation: verification.jwsRepresentation)
let transactionId = String(transaction.id)
let shouldAutoFinish = iosProps.andDangerouslyFinishTransactionAutomatically == true
if await state.isProcessed(transactionId) == false {
await state.markProcessed(transactionId)
emitPurchaseUpdate(purchase)
}
if shouldAutoFinish {
await transaction.finish()
} else {
await state.storePending(id: transactionId, transaction: transaction)
}
return .purchase(purchase)
case .userCancelled:
let error = makePurchaseError(code: .userCancelled, productId: sku)
emitPurchaseError(error)
throw error
case .pending:
let error = makePurchaseError(code: .deferredPayment, productId: sku)
emitPurchaseError(error)
throw error
@unknown default:
let error = makePurchaseError(code: .unknown, productId: sku)
emitPurchaseError(error)
throw error
}
}
public func requestPurchaseOnPromotedProductIOS() async throws -> Bool {
throw makePurchaseError(code: .featureNotSupported)
}
public func restorePurchases() async throws -> Void {
_ = try await syncIOS()
}
public func getAvailablePurchases(_ options: PurchaseOptions?) async throws -> [Purchase] {
try await ensureConnection()
let onlyActive = options?.onlyIncludeActiveItemsIOS ?? false
var purchasedItems: [Purchase] = []
OpenIapLog.debug("🔍 getAvailablePurchases called. onlyActive=\(onlyActive)")
for await verification in (onlyActive ? Transaction.currentEntitlements : Transaction.all) {
do {
let transaction = try checkVerified(verification)
if onlyActive, let expirationDate = transaction.expirationDate, expirationDate <= Date() {
continue
}
let purchase = await StoreKitTypesBridge.purchase(
from: transaction,
jwsRepresentation: verification.jwsRepresentation
)
purchasedItems.append(purchase)
} catch {
OpenIapLog.error("getAvailablePurchases: failed to verify transaction: \(error)")
continue
}
}
OpenIapLog.debug("🔍 getAvailablePurchases returning \(purchasedItems.count) purchases")
return purchasedItems
}
// MARK: - Transaction Management
public func finishTransaction(purchase: PurchaseInput, isConsumable: Bool?) async throws -> Void {
let identifier = purchase.id
if let pending = await state.getPending(id: identifier) {
await pending.finish()
await state.removePending(id: identifier)
return
}
guard let numericId = UInt64(identifier) else {
let error = makePurchaseError(code: .purchaseError, message: "Invalid transaction identifier")
emitPurchaseError(error)
throw error
}
for await result in Transaction.currentEntitlements {
do {
let transaction = try checkVerified(result)
if transaction.id == numericId {
await transaction.finish()
return
}
} catch {
continue
}
}
for await result in Transaction.unfinished {
do {
let transaction = try checkVerified(result)
if transaction.id == numericId {
await transaction.finish()
return
}
} catch {
continue
}
}
let error = makePurchaseError(code: .purchaseError, message: "Transaction not found")
emitPurchaseError(error)
throw error
}
public func getPendingTransactionsIOS() async throws -> [PurchaseIOS] {
let snapshot = await state.pendingSnapshot()
var purchases: [PurchaseIOS] = []
for transaction in snapshot {
purchases.append(await StoreKitTypesBridge.purchaseIOS(from: transaction, jwsRepresentation: nil))
}
return purchases
}
public func clearTransactionIOS() async throws -> Bool {
for await result in Transaction.unfinished {
do {
let transaction = try checkVerified(result)
await transaction.finish()
await state.removePending(id: String(transaction.id))
} catch {
continue
}
}
return true
}
public func isTransactionVerifiedIOS(sku: String) async throws -> Bool {
let product = try await storeProduct(for: sku)
guard let result = await product.latestTransaction else { return false }
do {
_ = try checkVerified(result)
return true
} catch {
return false
}
}
public func getTransactionJwsIOS(sku: String) async throws -> String? {
let product = try await storeProduct(for: sku)
guard let result = await product.latestTransaction else {
let error = makePurchaseError(code: .skuNotFound, productId: sku)
emitPurchaseError(error)
throw error
}
return result.jwsRepresentation
}
// MARK: - Validation
public func getReceiptDataIOS() async throws -> String? {
guard let receiptURL = Bundle.main.appStoreReceiptURL,
FileManager.default.fileExists(atPath: receiptURL.path) else {
return nil
}
let data = try Data(contentsOf: receiptURL)
return data.base64EncodedString()
}
public func validateReceiptIOS(_ props: ReceiptValidationProps) async throws -> ReceiptValidationResultIOS {
let receiptData = (try? await getReceiptDataIOS()) ?? ""
var latestPurchase: Purchase? = nil
var jws: String = ""
var isValid = false
do {
let product = try await storeProduct(for: props.sku)
if let result = await product.latestTransaction {
jws = result.jwsRepresentation
let transaction = try checkVerified(result)
latestPurchase = .purchaseIos(await StoreKitTypesBridge.purchaseIOS(from: transaction, jwsRepresentation: result.jwsRepresentation))
isValid = true
}
} catch {
isValid = false
}
return ReceiptValidationResultIOS(
isValid: isValid,
jwsRepresentation: jws,
latestTransaction: latestPurchase,
receiptData: receiptData
)
}
public func validateReceipt(_ props: ReceiptValidationProps) async throws -> ReceiptValidationResult {
let iosResult = try await validateReceiptIOS(props)
return .receiptValidationResultIos(iosResult)
}
// MARK: - Store Information
public func getStorefrontIOS() async throws -> String {
guard let storefront = await Storefront.current else {
let error = makePurchaseError(code: .unknown)
emitPurchaseError(error)
throw error
}
return storefront.countryCode
}
@available(iOS 16.0, macOS 14.0, *)
public func getAppTransactionIOS() async throws -> AppTransaction? {
let verification = try await StoreKit.AppTransaction.shared
switch verification {
case .verified(let transaction):
return mapAppTransaction(transaction)
case .unverified:
return nil
}
}
// MARK: - Subscription Management
public func getActiveSubscriptions(_ subscriptionIds: [String]?) async throws -> [ActiveSubscription] {
var subscriptions: [ActiveSubscription] = []
for await verification in Transaction.currentEntitlements {
do {
let transaction = try checkVerified(verification)
guard transaction.productType == .autoRenewable else { continue }
if let ids = subscriptionIds, ids.contains(transaction.productID) == false {
continue
}
let expiration = transaction.expirationDate
let isActive = expiration.map { $0 > Date() } ?? true
let dayDelta = expiration.map { Calendar.current.dateComponents([.day], from: Date(), to: $0).day ?? 0 }
let daysUntilExpiration = dayDelta.map { Double($0) }
let willExpireSoon = dayDelta.map { $0 < 7 } ?? false
let environment: String?
if #available(iOS 16.0, *) {
environment = transaction.environment.rawValue
} else {
environment = nil
}
subscriptions.append(
ActiveSubscription(
autoRenewingAndroid: nil,
daysUntilExpirationIOS: daysUntilExpiration,
environmentIOS: environment,
expirationDateIOS: expiration?.milliseconds,
isActive: isActive,
productId: transaction.productID,
purchaseToken: verification.jwsRepresentation,
transactionDate: transaction.purchaseDate.milliseconds,
transactionId: String(transaction.id),
willExpireSoon: willExpireSoon
)
)
} catch {
continue
}
}
return subscriptions
}
public func hasActiveSubscriptions(_ subscriptionIds: [String]?) async throws -> Bool {
let subscriptions = try await getActiveSubscriptions(subscriptionIds)
return subscriptions.contains { $0.isActive }
}
public func deepLinkToSubscriptions(_ options: DeepLinkOptions?) async throws -> Void {
#if canImport(UIKit)
let scene: UIWindowScene? = await MainActor.run {
UIApplication.shared.connectedScenes.first as? UIWindowScene
}
guard let scene else {
throw makePurchaseError(code: .unknown)
}
try await AppStore.showManageSubscriptions(in: scene)
#else
throw makePurchaseError(code: .featureNotSupported)
#endif
}
public func subscriptionStatusIOS(sku: String) async throws -> [SubscriptionStatusIOS] {
let product = try await storeProduct(for: sku)
guard let subscription = product.subscription else {
let error = makePurchaseError(code: .skuNotFound, productId: sku)
emitPurchaseError(error)
throw error
}
do {
let statuses = try await subscription.status
return statuses.map { status in
let renewalInfo: RenewalInfoIOS?
switch status.renewalInfo {
case .verified(let info):
let jsonString = String(data: info.jsonRepresentation, encoding: .utf8) ?? info.jsonRepresentation.base64EncodedString()
renewalInfo = RenewalInfoIOS(
autoRenewPreference: info.autoRenewPreference,
jsonRepresentation: jsonString,
willAutoRenew: info.willAutoRenew
)
case .unverified:
renewalInfo = nil
}
return SubscriptionStatusIOS(
renewalInfo: renewalInfo,
state: String(describing: status.state)
)
}
} catch {
let purchaseError = makePurchaseError(code: .serviceError, message: error.localizedDescription)
emitPurchaseError(purchaseError)
throw purchaseError
}
}
public func currentEntitlementIOS(sku: String) async throws -> PurchaseIOS? {
let product = try await storeProduct(for: sku)
guard let result = await product.currentEntitlement else { return nil }
do {
let transaction = try checkVerified(result)
return await StoreKitTypesBridge.purchaseIOS(from: transaction, jwsRepresentation: result.jwsRepresentation)
} catch {
let error = makePurchaseError(code: .transactionValidationFailed, message: error.localizedDescription)
emitPurchaseError(error)
throw error
}
}
public func latestTransactionIOS(sku: String) async throws -> PurchaseIOS? {
let product = try await storeProduct(for: sku)
guard let result = await product.latestTransaction else { return nil }
do {
let transaction = try checkVerified(result)
return await StoreKitTypesBridge.purchaseIOS(from: transaction, jwsRepresentation: result.jwsRepresentation)
} catch {
let error = makePurchaseError(code: .transactionValidationFailed, message: error.localizedDescription)
emitPurchaseError(error)
throw error
}
}
// MARK: - Refunds
public func beginRefundRequestIOS(sku: String) async throws -> String? {
#if canImport(UIKit)
let product = try await storeProduct(for: sku)
guard let result = await product.latestTransaction else {
let error = makePurchaseError(code: .skuNotFound, productId: sku)
emitPurchaseError(error)
throw error
}
let transaction = try checkVerified(result)
let scene: UIWindowScene? = await MainActor.run {
UIApplication.shared.connectedScenes.first as? UIWindowScene
}
guard let scene else {
let error = makePurchaseError(code: .purchaseError, message: "Cannot find window scene")
emitPurchaseError(error)
throw error
}
let status = try await transaction.beginRefundRequest(in: scene)
switch status {
case .success:
return "success"
case .userCancelled:
return "userCancelled"
@unknown default:
return nil
}
#else
throw makePurchaseError(code: .featureNotSupported)
#endif
}
// MARK: - Misc
public func isEligibleForIntroOfferIOS(groupID: String) async throws -> Bool {
for await verification in Transaction.currentEntitlements {
do {
let transaction = try checkVerified(verification)
if transaction.subscriptionGroupID == groupID {
return false
}
} catch {
continue
}
}
return true
}
public func syncIOS() async throws -> Bool {
do {
try await AppStore.sync()
return true
} catch {
throw makePurchaseError(code: .serviceError, message: error.localizedDescription)
}
}
public func presentCodeRedemptionSheetIOS() async throws -> Bool {
#if canImport(UIKit)
await MainActor.run {
SKPaymentQueue.default().presentCodeRedemptionSheet()
}
return true
#else
throw makePurchaseError(code: .featureNotSupported)
#endif
}
public func showManageSubscriptionsIOS() async throws -> [PurchaseIOS] {
try await deepLinkToSubscriptions(nil)
return []
}
// MARK: - External Purchase (iOS 18.2+)
public func canPresentExternalPurchaseNoticeIOS() async throws -> Bool {
#if os(iOS)
if #available(iOS 18.2, *) {
return await ExternalPurchase.canPresent
} else {
return false
}
#else
return false
#endif
}
public func presentExternalPurchaseNoticeSheetIOS() async throws -> ExternalPurchaseNoticeResultIOS {
#if os(iOS)
if #available(iOS 18.2, *) {
guard await ExternalPurchase.canPresent else {
return ExternalPurchaseNoticeResultIOS(
error: "External purchase notice sheet is not available",
result: .dismissed
)
}
do {
let result = try await ExternalPurchase.presentNoticeSheet()
switch result {
case .continuedWithExternalPurchaseToken(_):
return ExternalPurchaseNoticeResultIOS(error: nil, result: .continue)
@unknown default:
return ExternalPurchaseNoticeResultIOS(
error: "User dismissed notice sheet",
result: .dismissed
)
}
} catch {
return ExternalPurchaseNoticeResultIOS(
error: error.localizedDescription,
result: .dismissed
)
}
} else {
throw makePurchaseError(
code: .featureNotSupported,
message: "External purchase notice sheet requires iOS 18.2 or later"
)
}
#else
throw makePurchaseError(code: .featureNotSupported)
#endif
}
public func presentExternalPurchaseLinkIOS(_ url: String) async throws -> ExternalPurchaseLinkResultIOS {
#if canImport(UIKit)
guard let customLink = URL(string: url) else {
return ExternalPurchaseLinkResultIOS(
error: "Invalid URL",
success: false
)
}
return await MainActor.run {
if UIApplication.shared.canOpenURL(customLink) {
UIApplication.shared.open(customLink, options: [:]) { success in
// Completion handler - link opened
}
return ExternalPurchaseLinkResultIOS(error: nil, success: true)
} else {
return ExternalPurchaseLinkResultIOS(
error: "Cannot open URL",
success: false
)
}
}
#else
throw makePurchaseError(code: .featureNotSupported)
#endif
}
// MARK: - Event Listener Registration
public func purchaseUpdatedListener(_ listener: @escaping PurchaseUpdatedListener) -> Subscription {
let subscription = Subscription(eventType: .purchaseUpdated)
Task { await state.addPurchaseUpdatedListener((subscription.id, listener)) }
return subscription
}
public func purchaseErrorListener(_ listener: @escaping PurchaseErrorListener) -> Subscription {
let subscription = Subscription(eventType: .purchaseError)
Task { await state.addPurchaseErrorListener((subscription.id, listener)) }
return subscription
}
public func promotedProductListenerIOS(_ listener: @escaping PromotedProductListener) -> Subscription {
let subscription = Subscription(eventType: .promotedProductIos)
Task { await state.addPromotedProductListener((subscription.id, listener)) }
return subscription
}
public func removeListener(_ subscription: Subscription) {
Task { await state.removeListener(id: subscription.id, type: subscription.eventType) }
Task { await MainActor.run { subscription.onRemove?() } }
}
public func removeAllListeners() {
Task { await state.removeAllListeners() }
}
// MARK: - Private Helpers
private func ensureConnection() async throws {
if await state.isInitialized == false {
_ = try await initConnection()
}
guard await state.isInitialized else {
let error = makePurchaseError(code: .initConnection)
emitPurchaseError(error)
throw error
}
guard AppStore.canMakePayments else {
let error = makePurchaseError(code: .iapNotAvailable)
emitPurchaseError(error)
throw error
}
}
private func cleanupExistingState() async {
updateListenerTask?.cancel()
updateListenerTask = nil
await state.reset()
#if os(iOS)
if didRegisterPaymentQueueObserver {
await MainActor.run {
SKPaymentQueue.default().remove(self)
}
didRegisterPaymentQueueObserver = false
}
#endif
if let manager = productManager { await manager.removeAll() }
productManager = nil
}
private func storeProduct(for sku: String) async throws -> StoreKit.Product {
guard let productManager else {
let error = makePurchaseError(code: .notPrepared)
emitPurchaseError(error)
throw error
}
if let product = await productManager.getProduct(productID: sku) {
return product
}
let products = try await StoreKit.Product.products(for: [sku])
guard let first = products.first else {
let error = makePurchaseError(code: .skuNotFound, productId: sku)
emitPurchaseError(error)
throw error
}
await productManager.addProduct(first)
return first
}
private func resolveIosPurchaseProps(from params: RequestPurchaseProps) throws -> RequestPurchaseIosProps {
switch params.request {
case let .purchase(platforms):
if let ios = platforms.ios {
return ios
}
case let .subscription(platforms):
if let ios = platforms.ios {
return RequestPurchaseIosProps(
andDangerouslyFinishTransactionAutomatically: ios.andDangerouslyFinishTransactionAutomatically,
appAccountToken: ios.appAccountToken,
quantity: ios.quantity,
sku: ios.sku,
withOffer: ios.withOffer
)
}
}
throw makePurchaseError(code: .purchaseError, message: "Missing iOS purchase parameters")
}
private func startTransactionListener() {
updateListenerTask = Task { [weak self] in
guard let self else { return }
for await verification in Transaction.updates {
do {
guard await self.state.isInitialized else { continue }
let transaction = try self.checkVerified(verification)
let transactionId = String(transaction.id)
// Skip revoked or upgraded transactions (happens during subscription upgrades)
if transaction.revocationDate != nil || transaction.isUpgraded {
OpenIapLog.debug("⏭️ Skipping revoked/upgraded transaction: \(transactionId)")
continue
}
if await self.state.isProcessed(transactionId) {
OpenIapLog.debug("⏭️ Skipping already processed transaction: \(transactionId)")
// Remove from processed set for future updates (e.g., subscription renewals)
await self.state.unmarkProcessed(transactionId)
continue
}
await self.state.markProcessed(transactionId)
await self.state.storePending(id: transactionId, transaction: transaction)
let purchase = await StoreKitTypesBridge.purchase(from: transaction, jwsRepresentation: verification.jwsRepresentation)
self.emitPurchaseUpdate(purchase)
Task {
try? await Task.sleep(nanoseconds: 5_000_000_000)
await self.state.unmarkProcessed(transactionId)
}
} catch {
let purchaseError: PurchaseError
if let existing = error as? PurchaseError {
purchaseError = existing
} else {
purchaseError = makePurchaseError(code: .transactionValidationFailed, message: error.localizedDescription)
}
self.emitPurchaseError(purchaseError)
}
}
}
}
private func processUnfinishedTransactions() async {
for await verification in Transaction.unfinished {
do {
let transaction = try checkVerified(verification)
await state.storePending(id: String(transaction.id), transaction: transaction)
} catch {
continue
}
}
}
private func checkVerified<T>(_ result: VerificationResult<T>) throws -> T {
switch result {
case .verified(let value):
return value
case .unverified:
throw makePurchaseError(code: .transactionValidationFailed, message: "Transaction verification failed")
}
}
private func emitPurchaseUpdate(_ purchase: Purchase) {
Task { [state] in
let listeners = await state.snapshotPurchaseUpdated()
await MainActor.run {
listeners.forEach { $0(purchase) }
}
}
}
private func emitPurchaseError(_ error: PurchaseError) {
Task { [state] in
let listeners = await state.snapshotPurchaseError()
await MainActor.run {
listeners.forEach { $0(error) }
}
}
}
private func emitPromotedProduct(_ sku: String) {
Task { [state] in
let listeners = await state.snapshotPromoted()
await MainActor.run {
listeners.forEach { $0(sku) }
}
}
}
private func makePurchaseError(code: ErrorCode, productId: String? = nil, message: String? = nil) -> PurchaseError {
PurchaseError(
code: code,
message: message ?? defaultMessage(for: code),
productId: productId
)
}
private func defaultMessage(for code: ErrorCode) -> String {
switch code {
case .unknown: return "Unknown error occurred"
case .userCancelled: return "User cancelled the purchase flow"
case .userError: return "User action error"
case .itemUnavailable: return "Item unavailable"
case .remoteError: return "Remote service error"
case .networkError: return "Network connection error"
case .serviceError: return "Store service error"
case .receiptFailed: return "Receipt validation failed"
case .receiptFinished: return "Receipt already finished"
case .receiptFinishedFailed: return "Receipt finish failed"
case .notPrepared: return "Billing is not prepared"
case .notEnded: return "Billing connection not ended"
case .alreadyOwned: return "Item already owned"
case .developerError: return "Developer configuration error"
case .billingResponseJsonParseError: return "Failed to parse billing response"
case .deferredPayment: return "Payment was deferred (pending approval)"
case .interrupted: return "Purchase flow interrupted"
case .iapNotAvailable: return "In-app purchases not available on this device"
case .purchaseError: return "Purchase error"
case .syncError: return "Sync error"
case .transactionValidationFailed: return "Transaction validation failed"
case .activityUnavailable: return "Required activity is unavailable"
case .alreadyPrepared: return "Billing already prepared"
case .pending: return "Transaction pending"
case .connectionClosed: return "Connection closed"
case .initConnection: return "Failed to initialize billing connection"
case .serviceDisconnected: return "Billing service disconnected"
case .queryProduct: return "Failed to query product"
case .skuNotFound: return "SKU not found"
case .skuOfferMismatch: return "SKU offer mismatch"
case .itemNotOwned: return "Item not owned"
case .billingUnavailable: return "Billing unavailable"
case .featureNotSupported: return "Feature not supported on this platform"
case .emptySkuList: return "Empty SKU list provided"
}
}
@available(iOS 16.0, macOS 14.0, *)
private func mapAppTransaction(_ transaction: StoreKit.AppTransaction) -> AppTransaction {
let appVersionId = transaction.appVersionID.map(Double.init) ?? 0
let appVersion = transaction.appVersion
let appId = transaction.appID.map(Double.init) ?? 0
// iOS 18.4+ properties - only compile with Xcode 16.4+ (Swift 6.1+)
// This prevents build failures on Xcode 16.3 and below
var appTransactionId: String? = nil
var originalPlatformValue: String? = nil
#if swift(>=6.1)
if #available(iOS 18.4, *) {
appTransactionId = String(transaction.appTransactionID)
originalPlatformValue = transaction.originalPlatform.rawValue
}
#endif
return AppTransaction(
appId: appId,
appTransactionId: appTransactionId,
appVersion: appVersion,
appVersionId: appVersionId,
bundleId: transaction.bundleID,
deviceVerification: transaction.deviceVerification.base64EncodedString(),
deviceVerificationNonce: transaction.deviceVerificationNonce.uuidString,
environment: transaction.environment.rawValue,
originalAppVersion: transaction.originalAppVersion,
originalPlatform: originalPlatformValue,
originalPurchaseDate: transaction.originalPurchaseDate.milliseconds,
preorderDate: transaction.preorderDate?.milliseconds,