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 pathOpenIapStore.swift
More file actions
642 lines (535 loc) · 21.9 KB
/
OpenIapStore.swift
File metadata and controls
642 lines (535 loc) · 21.9 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
import Foundation
import StoreKit
/// Convenience store for OpenIapModule with managed listeners and state
/// Requires explicit initConnection() and endConnection() calls
@available(iOS 15.0, macOS 14.0, *)
@MainActor
public final class OpenIapStore: ObservableObject {
// MARK: - Published Properties
@Published public private(set) var isConnected: Bool = false
@Published public private(set) var products: [OpenIAP.Product] = []
@Published public private(set) var subscriptions: [OpenIAP.ProductSubscription] = []
@Published public private(set) var availablePurchases: [OpenIAP.Purchase] = []
@Published public private(set) var currentPurchase: OpenIAP.Purchase?
@Published public private(set) var currentPurchaseError: PurchaseError?
@Published public private(set) var activeSubscriptions: [ActiveSubscription] = []
@Published public private(set) var promotedProduct: String?
public var iosProducts: [ProductIOS] { products.compactMap { $0.asIOS() } }
public var iosSubscriptionProducts: [ProductSubscriptionIOS] { subscriptions.compactMap { $0.asIOS() } }
public var iosAvailablePurchases: [PurchaseIOS] { availablePurchases.compactMap { $0.asIOS() } }
public var iosCurrentPurchase: PurchaseIOS? { currentPurchase?.asIOS() }
// MARK: - UI Status Management
@Published public var status: IapStatus = IapStatus()
// MARK: - Private Properties
private let module = OpenIapModule.shared
private var listenerTokens: [Subscription] = []
// MARK: - Callbacks
public var onPurchaseSuccess: ((OpenIAP.Purchase) -> Void)?
public var onPurchaseError: ((PurchaseError) -> Void)?
public var onPromotedProduct: ((String) -> Void)?
// MARK: - Initialization
public init(
onPurchaseSuccess: ((OpenIAP.Purchase) -> Void)? = nil,
onPurchaseError: ((PurchaseError) -> Void)? = nil,
onPromotedProduct: ((String) -> Void)? = nil
) {
self.onPurchaseSuccess = onPurchaseSuccess
self.onPurchaseError = onPurchaseError
self.onPromotedProduct = onPromotedProduct
setupListeners()
}
deinit { listenerTokens.removeAll() }
// MARK: - Listener Management
private func setupListeners() {
let purchaseUpdate = module.purchaseUpdatedListener { [weak self] purchase in
Task { @MainActor in self?.handlePurchaseUpdate(purchase) }
}
listenerTokens.append(purchaseUpdate)
let purchaseError = module.purchaseErrorListener { [weak self] error in
Task { @MainActor in self?.handlePurchaseError(error) }
}
listenerTokens.append(purchaseError)
#if os(iOS)
let promoted = module.promotedProductListenerIOS { [weak self] productId in
Task { @MainActor in self?.handlePromotedProduct(productId) }
}
listenerTokens.append(promoted)
#endif
}
private func clearListeners() {
for token in listenerTokens { module.removeListener(token) }
listenerTokens.removeAll()
}
// MARK: - Connection Management
public func initConnection() async throws {
status.loadings.initConnection = true
defer { status.loadings.initConnection = false }
isConnected = try await module.initConnection()
}
public func endConnection() async throws {
clearListeners()
_ = try await module.endConnection()
isConnected = false
}
// MARK: - Event Handlers
private func handlePurchaseUpdate(_ purchase: OpenIAP.Purchase) {
currentPurchase = purchase
currentPurchaseError = nil
if let ios = purchase.asIOS() {
status.loadings.purchasing.remove(ios.productId)
status.lastPurchaseResult = PurchaseResultData(
productId: ios.productId,
transactionId: ios.transactionId,
timestamp: Date(timeIntervalSince1970: ios.transactionDate / 1000),
message: "Purchase successful"
)
availablePurchases = deduplicatePurchases(availablePurchases + [purchase])
}
onPurchaseSuccess?(purchase)
if let ios = purchase.asIOS() {
let shouldRefresh = ios.expirationDateIOS != nil
|| ios.isAutoRenewing
|| (ios.subscriptionGroupIdIOS?.isEmpty == false)
if shouldRefresh {
Task { await refreshPurchases() }
}
}
}
private func handlePurchaseError(_ error: PurchaseError) {
currentPurchase = nil
currentPurchaseError = error
if let productId = error.productId {
status.loadings.purchasing.remove(productId)
}
status.lastError = ErrorData(
code: error.code.rawValue,
message: error.message,
productId: error.productId
)
onPurchaseError?(error)
}
private func handlePromotedProduct(_ productId: String) {
promotedProduct = productId
onPromotedProduct?(productId)
}
// MARK: - Product Management
public func fetchProducts(skus: [String], type: ProductQueryType = .all) async throws {
status.loadings.fetchProducts = true
defer { status.loadings.fetchProducts = false }
let request = ProductRequest(skus: skus, type: type)
let result = try await module.fetchProducts(request)
switch result {
case .products(let list):
products = list ?? []
subscriptions = []
case .subscriptions(let list):
subscriptions = list ?? []
products = []
}
}
// MARK: - Purchase Management
public func getAvailablePurchases(options: PurchaseOptions? = nil) async throws {
status.loadings.restorePurchases = true
defer { status.loadings.restorePurchases = false }
let purchases = try await module.getAvailablePurchases(options)
availablePurchases = deduplicatePurchases(purchases)
OpenIapLog.debug("🧾 availablePurchases: \(purchases.count) total → \(availablePurchases.count) active")
// Show renewal info details for active subscriptions
let withRenewalInfo = availablePurchases.compactMap { $0.asIOS() }.filter { $0.renewalInfoIOS != nil }
for purchase in withRenewalInfo {
if let info = purchase.renewalInfoIOS {
OpenIapLog.debug(" 📋 \(purchase.productId) renewalInfo:")
OpenIapLog.debug(" • willAutoRenew: \(info.willAutoRenew)")
OpenIapLog.debug(" • autoRenewPreference: \(info.autoRenewPreference ?? "nil")")
if let pendingUpgrade = info.pendingUpgradeProductId {
OpenIapLog.debug(" • pendingUpgradeProductId: \(pendingUpgrade) ⚠️ UPGRADE PENDING")
}
if let expirationReason = info.expirationReason {
OpenIapLog.debug(" • expirationReason: \(expirationReason)")
}
if let renewalDate = info.renewalDate {
let date = Date(timeIntervalSince1970: renewalDate / 1000)
OpenIapLog.debug(" • renewalDate: \(date)")
}
if let gracePeriod = info.gracePeriodExpirationDate {
let date = Date(timeIntervalSince1970: gracePeriod / 1000)
OpenIapLog.debug(" • gracePeriodExpirationDate: \(date)")
}
if let offerId = info.renewalOfferId {
OpenIapLog.debug(" • renewalOfferId: \(offerId)")
}
if let offerType = info.renewalOfferType {
OpenIapLog.debug(" • renewalOfferType: \(offerType)")
}
}
}
}
public func requestPurchase(
sku: String,
type: ProductQueryType = .inApp,
autoFinish: Bool? = nil,
quantity: Int? = nil,
appAccountToken: String? = nil,
withOffer: DiscountOfferInputIOS? = nil
) async throws -> OpenIAP.Purchase? {
switch type {
case .subs:
let iosProps = RequestSubscriptionIosProps(
andDangerouslyFinishTransactionAutomatically: autoFinish,
appAccountToken: appAccountToken,
quantity: quantity,
sku: sku,
withOffer: withOffer
)
let request = RequestPurchaseProps(
request: .subscription(RequestSubscriptionPropsByPlatforms(android: nil, ios: iosProps)),
type: .subs
)
return try await requestPurchase(request)
default:
let iosProps = RequestPurchaseIosProps(
andDangerouslyFinishTransactionAutomatically: autoFinish,
appAccountToken: appAccountToken,
quantity: quantity,
sku: sku,
withOffer: withOffer
)
let request = RequestPurchaseProps(
request: .purchase(RequestPurchasePropsByPlatforms(android: nil, ios: iosProps)),
type: .inApp
)
return try await requestPurchase(request)
}
}
public func requestPurchase(_ params: RequestPurchaseProps) async throws -> OpenIAP.Purchase? {
clearCurrentPurchase()
clearCurrentPurchaseError()
if let sku = params.iosSku {
status.loadings.purchasing.insert(sku)
}
defer {
if let sku = params.iosSku {
status.loadings.purchasing.remove(sku)
}
}
let result = try await module.requestPurchase(params)
switch result {
case .purchase(let purchase?):
currentPurchase = purchase
return purchase
case .purchase(nil):
return nil
case .purchases(let purchases?):
availablePurchases = deduplicatePurchases(purchases)
currentPurchase = purchases.first
return purchases.first
case .purchases(nil):
return nil
case .none:
return nil
@unknown default:
return nil
}
}
public func finishTransaction(purchase: PurchaseIOS, isConsumable: Bool = false) async throws {
try await finishTransaction(purchase: .purchaseIos(purchase), isConsumable: isConsumable)
}
public func finishTransaction(purchase: Purchase, isConsumable: Bool = false) async throws {
guard let ios = purchase.asIOS() else {
throw PurchaseError(code: .featureNotSupported, message: "Finishing only supported for iOS purchases", productId: nil)
}
try await module.finishTransaction(purchase: purchase, isConsumable: isConsumable)
if currentPurchase?.transactionId == ios.transactionId {
clearCurrentPurchase()
}
status.lastPurchaseResult = nil
}
public func getActiveSubscriptions(subscriptionIds: [String]? = nil) async throws {
activeSubscriptions = try await module.getActiveSubscriptions(subscriptionIds)
OpenIapLog.debug("📊 activeSubscriptions: \(activeSubscriptions.count) subscriptions")
// Show renewal info details
for sub in activeSubscriptions where sub.renewalInfoIOS != nil {
if let info = sub.renewalInfoIOS {
OpenIapLog.debug(" 📋 \(sub.productId) renewalInfo:")
OpenIapLog.debug(" • willAutoRenew: \(info.willAutoRenew)")
if let pendingUpgrade = info.pendingUpgradeProductId {
OpenIapLog.debug(" • pendingUpgradeProductId: \(pendingUpgrade) ⚠️ UPGRADE PENDING")
}
}
}
}
public func hasActiveSubscriptions(subscriptionIds: [String]? = nil) async throws -> Bool {
try await module.hasActiveSubscriptions(subscriptionIds)
}
public func refreshPurchases(forceSync: Bool = false) async throws {
try await getAvailablePurchases()
guard forceSync else { return }
status.loadings.restorePurchases = true
defer { status.loadings.restorePurchases = false }
_ = try await module.syncIOS()
try await getAvailablePurchases()
}
// MARK: - Validation & Metadata
public func validateReceipt(sku: String) async throws -> ReceiptValidationResultIOS {
try await module.validateReceiptIOS(ReceiptValidationProps(sku: sku))
}
public func getPromotedProductIOS() async throws -> ProductIOS? {
try await module.getPromotedProductIOS()
}
public func getPendingTransactionsIOS() async throws -> [PurchaseIOS] {
try await module.getPendingTransactionsIOS()
}
public func getReceiptDataIOS() async throws -> String? {
try await module.getReceiptDataIOS()
}
public func getTransactionJwsIOS(sku: String) async throws -> String? {
try await module.getTransactionJwsIOS(sku: sku)
}
public func getStorefrontIOS() async throws -> String {
try await module.getStorefrontIOS()
}
@available(iOS 16.0, macOS 14.0, *)
public func getAppTransactionIOS() async throws -> AppTransaction? {
try await module.getAppTransactionIOS()
}
public func isEligibleForIntroOfferIOS(groupID: String) async throws -> Bool {
try await module.isEligibleForIntroOfferIOS(groupID: groupID)
}
public func subscriptionStatusIOS(sku: String) async throws -> [SubscriptionStatusIOS] {
try await module.subscriptionStatusIOS(sku: sku)
}
public func currentEntitlementIOS(sku: String) async throws -> PurchaseIOS? {
try await module.currentEntitlementIOS(sku: sku)
}
public func latestTransactionIOS(sku: String) async throws -> PurchaseIOS? {
try await module.latestTransactionIOS(sku: sku)
}
public func beginRefundRequestIOS(sku: String) async throws -> String? {
try await module.beginRefundRequestIOS(sku: sku)
}
public func isTransactionVerifiedIOS(sku: String) async throws -> Bool {
try await module.isTransactionVerifiedIOS(sku: sku)
}
public func syncIOS() async throws -> Bool {
try await module.syncIOS()
}
public func presentCodeRedemptionSheetIOS() async throws {
_ = try await module.presentCodeRedemptionSheetIOS()
}
public func showManageSubscriptionsIOS() async throws {
_ = try await module.showManageSubscriptionsIOS()
}
public func deepLinkToSubscriptionsIOS() async throws {
try await module.deepLinkToSubscriptions(nil)
}
public func clearTransactionIOS() async throws {
_ = try await module.clearTransactionIOS()
}
public func resetEphemeralState() {
currentPurchase = nil
currentPurchaseError = nil
status.reset()
}
// MARK: - Private Helpers
private func clearCurrentPurchase() {
currentPurchase = nil
}
private func clearCurrentPurchaseError() {
currentPurchaseError = nil
}
private func deduplicatePurchases(_ purchases: [OpenIAP.Purchase]) -> [OpenIAP.Purchase] {
var nonSubscriptionPurchases: [OpenIAP.Purchase] = []
var latestSubscriptionByProduct: [String: OpenIAP.Purchase] = [:]
var skippedInactive = 0
for purchase in purchases {
guard let iosPurchase = purchase.asIOS() else {
nonSubscriptionPurchases.append(purchase)
continue
}
let isSubscription = iosPurchase.expirationDateIOS != nil
|| iosPurchase.isAutoRenewing
|| (iosPurchase.subscriptionGroupIdIOS?.isEmpty == false)
if isSubscription == false {
nonSubscriptionPurchases.append(purchase)
continue
}
let isActive: Bool
if let expiry = iosPurchase.expirationDateIOS {
let expiryDate = Date(timeIntervalSince1970: expiry / 1000)
isActive = expiryDate > Date()
} else {
isActive = iosPurchase.isAutoRenewing
|| iosPurchase.purchaseState == .purchased
|| iosPurchase.purchaseState == .restored
}
guard isActive else {
skippedInactive += 1
continue
}
if let existing = latestSubscriptionByProduct[iosPurchase.productId], let existingIos = existing.asIOS() {
let shouldReplace = shouldReplaceSubscription(existing: existingIos, candidate: iosPurchase)
if shouldReplace {
latestSubscriptionByProduct[iosPurchase.productId] = purchase
}
} else {
latestSubscriptionByProduct[iosPurchase.productId] = purchase
}
}
if skippedInactive > 0 {
OpenIapLog.debug(" ↳ filtered out \(skippedInactive) inactive subscriptions")
}
let allPurchases = nonSubscriptionPurchases + Array(latestSubscriptionByProduct.values)
return allPurchases.sorted { lhs, rhs in
(lhs.asIOS()?.transactionDate ?? 0) > (rhs.asIOS()?.transactionDate ?? 0)
}
}
private func shouldReplaceSubscription(existing: PurchaseIOS, candidate: PurchaseIOS) -> Bool {
let existingDate = existing.transactionDate
let candidateDate = candidate.transactionDate
if candidateDate > existingDate { return true }
if candidateDate < existingDate { return false }
if existing.isAutoRenewing != candidate.isAutoRenewing {
return candidate.isAutoRenewing == false
}
let existingRevocation = existing.revocationDateIOS ?? 0
let candidateRevocation = candidate.revocationDateIOS ?? 0
if candidateRevocation != existingRevocation {
return candidateRevocation > existingRevocation
}
let existingExpiration = existing.expirationDateIOS ?? 0
let candidateExpiration = candidate.expirationDateIOS ?? 0
if candidateExpiration != existingExpiration {
return candidateExpiration > existingExpiration
}
return false
}
private func refreshPurchases() async {
do {
try await getAvailablePurchases()
} catch {
OpenIapLog.error("Failed to refresh purchases: \(error)")
}
}
}
// MARK: - Internal Helpers
@available(iOS 15.0, macOS 14.0, *)
private extension OpenIAP.Product {
func asIOS() -> ProductIOS? {
switch self {
case .productIos(let product):
return product
default:
return nil
}
}
}
@available(iOS 15.0, macOS 14.0, *)
private extension OpenIAP.ProductSubscription {
func asIOS() -> ProductSubscriptionIOS? {
switch self {
case .productSubscriptionIos(let product):
return product
default:
return nil
}
}
}
@available(iOS 15.0, macOS 14.0, *)
private extension OpenIAP.Purchase {
func asIOS() -> PurchaseIOS? {
switch self {
case .purchaseIos(let purchase):
return purchase
default:
return nil
}
}
var transactionId: String {
switch self {
case .purchaseIos(let purchase):
return purchase.transactionId
default:
return ""
}
}
}
@available(iOS 15.0, macOS 14.0, *)
private extension RequestPurchaseProps {
var iosSku: String? {
switch request {
case .purchase(let platforms):
return platforms.ios?.sku
case .subscription(let platforms):
return platforms.ios?.sku
}
}
}
// MARK: - Nested UI Status Types
@available(iOS 15.0, macOS 14.0, *)
public extension OpenIapStore {
struct IapStatus {
public var loadings: LoadingStates = LoadingStates()
public var lastPurchaseResult: PurchaseResultData?
public var lastError: ErrorData?
public var currentOperation: IapOperation?
public var operationHistory: [IapOperation] = []
public init() {}
public func isPurchasing(_ productId: String) -> Bool {
loadings.purchasing.contains(productId)
}
public var isLoading: Bool {
loadings.initConnection || loadings.fetchProducts || loadings.restorePurchases || !loadings.purchasing.isEmpty
}
public mutating func addToHistory(_ operation: IapOperation) {
operationHistory.insert(operation, at: 0)
if operationHistory.count > 10 {
operationHistory.removeLast()
}
}
public mutating func reset() {
loadings = LoadingStates()
lastPurchaseResult = nil
lastError = nil
currentOperation = nil
operationHistory.removeAll()
}
}
struct LoadingStates {
public var initConnection: Bool = false
public var fetchProducts: Bool = false
public var restorePurchases: Bool = false
public var purchasing: Set<String> = []
public init() {}
}
struct PurchaseResultData {
public let productId: String
public let transactionId: String
public let timestamp: Date
public let message: String
public init(productId: String, transactionId: String, timestamp: Date = Date(), message: String) {
self.productId = productId
self.transactionId = transactionId
self.timestamp = timestamp
self.message = message
}
}
struct ErrorData {
public let code: String
public let message: String
public let productId: String?
public init(code: String, message: String, productId: String?) {
self.code = code
self.message = message
self.productId = productId
}
}
enum IapOperation: String {
case initConnection
case fetchProducts
case restorePurchases
case requestPurchase
case finishTransaction
case validateReceipt
case custom
}
}