-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathOpenIapModule.swift
More file actions
1467 lines (1312 loc) · 64.8 KB
/
OpenIapModule.swift
File metadata and controls
1467 lines (1312 loc) · 64.8 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
// UIKit: Required for UIApplication, UIWindowScene on iOS/tvOS/visionOS
#if canImport(UIKit)
import UIKit
#endif
// AppKit: Required for NSApplication, NSWindow on macOS
#if canImport(AppKit)
import AppKit
#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>?
// iOS-only: SKPaymentQueue observer for promoted in-app purchases
// Reference: https://developer.apple.com/documentation/storekit/promoting-in-app-purchases
#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()
// iOS-only: Register SKPaymentQueue observer for promoted in-app purchases
// Reference: https://developer.apple.com/documentation/storekit/promoting-in-app-purchases
#if os(iOS)
if !self.didRegisterPaymentQueueObserver {
await MainActor.run {
SKPaymentQueue.default().add(self)
}
self.didRegisterPaymentQueueObserver = true
}
#endif // os(iOS)
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:
// Return products that are subscriptions (both auto-renewable and non-renewing)
// Auto-renewable subscriptions have product.subscription != nil and use subscriptionEntries
// Non-renewing subscriptions have product.type == .nonRenewable but no subscription metadata
let autoRenewableSubs = subscriptionEntries.filter { sub in
fetchedProducts.contains { product in
product.id == sub.id && product.subscription != nil
}
}
// Include non-renewing subscriptions as ProductSubscriptionIOS
// Note: Non-renewing subscriptions in StoreKit 2 don't have subscription metadata
// (no discounts, intro offers, subscription period, or subscription group).
// This is a StoreKit limitation, not missing data - we include all available product info.
let nonRenewingSubs: [ProductSubscription] = fetchedProducts.compactMap { product in
guard product.type == .nonRenewable else { return nil }
return .productSubscriptionIos(ProductSubscriptionIOS(
currency: product.priceFormatStyle.currencyCode,
debugDescription: product.description,
description: product.description,
discountsIOS: nil, // StoreKit: Non-renewing subscriptions don't support discounts
displayName: product.displayName,
displayNameIOS: product.displayName,
displayPrice: product.displayPrice,
id: product.id,
introductoryPriceAsAmountIOS: nil, // StoreKit: Non-renewing subscriptions don't support intro offers
introductoryPriceIOS: nil,
introductoryPriceNumberOfPeriodsIOS: nil,
introductoryPricePaymentModeIOS: .empty,
introductoryPriceSubscriptionPeriodIOS: nil,
isFamilyShareableIOS: product.isFamilyShareable,
jsonRepresentationIOS: String(data: product.jsonRepresentation, encoding: .utf8) ?? "",
platform: .ios,
price: NSDecimalNumber(decimal: product.price).doubleValue,
subscriptionInfoIOS: nil, // StoreKit: Non-renewing subscriptions have no subscription metadata
subscriptionPeriodNumberIOS: nil,
subscriptionPeriodUnitIOS: nil,
title: product.displayName,
type: .subs,
typeIOS: .nonRenewingSubscription
))
}
let allSubs = autoRenewableSubs + nonRenewingSubs
return .subscriptions(allSubs.isEmpty ? nil : allSubs)
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? {
// iOS-only: Promoted in-app purchases (App Store promotional purchases) only available on iOS
// Reference: https://developer.apple.com/documentation/storekit/promoting-in-app-purchases
#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 // os(iOS)
}
// 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)
// Check if subscription is already owned before attempting purchase
// This prevents iOS from showing "You're already subscribed" alert
if product.type == .autoRenewable {
// Check current entitlements for this product
if let currentEntitlement = await product.currentEntitlement {
do {
let transaction = try checkVerified(currentEntitlement)
// Check if the subscription is active (not expired)
let isActive: Bool
if let expirationDate = transaction.expirationDate {
isActive = expirationDate > Date()
} else {
// No expiration date means it's active
isActive = true
}
if isActive {
// Note: product.currentEntitlement returns the active entitlement for the subscription group,
// not necessarily for this specific product SKU. This is StoreKit 2's expected behavior.
// We need to check if the active subscription's productID matches the requested SKU.
// If transaction.productID != sku, this is an upgrade/downgrade attempt - allow it
if transaction.productID != sku {
OpenIapLog.debug("""
✅ [requestPurchase] Allowing subscription change:
- From: \(transaction.productID)
- To: \(sku)
- This is an upgrade/downgrade within the subscription group
""")
// Don't block - let StoreKit handle the subscription change
} else {
// Same product - check if subscription is cancelled (will not auto-renew)
// or if user has scheduled a different subscription for next renewal
var willAutoRenew = true
var autoRenewPreference: String?
if let subscription = product.subscription {
do {
let statuses = try await subscription.status
if let status = statuses.first {
switch status.renewalInfo {
case .verified(let info):
willAutoRenew = info.willAutoRenew
autoRenewPreference = info.autoRenewPreference
case .unverified:
willAutoRenew = true
autoRenewPreference = nil
}
}
} catch {
OpenIapLog.debug("⚠️ Failed to check renewal status: \(error.localizedDescription)")
}
}
// Check if user has scheduled a different subscription
// autoRenewPreference is the product that will renew next (if different from current)
let hasScheduledChange = autoRenewPreference != nil && autoRenewPreference != transaction.productID
if hasScheduledChange {
// User has scheduled a change to a different product
// Allow them to change back or modify their scheduled change
OpenIapLog.debug("""
✅ [requestPurchase] Allowing modification of scheduled subscription change:
- Current: \(transaction.productID)
- Scheduled: \(autoRenewPreference ?? "unknown")
- Requesting: \(sku)
""")
} else if willAutoRenew {
// Only block if:
// - Same product as current active subscription
// - Will auto-renew
// - No scheduled change to a different product
OpenIapLog.debug("""
⚠️ [requestPurchase] Subscription already owned:
- SKU: \(sku)
- Transaction ID: \(transaction.id)
- Expiration: \(transaction.expirationDate?.description ?? "none")
- Will Auto-Renew: \(willAutoRenew)
""")
let error = makePurchaseError(code: .alreadyOwned, productId: sku)
emitPurchaseError(error)
throw error
} else {
OpenIapLog.debug("""
✅ [requestPurchase] Allowing repurchase of cancelled subscription:
- SKU: \(sku)
- Transaction ID: \(transaction.id)
- Expiration: \(transaction.expirationDate?.description ?? "none")
- Will Auto-Renew: \(willAutoRenew)
""")
}
}
}
} catch let purchaseError as PurchaseError {
// Always emit error for library user to handle
emitPurchaseError(purchaseError)
// If it's an alreadyOwned error, re-throw it to stop purchase flow
if purchaseError.code == .alreadyOwned {
throw purchaseError
}
// For other errors (like transactionValidationFailed), log and continue with purchase
OpenIapLog.debug("⚠️ Current entitlement verification failed: \(purchaseError.message)")
} catch {
// For verification errors, emit error but continue with purchase
let verificationError = makePurchaseError(
code: .transactionValidationFailed,
productId: sku,
message: "Current entitlement check failed: \(error.localizedDescription)"
)
OpenIapLog.debug("⚠️ Current entitlement check failed: \(error.localizedDescription)")
emitPurchaseError(verificationError)
}
}
}
let result: StoreKit.Product.PurchaseResult
do {
// iOS 17.0+, tvOS 17.0+, macOS 15.2+: Use purchase(confirmIn:options:) for better purchase confirmation UI
// Reference: https://developer.apple.com/documentation/storekit/product/purchase(confirmin:options:)-6dj6y
#if canImport(UIKit)
// iOS/tvOS: Use UIWindowScene
if #available(iOS 17.0, tvOS 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)
}
#elseif canImport(AppKit)
// macOS: Use NSWindow (macOS 15.2+)
if #available(macOS 15.2, *) {
let window: NSWindow? = await MainActor.run {
NSApplication.shared.windows.first
}
guard let window else {
let error = makePurchaseError(code: .purchaseError, message: "Could not find window")
emitPurchaseError(error)
throw error
}
result = try await product.purchase(confirmIn: window, 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
}
// Use PurchaseError.wrap to automatically map errors (including StoreKitError.userCancelled)
let purchaseError = PurchaseError.wrap(error, fallback: .purchaseError, productId: sku)
emitPurchaseError(purchaseError)
throw purchaseError
}
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
let isSubscription = product.type == .autoRenewable
OpenIapLog.debug("""
🎯 [requestPurchase] Purchase successful:
- Requested SKU: \(sku)
- Returned Product: \(transaction.productID)
- Transaction ID: \(transactionId)
- Purchase Date: \(transaction.purchaseDate)
- Product Type: \(product.type == .autoRenewable ? "subscription" : "non-subscription")
- SKU matches: \(transaction.productID == sku)
- Note: \(isSubscription ? "Subscription transactions will be emitted via Transaction.updates" : "Emitting directly")
""")
if shouldAutoFinish {
await transaction.finish()
} else {
await state.storePending(id: transactionId, transaction: transaction)
}
// Emit purchase update
// Note: Transaction.updates will NOT fire for purchases initiated via product.purchase()
// It only fires for background events (renewals, restores, external purchases)
emitPurchaseUpdate(purchase)
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] = []
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: \(purchasedItems.count) purchases (onlyActive=\(onlyActive))")
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()
}
@available(*, deprecated, message: "Use verifyPurchase")
public func validateReceiptIOS(_ props: VerifyPurchaseProps) async throws -> VerifyPurchaseResultIOS {
try await performVerifyPurchaseIOS(props)
}
private func performVerifyPurchaseIOS(_ props: VerifyPurchaseProps) async throws -> VerifyPurchaseResultIOS {
let receiptData = (try? await getReceiptDataIOS()) ?? ""
var latestPurchase: Purchase? = nil
var jws: String = ""
var isValid = false
// If apple options with JWS are provided, use that directly
// Otherwise, fetch the latest transaction from StoreKit
if let appleOptions = props.apple, !appleOptions.jws.isEmpty {
jws = appleOptions.jws
// When JWS is provided externally, we trust it's valid
// The caller should verify the JWS on their server
isValid = true
} else {
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 VerifyPurchaseResultIOS(
isValid: isValid,
jwsRepresentation: jws,
latestTransaction: latestPurchase,
receiptData: receiptData
)
}
@available(*, deprecated, message: "Use verifyPurchase")
public func validateReceipt(_ props: VerifyPurchaseProps) async throws -> VerifyPurchaseResult {
try await verifyPurchase(props)
}
public func verifyPurchase(_ props: VerifyPurchaseProps) async throws -> VerifyPurchaseResult {
let iosResult = try await performVerifyPurchaseIOS(props)
return .verifyPurchaseResultIos(iosResult)
}
public func verifyPurchaseWithProvider(_ props: VerifyPurchaseWithProviderProps) async throws -> VerifyPurchaseWithProviderResult {
guard props.provider == .iapkit else {
throw makePurchaseError(code: .featureNotSupported, message: "Provider \(props.provider.rawValue) is not supported")
}
guard let iapkit = props.iapkit else {
throw makePurchaseError(code: .developerError, message: "Missing IAPKit verification parameters")
}
let result = try await verifyPurchaseWithIapkit(props: iapkit)
return VerifyPurchaseWithProviderResult(
iapkit: result,
provider: props.provider
)
}
// NOTE: This Apple module intentionally sends only Apple payloads to IAPKit.
// The buildIapkitPayload function has a .google branch for type completeness,
// but it is never invoked from this module.
private func verifyPurchaseWithIapkit(props: RequestVerifyPurchaseWithIapkitProps) async throws -> RequestVerifyPurchaseWithIapkitResult {
// URL is a constant and cannot fail, so force unwrap is safe
let url = URL(string: "https://api.iapkit.com/v1/purchase/verify")!
// On Apple, only Apple verification is supported
guard props.apple != nil else {
throw makePurchaseError(code: .developerError, message: "IAPKit verification on Apple requires an apple payload")
}
let store: IapStore = .apple
let body = try buildIapkitPayload(props: props, store: store)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if let apiKey = props.apiKey, apiKey.isEmpty == false {
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
}
request.httpBody = body
// Log request details for debugging
OpenIapLog.debug("IAPKit request URL: \(url.absoluteString)")
if let requestBody = String(data: body, encoding: .utf8) {
// Truncate JWS for readability (keep first/last 50 chars)
let truncatedBody = requestBody.count > 200
? String(requestBody.prefix(100)) + "..." + String(requestBody.suffix(50))
: requestBody
OpenIapLog.debug("IAPKit request body: \(truncatedBody)")
}
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw makePurchaseError(code: .networkError, message: "Invalid response")
}
guard (200...299).contains(httpResponse.statusCode) else {
let responseBody = String(data: data, encoding: .utf8) ?? ""
OpenIapLog.warn("verifyPurchaseWithProvider failed (HTTP \(httpResponse.statusCode)): \(responseBody)")
// Extract concise error message from IAPKit response
var errorMessage = "HTTP \(httpResponse.statusCode)"
if let jsonData = responseBody.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] {
errorMessage = extractIapkitErrorMessage(from: json) ?? errorMessage
}
throw makePurchaseError(code: .receiptFailed, message: errorMessage)
}
// Log raw response for debugging
let jsonString = String(data: data, encoding: .utf8) ?? ""
OpenIapLog.info("IAPKit raw response: \(jsonString)")
// Parse manually to handle extra fields from IAPKit
// API response format: { "store": "apple", "isValid": true, "state": "PURCHASED" }
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
OpenIapLog.warn("Failed to parse IAPKit verification response. Raw: \(jsonString)")
throw makePurchaseError(code: .receiptFailed, message: "Unable to parse verification response")
}
// Check for error response format: { "errors": [{ "code": "...", "message": "..." }] }
if let errors = json["errors"] as? [[String: Any]], let firstError = errors.first {
let errorMessage = firstError["message"] as? String ?? "Unknown error"
let errorCode = firstError["code"] as? String ?? "unknown"
OpenIapLog.warn("IAPKit verification error: \(errorCode) - \(errorMessage)")
throw makePurchaseError(code: .receiptFailed, message: errorMessage)
}
let isValid = (json["isValid"] as? Bool) ?? false
let stateString = json["state"] as? String ?? "UNKNOWN"
// IAPKit API returns UPPER_SNAKE_CASE (e.g., "PURCHASED", "PENDING_ACKNOWLEDGMENT")
// Swift enum expects lower-kebab-case (e.g., "purchased", "pending-acknowledgment")
let normalizedState = stateString.lowercased().replacingOccurrences(of: "_", with: "-")
let parsedState = IapkitPurchaseState(rawValue: normalizedState) ?? .unknown
let storeString = json["store"] as? String
let parsedStore = storeString.flatMap { IapStore(rawValue: $0) } ?? store
OpenIapLog.info("IAPKit verification result: store=\(parsedStore.rawValue), isValid=\(isValid), state=\(parsedState.rawValue)")
return RequestVerifyPurchaseWithIapkitResult(isValid: isValid, state: parsedState, store: parsedStore)
}
private struct IapkitApplePayload: Codable {
let store: IapStore
let jws: String
}
private struct IapkitGooglePayload: Codable {
let store: IapStore
let purchaseToken: String
}
private func buildIapkitPayload(props: RequestVerifyPurchaseWithIapkitProps, store: IapStore) throws -> Data {
let encoder = JSONEncoder()
encoder.outputFormatting = [.withoutEscapingSlashes]
switch store {
case .apple:
guard let apple = props.apple else {
throw makePurchaseError(code: .developerError, message: "Apple verification parameters are required")
}
guard apple.jws.isEmpty == false else {
throw makePurchaseError(code: .developerError, message: "JWS is required")
}
let payload = IapkitApplePayload(
store: store,
jws: apple.jws
)
return try encoder.encode(payload)
case .google, .horizon:
guard let google = props.google else {
throw makePurchaseError(code: .developerError, message: "Google verification parameters are required")
}
guard google.purchaseToken.isEmpty == false else {
throw makePurchaseError(code: .developerError, message: "purchaseToken is required")
}
let payload = IapkitGooglePayload(
store: store,
purchaseToken: google.purchaseToken
)
return try encoder.encode(payload)
case .unknown:
throw makePurchaseError(code: .developerError, message: "Unknown store type")
}
}
/// Extract concise error message from IAPKit error response.
/// IAPKit returns nested error structures - we extract the deepest originalError for clarity.
private func extractIapkitErrorMessage(from json: [String: Any]) -> String? {
// Try to get details.originalError first (deepest level)
if let details = json["details"] as? [String: Any],
let originalError = details["originalError"] as? String {
// originalError might be a JSON string, try to parse it
if let data = originalError.data(using: .utf8),
let nested = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
return extractIapkitErrorMessage(from: nested) ?? originalError
}
return originalError
}
// Try errors array format: { "errors": [{ "message": "..." }] }
if let errors = json["errors"] as? [[String: Any]], let firstError = errors.first {
return extractIapkitErrorMessage(from: firstError)
}
// Try message field, but avoid the verbose nested JSON string
if let message = json["message"] as? String, !message.contains("{\"error\"") {
return message
}
// Fallback to error code
return json["error"] as? String
}
// 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
}
/// Get the app transaction that represents the user's purchase of the app
/// - Note: Available on iOS 16.0+, macOS 14.0+, tvOS 16.0+, watchOS 9.0+
/// - SeeAlso: https://developer.apple.com/documentation/storekit/apptransaction
@available(iOS 16.0, macOS 14.0, tvOS 16.0, watchOS 9.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 allSubscriptions: [ActiveSubscription] = []
for await verification in Transaction.currentEntitlements {
do {
let transaction = try checkVerified(verification)
guard transaction.productType == .autoRenewable else { continue }
// Skip upgraded subscriptions - they've been replaced
if transaction.isUpgraded {
continue
}
if let ids = subscriptionIds, ids.contains(transaction.productID) == false {
continue
}
let expiration = transaction.expirationDate
// If expiration date is nil, treat as inactive (expired or invalid)
// This prevents treating subscriptions without expiration dates as active
let isActive = expiration.map { $0 > Date() } ?? false
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, tvOS 16.0, watchOS 9.0, *) {
environment = transaction.environment.rawValue
} else {
environment = nil
}
// Fetch renewal info for subscription
let renewalInfo = await StoreKitTypesBridge.subscriptionRenewalInfoIOS(for: transaction)
allSubscriptions.append(
ActiveSubscription(
autoRenewingAndroid: nil,
daysUntilExpirationIOS: daysUntilExpiration,
environmentIOS: environment,
expirationDateIOS: expiration?.milliseconds,
isActive: isActive,
productId: transaction.productID,
purchaseToken: verification.jwsRepresentation,
renewalInfoIOS: renewalInfo,
transactionDate: transaction.purchaseDate.milliseconds,
transactionId: String(transaction.id),
willExpireSoon: willExpireSoon
)
)
} catch {
continue
}
}
OpenIapLog.debug("📊 Returning \(allSubscriptions.count) active subscriptions")
// Upgraded subscriptions are already filtered out by transaction.isUpgraded check
// Return all remaining subscriptions (active, downgraded, and cancelled)
return allSubscriptions
}
public func hasActiveSubscriptions(_ subscriptionIds: [String]?) async throws -> Bool {
let subscriptions = try await getActiveSubscriptions(subscriptionIds)
return subscriptions.contains { $0.isActive }
}
/// Show the subscription management interface
/// - Note: Available on iOS 15.0+, iPadOS 15.0+, Mac Catalyst 15.0+, macOS 14.0+, visionOS 1.0+. Not available on tvOS (subscriptions are managed in Settings > Accounts) or watchOS.
/// - SeeAlso: https://developer.apple.com/documentation/storekit/appstore/showmanagesubscriptions(in:)
public func deepLinkToSubscriptions(_ options: DeepLinkOptions?) async throws -> Void {
// tvOS: AppStore.showManageSubscriptions not available on tvOS (subscriptions managed in Settings > Accounts)
// watchOS: No window scene UI for showManageSubscriptions
#if !os(tvOS) && !os(watchOS)
#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)
#elseif canImport(AppKit)
// macOS: Needs NSWindow for showManageSubscriptions
// For now, throw unsupported - will need proper window integration
throw makePurchaseError(code: .featureNotSupported, message: "macOS window integration required")
#endif
#else
throw makePurchaseError(code: .featureNotSupported)
#endif // !os(tvOS) && !os(watchOS)
}
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
/// Begin a refund request for a transaction
/// - Note: Available on iOS 15.0+, iPadOS 15.0+, Mac Catalyst 15.0+, macOS 12.0+, visionOS 1.0+. Not available on tvOS or watchOS.
/// - SeeAlso: https://developer.apple.com/documentation/storekit/transaction/3803220-beginrefundrequest
public func beginRefundRequestIOS(sku: String) async throws -> String? {
// tvOS: Transaction.beginRefundRequest not available on tvOS
// watchOS: Transaction.beginRefundRequest not available on watchOS
#if !os(tvOS) && !os(watchOS)
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)
#if canImport(UIKit)
let scene: UIWindowScene? = await MainActor.run {