From 9aa6c023cf387669094e4efe89f0119644883f36 Mon Sep 17 00:00:00 2001 From: tiagocandido Date: Fri, 15 May 2026 16:02:39 +0200 Subject: [PATCH] Restore CheckoutDelegate with trimmed lifecycle API --- platforms/swift/README.md | 69 +++++-------------- .../ShopifyCheckoutKit/CheckoutDelegate.swift | 33 +++++++++ ...lient+CheckoutCommunicationProtocol.swift} | 7 +- .../CheckoutViewController.swift | 8 +-- .../ShopifyCheckoutKit/CheckoutWebView.swift | 20 ++++++ .../CheckoutWebViewController.swift | 9 ++- .../ShopifyCheckoutKit.swift | 8 +-- .../CheckoutWebViewControllerTests.swift | 37 ++++++++++ .../Mocks/MockCheckoutDelegate.swift | 13 ++++ .../ShopifyCheckoutKitTests.swift | 20 ++++++ 10 files changed, 158 insertions(+), 66 deletions(-) create mode 100644 platforms/swift/Sources/ShopifyCheckoutKit/CheckoutDelegate.swift rename platforms/swift/{Samples/MobileBuyIntegration/MobileBuyIntegration/Sources/CheckoutProtocolBridge.swift => Sources/ShopifyCheckoutKit/CheckoutProtocolClient+CheckoutCommunicationProtocol.swift} (88%) diff --git a/platforms/swift/README.md b/platforms/swift/README.md index bedb7b5b..4414adf1 100644 --- a/platforms/swift/README.md +++ b/platforms/swift/README.md @@ -144,7 +144,7 @@ struct ContentView: View { } .sheet(isPresented: $isPresented) { if let url = checkoutURL { - ShopifyCheckout(url: url) + ShopifyCheckout(checkout: url) /// Configuration .title("Checkout") .colorScheme(.automatic) @@ -156,17 +156,9 @@ struct ContentView: View { .onCancel { isPresented = false } - .onComplete { event in - handleCompletedEvent(event) - } .onFail { error in handleError(error) } - .onLinkClick { url in - if UIApplication.shared.canOpenURL(url) { - UIApplication.shared.open(url) - } - } .edgesIgnoringSafeArea(.all) } } @@ -373,15 +365,10 @@ A preloaded checkout _is not_ automatically invalidated when checkout sheet is c ## Monitoring the lifecycle of a checkout session -You can use the `ShopifyCheckoutKitDelegate` protocol to register callbacks for key lifecycle events during the checkout session: +You can use the `CheckoutDelegate` protocol to register callbacks for lifecycle events the host app needs to react to: ```swift -extension MyViewController: ShopifyCheckoutKitDelegate { - func checkoutDidComplete(event: CheckoutCompletedEvent) { - // Called when the checkout was completed successfully by the buyer. - // Use this to update UI, reset cart state, etc. - } - +extension MyViewController: CheckoutDelegate { func checkoutDidCancel() { // Called when the checkout was canceled by the buyer. // Use this to call `dismiss(animated:)`, etc. @@ -389,35 +376,25 @@ extension MyViewController: ShopifyCheckoutKitDelegate { func checkoutDidFail(error: CheckoutError) { // Called when the checkout encountered an error and has been aborted. The callback - // provides a `CheckoutError` enum, with one of the following values: - // Internal error: exception within the Checkout SDK code - // You can inspect and log the Erorr and stacktrace to identify the problem. - case sdkError(underlying: Swift.Error) + // provides a `CheckoutError` enum, with one of the following cases: - // Issued when the provided checkout URL results in an error related to shop configuration. - // Note: The SDK only supports stores migrated for extensibility. - case configurationError(message: String) + // Internal error: exception within the Checkout SDK code. + // Inspect the underlying error to identify the problem. + case sdkError(underlying: Swift.Error, recoverable: Bool) - // Unavailable error: checkout cannot be initiated or completed, e.g. due to network or server-side error + // Checkout cannot be initiated or completed, e.g. due to network or server-side error. // The provided message describes the error and may be logged and presented to the buyer. - case checkoutUnavailable(message: String) + case checkoutUnavailable(message: String, code: CheckoutUnavailable, recoverable: Bool) - // Expired error: checkout session associated with provided checkoutURL is no longer available. + // Checkout session associated with the provided checkoutURL is no longer available. // The provided message describes the error and may be logged and presented to the buyer. - case checkoutExpired(message: String) + case checkoutExpired(message: String, code: CheckoutErrorCode, recoverable: Bool) } - - func checkoutDidClickLink(url: URL) { - // Called when the buyer clicks a link within the checkout experience: - // - email address (`mailto:`), - // - telephone number (`tel:`), - // - web (`http:`) - // and is being directed outside the application. - } - } ``` +Completion events and other in-checkout messages flow through `CheckoutCommunicationProtocol` (UCP) — register handlers on a `CheckoutProtocol.Client` and pass it to `present(checkout:from:delegate:client:)`. See `Samples/MobileBuyIntegration` for a full example. + ## Error handling In the event of a checkout error occurring, the Checkout Kit _may_ attempt a retry to recover from the error. Recovery will happen in the background by discarding the failed webview and creating a new "recovery" instance. Recovery will be attempted in the following scenarios: @@ -428,15 +405,9 @@ In the event of a checkout error occurring, the Checkout Kit _may_ attempt a ret There are some caveats to note when this scenario occurs: 1. The checkout experience may look different to buyers. Though the kit will attempt to load any checkout customizations for the storefront, there is no guarantee they will show in recovery mode. -2. The `checkoutDidComplete(event:)` will be emitted with partial data. Invocations will only receive the order ID via `event.orderDetails.id`. +2. Completion events delivered via `CheckoutProtocol.complete` during recovery may contain partial data — typically only the order ID. -Should you wish to opt-out of this fallback experience entirely, you can do so by adding a `shouldRecoverFromError(error:)` method to your delegate controller. Errors given to the `checkoutDidFail(error:)` lifecycle method, will contain an `isRecoverable` property by default indicating whether the request should be retried or not. - -```swift -func shouldRecoverFromError(error: CheckoutError) { - return error.isRecoverable // default -} -``` +Errors given to `checkoutDidFail(error:)` carry an `isRecoverable` property indicating whether recovery will be attempted. ### `CheckoutError` @@ -495,15 +466,7 @@ Certain payment providers finalize transactions by redirecting customers to exte See the [Universal Links guide](https://github.com/Shopify/checkout-kit/blob/main/platforms/swift/documentation/universal_links.md) for information on how to get started with adding support for Offsite Payments in your app. -It is crucial for your app to be configured to handle URL clicks during the checkout process effectively. By default, the kit includes the following delegate method to manage these interactions. This code ensures that external links, such as HTTPS and deep links, are opened correctly by iOS. - -```swift -public func checkoutDidClickLink(url: URL) { - if UIApplication.shared.canOpenURL(url) { - UIApplication.shared.open(url) - } -} -``` +External links opened from within checkout (HTTPS, deep links, `mailto:`, `tel:`) are forwarded to `UIApplication.shared.open(_:)` by the kit, so universal links and Offsite Payments redirects route back to your app automatically once the rest of the universal-links setup is in place. ## Accelerated Checkouts diff --git a/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutDelegate.swift b/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutDelegate.swift new file mode 100644 index 00000000..c56586a8 --- /dev/null +++ b/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutDelegate.swift @@ -0,0 +1,33 @@ +/* + MIT License + + Copyright 2023 - Present, Shopify Inc. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +import Foundation + +/// A delegate protocol for managing checkout lifecycle events. +public protocol CheckoutDelegate: AnyObject { + /// Tells the delegate that the checkout was cancelled by the buyer. + func checkoutDidCancel() + + /// Tells the delegate that the checkout encountered one or more errors. + func checkoutDidFail(error: CheckoutError) +} diff --git a/platforms/swift/Samples/MobileBuyIntegration/MobileBuyIntegration/Sources/CheckoutProtocolBridge.swift b/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutProtocolClient+CheckoutCommunicationProtocol.swift similarity index 88% rename from platforms/swift/Samples/MobileBuyIntegration/MobileBuyIntegration/Sources/CheckoutProtocolBridge.swift rename to platforms/swift/Sources/ShopifyCheckoutKit/CheckoutProtocolClient+CheckoutCommunicationProtocol.swift index 442069cd..6aac007b 100644 --- a/platforms/swift/Samples/MobileBuyIntegration/MobileBuyIntegration/Sources/CheckoutProtocolBridge.swift +++ b/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutProtocolClient+CheckoutCommunicationProtocol.swift @@ -21,7 +21,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import ShopifyCheckoutKit -import ShopifyCheckoutProtocol +#if !COCOAPODS + import ShopifyCheckoutProtocol +#endif -extension CheckoutProtocol.Client: @retroactive CheckoutCommunicationProtocol {} +extension CheckoutProtocol.Client: CheckoutCommunicationProtocol {} diff --git a/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutViewController.swift b/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutViewController.swift index 026aa357..b905d16f 100644 --- a/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutViewController.swift +++ b/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutViewController.swift @@ -28,15 +28,15 @@ import SwiftUI import UIKit public class CheckoutViewController: UINavigationController { - public init(checkout url: URL, client: (any CheckoutCommunicationProtocol)? = nil) { - let rootViewController = CheckoutWebViewController(checkoutURL: url, client: client, entryPoint: nil) + public init(checkout url: URL, delegate: (any CheckoutDelegate)? = nil, client: (any CheckoutCommunicationProtocol)? = nil) { + let rootViewController = CheckoutWebViewController(checkoutURL: url, delegate: delegate, client: client, entryPoint: nil) rootViewController.notifyPresented() super.init(rootViewController: rootViewController) presentationController?.delegate = rootViewController } - package init(checkout url: URL, client: (any CheckoutCommunicationProtocol)? = nil, entryPoint: MetaData.EntryPoint? = nil) { - let rootViewController = CheckoutWebViewController(checkoutURL: url, client: client, entryPoint: entryPoint) + package init(checkout url: URL, delegate: (any CheckoutDelegate)? = nil, client: (any CheckoutCommunicationProtocol)? = nil, entryPoint: MetaData.EntryPoint? = nil) { + let rootViewController = CheckoutWebViewController(checkoutURL: url, delegate: delegate, client: client, entryPoint: entryPoint) rootViewController.notifyPresented() super.init(rootViewController: rootViewController) presentationController?.delegate = rootViewController diff --git a/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutWebView.swift b/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutWebView.swift index 672073e2..144a31ef 100644 --- a/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutWebView.swift +++ b/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutWebView.swift @@ -210,11 +210,31 @@ class CheckoutWebView: WKWebView { if CheckoutURL(from: url).isConfirmationPage() { CheckoutWebView.invalidate(disconnect: false) navigationObserver?.invalidate() + forwardSyntheticCompleteToClient(url: url) } } } } + private func forwardSyntheticCompleteToClient(url: URL) { + guard let client else { return } + let orderId = URLComponents(url: url, resolvingAgainstBaseURL: false)? + .queryItems? + .first(where: { $0.name == "order_id" })? + .value + let message = Self.syntheticCompleteMessage(orderId: orderId) + Task { _ = await client.process(message) } + } + + static func syntheticCompleteMessage(orderId: String?) -> String { + let id = orderId ?? "" + let orderJson = orderId.map { ",\"order\":{\"id\":\"\($0)\"}" } ?? "" + return "{\"jsonrpc\":\"2.0\",\"method\":\"ec.complete\"," + + "\"params\":{\"id\":\"\(id)\",\"currency\":\"\",\"line_items\":[],\"links\":[]," + + "\"status\":\"completed\",\"totals\":[]," + + "\"ucp\":{\"version\":\"\(CheckoutProtocol.specVersion)\",\"status\":\"success\"}\(orderJson)}}" + } + func instrument(_ payload: InstrumentationPayload) { OSLogger.shared.debug("Emitting instrumentation event with payload: \(payload)") checkoutBridge.instrument(self, payload) diff --git a/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutWebViewController.swift b/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutWebViewController.swift index a76f11d3..9086b0bc 100644 --- a/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutWebViewController.swift +++ b/platforms/swift/Sources/ShopifyCheckoutKit/CheckoutWebViewController.swift @@ -27,6 +27,7 @@ import WebKit class CheckoutWebViewController: UIViewController, UIAdaptivePresentationControllerDelegate { var onCancel: (() -> Void)? var onFail: ((CheckoutError) -> Void)? + weak var delegate: (any CheckoutDelegate)? var client: (any CheckoutCommunicationProtocol)? var checkoutViewDidFailWithErrorCount = 0 @@ -77,8 +78,9 @@ class CheckoutWebViewController: UIViewController, UIAdaptivePresentationControl // MARK: Initializers - public init(checkoutURL url: URL, client: (any CheckoutCommunicationProtocol)? = nil, entryPoint: MetaData.EntryPoint? = nil) { + public init(checkoutURL url: URL, delegate: (any CheckoutDelegate)? = nil, client: (any CheckoutCommunicationProtocol)? = nil, entryPoint: MetaData.EntryPoint? = nil) { checkoutURL = url + self.delegate = delegate self.client = client let checkoutView = CheckoutWebView.for(checkout: url, entryPoint: entryPoint) @@ -182,6 +184,7 @@ class CheckoutWebViewController: UIViewController, UIAdaptivePresentationControl } onCancel?() + delegate?.checkoutDidCancel() } package func presentFallbackViewController(url: URL) { @@ -192,6 +195,7 @@ class CheckoutWebViewController: UIViewController, UIAdaptivePresentationControl checkoutView.translatesAutoresizingMaskIntoConstraints = false checkoutView.scrollView.contentInsetAdjustmentBehavior = .never checkoutView.viewDelegate = self + checkoutView.client = client checkoutView.alpha = 1 view.addSubview(checkoutView) @@ -233,11 +237,12 @@ extension CheckoutWebViewController: CheckoutWebViewDelegate { func checkoutViewDidFailWithError(error: CheckoutError) { checkoutViewDidFailWithErrorCount += 1 CheckoutWebView.invalidate() - onFail?(error) if shouldAttemptRecovery(for: error) { presentFallbackViewController(url: checkoutURL) } else { + onFail?(error) + delegate?.checkoutDidFail(error: error) dismiss(animated: true) } } diff --git a/platforms/swift/Sources/ShopifyCheckoutKit/ShopifyCheckoutKit.swift b/platforms/swift/Sources/ShopifyCheckoutKit/ShopifyCheckoutKit.swift index b6da73a9..75281dfd 100644 --- a/platforms/swift/Sources/ShopifyCheckoutKit/ShopifyCheckoutKit.swift +++ b/platforms/swift/Sources/ShopifyCheckoutKit/ShopifyCheckoutKit.swift @@ -63,17 +63,17 @@ public func invalidate() { } @discardableResult -public func present(checkout url: URL, from: UIViewController, client: (any CheckoutCommunicationProtocol)? = nil) -> CheckoutViewController { +public func present(checkout url: URL, from: UIViewController, delegate: (any CheckoutDelegate)? = nil, client: (any CheckoutCommunicationProtocol)? = nil) -> CheckoutViewController { let decorated = CheckoutProtocol.url(for: url, colorScheme: configuration.colorScheme.rawValue) - let viewController = CheckoutViewController(checkout: decorated, client: client) + let viewController = CheckoutViewController(checkout: decorated, delegate: delegate, client: client) from.present(viewController, animated: true) return viewController } @discardableResult -package func present(checkout url: URL, from: UIViewController, entryPoint: MetaData.EntryPoint, client: (any CheckoutCommunicationProtocol)? = nil) -> CheckoutViewController { +package func present(checkout url: URL, from: UIViewController, entryPoint: MetaData.EntryPoint, delegate: (any CheckoutDelegate)? = nil, client: (any CheckoutCommunicationProtocol)? = nil) -> CheckoutViewController { let decorated = CheckoutProtocol.url(for: url, colorScheme: configuration.colorScheme.rawValue) - let viewController = CheckoutViewController(checkout: decorated, client: client, entryPoint: entryPoint) + let viewController = CheckoutViewController(checkout: decorated, delegate: delegate, client: client, entryPoint: entryPoint) from.present(viewController, animated: true) return viewController } diff --git a/platforms/swift/Tests/ShopifyCheckoutKitTests/CheckoutWebViewControllerTests.swift b/platforms/swift/Tests/ShopifyCheckoutKitTests/CheckoutWebViewControllerTests.swift index 2e2d0dcd..54d3641b 100644 --- a/platforms/swift/Tests/ShopifyCheckoutKitTests/CheckoutWebViewControllerTests.swift +++ b/platforms/swift/Tests/ShopifyCheckoutKitTests/CheckoutWebViewControllerTests.swift @@ -144,6 +144,43 @@ class CheckoutWebViewControllerTests: XCTestCase { XCTAssertTrue(viewController.dismissAnimated) } + func test_checkoutViewDidFailWithError_invokesDelegate() { + let delegate = MockCheckoutDelegate() + let viewController = TestableCheckoutWebViewController(checkoutURL: url, delegate: delegate, entryPoint: nil) + + viewController.checkoutViewDidFailWithError(error: nonRecoverableError) + + XCTAssertEqual(delegate.didFailErrors.count, 1) + } + + func test_checkoutViewDidFailWithError_doesNotInvokeDelegateWhileRecovering() { + let delegate = MockCheckoutDelegate() + var onFailCount = 0 + let viewController = TestableCheckoutWebViewController(checkoutURL: url, delegate: delegate, entryPoint: nil) + viewController.onFail = { _ in onFailCount += 1 } + + viewController.checkoutViewDidFailWithError(error: recoverableError) + + XCTAssertTrue(viewController.presentFallbackViewControllerCalled) + XCTAssertEqual(delegate.didFailErrors.count, 0) + XCTAssertEqual(onFailCount, 0) + + viewController.checkoutViewDidFailWithError(error: recoverableError) + + XCTAssertTrue(viewController.dismissCalled) + XCTAssertEqual(delegate.didFailErrors.count, 1) + XCTAssertEqual(onFailCount, 1) + } + + func test_presentationControllerDidDismiss_invokesDelegateCancel() { + let delegate = MockCheckoutDelegate() + let viewController = TestableCheckoutWebViewController(checkoutURL: url, delegate: delegate, entryPoint: nil) + + viewController.presentationControllerDidDismiss(UIPresentationController(presentedViewController: viewController, presenting: nil)) + + XCTAssertEqual(delegate.didCancelCount, 1) + } + func test_checkoutViewDidFailWithError_respectsErrorRecoverableProperty() { struct TestCase { let name: String diff --git a/platforms/swift/Tests/ShopifyCheckoutKitTests/Mocks/MockCheckoutDelegate.swift b/platforms/swift/Tests/ShopifyCheckoutKitTests/Mocks/MockCheckoutDelegate.swift index cecc5fd9..31774b88 100644 --- a/platforms/swift/Tests/ShopifyCheckoutKitTests/Mocks/MockCheckoutDelegate.swift +++ b/platforms/swift/Tests/ShopifyCheckoutKitTests/Mocks/MockCheckoutDelegate.swift @@ -32,3 +32,16 @@ struct MockBridgeClient: CheckoutCommunicationProtocol { return responseMessage } } + +final class MockCheckoutDelegate: CheckoutDelegate { + private(set) var didCancelCount = 0 + private(set) var didFailErrors: [CheckoutError] = [] + + func checkoutDidCancel() { + didCancelCount += 1 + } + + func checkoutDidFail(error: CheckoutError) { + didFailErrors.append(error) + } +} diff --git a/platforms/swift/Tests/ShopifyCheckoutKitTests/ShopifyCheckoutKitTests.swift b/platforms/swift/Tests/ShopifyCheckoutKitTests/ShopifyCheckoutKitTests.swift index 004261e7..cd1f3560 100644 --- a/platforms/swift/Tests/ShopifyCheckoutKitTests/ShopifyCheckoutKitTests.swift +++ b/platforms/swift/Tests/ShopifyCheckoutKitTests/ShopifyCheckoutKitTests.swift @@ -63,6 +63,26 @@ class ShopifyCheckoutKitTests: XCTestCase { ) } + func test_present_propagatesDelegateAndClientToWebViewController() throws { + let delegate = MockCheckoutDelegate() + let client = MockBridgeClient() + let presenter = UIViewController() + let checkoutURL = try XCTUnwrap(URL(string: "https://shop.example/checkouts/cn/123")) + + let viewController = ShopifyCheckoutKit.present( + checkout: checkoutURL, + from: presenter, + delegate: delegate, + client: client + ) + + let webViewController = try XCTUnwrap( + viewController.viewControllers.compactMap { $0 as? CheckoutWebViewController }.first + ) + XCTAssertTrue(webViewController.delegate === delegate) + XCTAssertNotNil(webViewController.client) + } + func test_logger_withDifferentLogLevels_shouldHaveCorrectLogLevel() { ShopifyCheckoutKit.configuration.logLevel = .all XCTAssertEqual(