From 44b0a74036eb9491586639ce0917e1044e42d565 Mon Sep 17 00:00:00 2001 From: Balazs Perlaki-Horvath Date: Thu, 14 Nov 2024 08:51:11 +0100 Subject: [PATCH] Add merchant session for macOS --- Model/Payment.swift | 22 +++++++++++++++++++++- Model/StripeKiwix.swift | 1 + 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/Model/Payment.swift b/Model/Payment.swift index b49f90b3..ff498dd5 100644 --- a/Model/Payment.swift +++ b/Model/Payment.swift @@ -24,6 +24,7 @@ struct Payment { let completeSubject = PassthroughSubject() + static let merchantSessionURL = URL(string: "https://apple-pay-gateway.apple.com" )! static let merchantId = "merchant.org.kiwix.apple" static let paymentSubscriptionManagingURL = "https://www.kiwix.org" static let supportedNetworks: [PKPaymentNetwork] = [ @@ -141,6 +142,25 @@ struct Payment { @available(macOS 13.0, *) func onMerchantSessionUpdate() async -> PKPaymentRequestMerchantSessionUpdate { - .init(status: .success, merchantSession: nil) + var request = URLRequest(url: Self.merchantSessionURL) + request.httpMethod = "GET" + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + do { + let (data, response) = try await URLSession.shared.data(for: request) + guard let httpResponse = response as? HTTPURLResponse, + (200..<300).contains(httpResponse.statusCode), + let dict = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else { + throw MerchantSessionError.invalidStatus + } + let session = PKPaymentMerchantSession(dictionary: dict) + return .init(status: .success, merchantSession: session) + } catch (let error) { + os_log("Merchant session not established: %@", type: .debug, error.localizedDescription) + return .init(status: .failure, merchantSession: nil) + } } } + +private enum MerchantSessionError: Error { + case invalidStatus +} diff --git a/Model/StripeKiwix.swift b/Model/StripeKiwix.swift index bfff6dbf..9e138dd3 100644 --- a/Model/StripeKiwix.swift +++ b/Model/StripeKiwix.swift @@ -41,6 +41,7 @@ struct StripeKiwix { func clientSecretForPayment(selectedAmount: SelectedAmount) async -> Result { do { + // TODO: for monthly this should create a setup-intent ! var request = URLRequest(url: endPoint.appending(path: "create-payment-intent")) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type")