|
| 1 | +import Foundation |
| 2 | + |
| 3 | +extension URL { |
| 4 | + /// Default Amore licensing server. Internal to `AmoreStore` so it does not |
| 5 | + /// collide with the public `URL.amoreServer` declared in `AmoreLicensing`. |
| 6 | + static let amoreServer = URL(string: "https://api.amore.computer")! |
| 7 | +} |
| 8 | + |
| 9 | +/// Lists the products configured for an Amore-licensed app. |
| 10 | +/// |
| 11 | +/// Fetch products with ``products()``, then read ``Product/checkoutURL`` on a |
| 12 | +/// returned product to send a customer to Stripe checkout. Use this to build |
| 13 | +/// paywalls, pickers, or any view that displays the products and prices |
| 14 | +/// configured in the licensing dashboard. |
| 15 | +public struct AmoreStore: Sendable { |
| 16 | + private let bundleIdentifier: String |
| 17 | + private let productsClient: ProductsClient |
| 18 | + |
| 19 | + /// Creates a store client for the given bundle identifier, targeting the Amore server. |
| 20 | + /// - Parameter bundleIdentifier: The app's bundle identifier. Defaults to `Bundle.main.bundleIdentifier`. |
| 21 | + public init(bundleIdentifier: String? = nil) { |
| 22 | + self.init(bundleIdentifier: bundleIdentifier, baseURL: .amoreServer) |
| 23 | + } |
| 24 | + |
| 25 | + /// Creates a store client for the given bundle identifier and server URL. |
| 26 | + /// - Parameters: |
| 27 | + /// - bundleIdentifier: The app's bundle identifier. Defaults to `Bundle.main.bundleIdentifier`. |
| 28 | + /// - baseURL: The licensing server base URL. |
| 29 | + public init(bundleIdentifier: String? = nil, baseURL: URL) { |
| 30 | + self.bundleIdentifier = bundleIdentifier ?? Bundle.main.bundleIdentifier ?? "" |
| 31 | + self.productsClient = HTTPProductsClient(baseURL: baseURL) |
| 32 | + } |
| 33 | + |
| 34 | + init(bundleIdentifier: String, productsClient: ProductsClient) { |
| 35 | + self.bundleIdentifier = bundleIdentifier |
| 36 | + self.productsClient = productsClient |
| 37 | + } |
| 38 | + |
| 39 | + /// Returns the products configured for this app. Purchasable products carry a |
| 40 | + /// non-`nil` ``Product/checkoutURL``. |
| 41 | + /// - Throws: ``StoreError`` if the request fails. |
| 42 | + public func products() async throws(StoreError) -> [Product] { |
| 43 | + do { |
| 44 | + return try await productsClient.fetchProducts(bundleIdentifier: bundleIdentifier) |
| 45 | + } catch let error as StoreError { |
| 46 | + throw error |
| 47 | + } catch { |
| 48 | + throw .network(error.localizedDescription) |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments