Repository navigation
Expand file tree
/
Copy pathCartViewController.swift
More file actions
66 lines (57 loc) · 1.85 KB
/
Copy pathCartViewController.swift
File metadata and controls
66 lines (57 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// [START complete-tutorial.present-checkout]
// [START integrate.present-checkout]
// [START integrate.install]
import UIKit
import ShopifyCheckoutSheetKit
// [END integrate.install]
class CartViewController: UIViewController {
private var checkoutUrl: URL?
private let storefrontClient = StorefrontClient(
shopDomain: "{shop}.myshopify.com",
accessToken: "your-storefront-access-token"
)
func addToCart(variantId: String) async {
do {
let cart = try await storefrontClient.createCart(variantId: variantId)
checkoutUrl = URL(string: cart.checkoutUrl)
} catch {
print("Failed to create cart: \(error)")
}
}
@IBAction func checkoutTapped(_ sender: UIButton) {
guard let url = checkoutUrl else {
print("No checkout URL available")
return
}
ShopifyCheckoutSheetKit.present(
checkout: url,
from: self,
delegate: self
)
}
}
extension CartViewController: CheckoutDelegate {
func checkoutDidComplete(event: CheckoutCompletedEvent) {
let orderId = event.orderDetails.id
print("Order completed: \(orderId)")
checkoutUrl = nil
}
func checkoutDidCancel() {
print("Checkout canceled")
}
func checkoutDidFail(error: CheckoutError) {
print("Checkout failed: \(error.localizedDescription)")
let alert = UIAlertController(
title: "Checkout Error",
message: error.localizedDescription,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default))
present(alert, animated: true)
}
func checkoutDidClickLink(url: URL) {
UIApplication.shared.open(url)
}
}
// [END integrate.present-checkout]
// [END complete-tutorial.present-checkout]