Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 16 additions & 53 deletions platforms/swift/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
}
}
Expand Down Expand Up @@ -373,51 +365,36 @@ 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.
}

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:
Expand All @@ -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`

Expand Down Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
@@ -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)
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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\","
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think with ready we wrapped it up in the protocol lib - seems like this json could be moved over there

+ "\"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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -182,6 +184,7 @@ class CheckoutWebViewController: UIViewController, UIAdaptivePresentationControl
}

onCancel?()
delegate?.checkoutDidCancel()
}

package func presentFallbackViewController(url: URL) {
Expand All @@ -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)
Expand Down Expand Up @@ -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)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading