How do I create protocol-driven abstractions with StoreKit 2 in Swift?

Creating protocol-driven abstractions with StoreKit 2 in Swift allows you to decouple your payment processing logic from the specific implementation of StoreKit. This can lead to more maintainable and testable code. Below, we present an example of how to achieve this using Swift protocols.

// Define a protocol for in-app purchase handling protocol InAppPurchaseHandler { func fetchProducts() async throws -> [Product] func purchase(product: Product) async throws -> Transaction func restorePurchases() async throws -> [Transaction] } // Implement the protocol using StoreKit 2 final class StoreKitPurchaseHandler: InAppPurchaseHandler { func fetchProducts() async throws -> [Product] { let products = try await Product.products(for: ["com.example.app.product1", "com.example.app.product2"]) return products } func purchase(product: Product) async throws -> Transaction { let result = try await product.purchase() switch result { case .success(let verificationResult): return try verificationResult.reconstructedTransaction() case .userCancelled, .pending: throw NSError(domain: "PurchaseError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Purchase was cancelled or is pending."]) } } func restorePurchases() async throws -> [Transaction] { let result = try await AppStore.sync() return result.transactions } } // Example usage func purchaseExample() async { let purchaseHandler: InAppPurchaseHandler = StoreKitPurchaseHandler() do { let products = try await purchaseHandler.fetchProducts() if let product = products.first { let transaction = try await purchaseHandler.purchase(product: product) print("Purchase successful: \(transaction.id)") } } catch { print("Failed to purchase: \(error.localizedDescription)") } }

Swift StoreKit 2 Protocol-Oriented Programming In-App Purchases Abstractions