-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathShopifyCheckoutKit.swift
More file actions
389 lines (331 loc) · 14.5 KB
/
Copy pathShopifyCheckoutKit.swift
File metadata and controls
389 lines (331 loc) · 14.5 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import Foundation
import PassKit
import React
import ShopifyCheckoutKit
import SwiftUI
import UIKit
/// Canonical list of SDK lifecycle event types emitted by the
/// per-`present()` dispatcher.
///
/// Mirrors `SDK_LIFECYCLE_EVENT_TYPES` in the JS package and
/// `DispatchEventTypes` on Android. Exposed to JS via
/// `constantsToExport()` so the JS layer can verify the two sides
/// agree at construction time.
enum DispatchEventType: String, CaseIterable {
case close
case fail
case geolocationRequest
}
@objc(RCTShopifyCheckoutKit)
class RCTShopifyCheckoutKit: NSObject {
internal var checkoutSheet: UIViewController?
private var acceleratedCheckoutsConfiguration: Any?
private var acceleratedCheckoutsApplePayConfiguration: Any?
private var defaultLogLevel: LogLevel = .error
@objc var methodQueue: DispatchQueue {
return DispatchQueue.main
}
@objc static func requiresMainQueueSetup() -> Bool {
return true
}
override init() {
configure {
$0.platform = Platform.reactNative
}
super.init()
}
@objc func constantsToExport() -> [AnyHashable: Any]! {
return [
"version": ShopifyCheckoutKit.version,
// Surfaced so the JS layer can verify the SDK lifecycle event set
// it was built against matches what this native module emits.
"dispatchEventTypes": DispatchEventType.allCases.map { $0.rawValue }
]
}
@objc func getConstants() -> [AnyHashable: Any]! {
return constantsToExport()
}
static func getRootViewController() -> UIViewController? {
return (
UIApplication.shared.connectedScenes
.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene
)?.windows
.first(where: { $0.isKeyWindow })?.rootViewController
}
func getCurrentViewController(_ controller: UIViewController? = getRootViewController()) -> UIViewController? {
if let presentedViewController = controller?.presentedViewController {
return getCurrentViewController(presentedViewController)
}
if let navigationController = controller as? UINavigationController {
return getCurrentViewController(navigationController.visibleViewController)
}
if let tabBarController = controller as? UITabBarController {
if let selectedViewController = tabBarController.selectedViewController {
return getCurrentViewController(selectedViewController)
}
}
return controller
}
@objc func dismiss() {
DispatchQueue.main.async {
self.checkoutSheet?.dismiss(animated: true)
self.checkoutSheet = nil
}
}
@objc func invalidateCache() {
// Retained for compatibility with the generated native module interface.
}
@objc func present(_ checkoutURL: String, subscribedMethods: [String]) {
DispatchQueue.main.async {
guard let url = URL(string: checkoutURL),
let viewController = self.getCurrentViewController() else { return }
// Protocol relay: forwards UCP messages from native to the JS
// dispatch event stream.
let client = makeRelayClient(
subscribedMethods: subscribedMethods,
dispatch: { [weak self] json in
self?.emitDispatchEvent(json)
}
)
// `delegate: self` wires the SDK lifecycle events (close/fail)
// into the same JS dispatcher; `client:` wires the UCP
// protocol event stream. They are independent inputs feeding
// the same outbound envelope channel.
let view = ShopifyCheckoutKit.present(
checkout: url,
from: viewController,
delegate: self,
client: client
)
self.checkoutSheet = view
}
}
@objc func preload(_: String) {}
private func getColorScheme(_ colorScheme: String) -> Configuration.ColorScheme {
switch colorScheme {
case "web_default":
return Configuration.ColorScheme.web
case "automatic":
return Configuration.ColorScheme.automatic
case "light":
return Configuration.ColorScheme.light
case "dark":
return Configuration.ColorScheme.dark
default:
return Configuration.ColorScheme.automatic
}
}
@objc func setConfig(_ configuration: [AnyHashable: Any]) {
let colorConfig = configuration["colors"] as? [AnyHashable: Any]
let iosConfig = colorConfig?["ios"] as? [String: String]
if let title = configuration["title"] as? String {
ShopifyCheckoutKit.configuration.title = title
}
if let colorScheme = configuration["colorScheme"] as? String {
ShopifyCheckoutKit.configuration.colorScheme = getColorScheme(colorScheme)
}
if let tintColorHex = iosConfig?["tintColor"] as? String {
ShopifyCheckoutKit.configuration.tintColor = UIColor(hex: tintColorHex)
}
if let backgroundColorHex = iosConfig?["backgroundColor"] as? String {
ShopifyCheckoutKit.configuration.backgroundColor = UIColor(hex: backgroundColorHex)
}
if let closeButtonColorHex = iosConfig?["closeButtonColor"] as? String {
ShopifyCheckoutKit.configuration.closeButtonTintColor = UIColor(hex: closeButtonColorHex)
}
if let logLevel = configuration["logLevel"] as? String {
ShopifyCheckoutKit.configuration.logLevel = LogLevel(rawValue: logLevel.lowercased()) ?? defaultLogLevel
} else {
ShopifyCheckoutKit.configuration.logLevel = defaultLogLevel
}
NotificationCenter.default.post(name: Notification.Name("CheckoutKitConfigurationUpdated"), object: nil)
}
@objc func getConfig() -> NSDictionary {
return [
"title": ShopifyCheckoutKit.configuration.title,
"colorScheme": ShopifyCheckoutKit.configuration.colorScheme.rawValue,
"tintColor": ShopifyCheckoutKit.configuration.tintColor,
"backgroundColor": ShopifyCheckoutKit.configuration.backgroundColor,
"closeButtonColor": ShopifyCheckoutKit.configuration.closeButtonTintColor,
"logLevel": logLevelToString(ShopifyCheckoutKit.configuration.logLevel)
]
}
@objc func configureAcceleratedCheckouts(
_ storefrontDomain: String,
storefrontAccessToken: String,
customerEmail: String?,
customerPhoneNumber: String?,
customerAccessToken: String?,
applePayMerchantIdentifier: String?,
applyPayContactFields: [String]?,
supportedShippingCountries: [String]?
) -> NSNumber {
guard #available(iOS 16.0, *) else {
return NSNumber(value: false)
}
let customer = ShopifyAcceleratedCheckouts.Customer(
email: customerEmail,
phoneNumber: customerPhoneNumber,
customerAccessToken: customerAccessToken
)
acceleratedCheckoutsConfiguration = ShopifyAcceleratedCheckouts.Configuration(
storefrontDomain: storefrontDomain,
storefrontAccessToken: storefrontAccessToken,
customer: customer
)
if let merchantIdentifier = applePayMerchantIdentifier, let contactFields = applyPayContactFields {
do {
let fields = try contactFieldsToRequiredContactFields(contactFields)
acceleratedCheckoutsApplePayConfiguration = ShopifyAcceleratedCheckouts.ApplePayConfiguration(
merchantIdentifier: merchantIdentifier,
contactFields: fields,
supportedShippingCountries: Set(supportedShippingCountries ?? [])
)
AcceleratedCheckoutConfiguration.shared.applePayConfiguration = acceleratedCheckoutsApplePayConfiguration as? ShopifyAcceleratedCheckouts.ApplePayConfiguration
} catch {
return NSNumber(value: false)
}
}
AcceleratedCheckoutConfiguration.shared.configuration = acceleratedCheckoutsConfiguration as? ShopifyAcceleratedCheckouts.Configuration
NotificationCenter.default.post(name: Notification.Name("AcceleratedCheckoutConfigurationUpdated"), object: nil)
return NSNumber(value: true)
}
@objc func isAcceleratedCheckoutAvailable() -> NSNumber {
guard #available(iOS 16.0, *) else {
return NSNumber(value: false)
}
return NSNumber(value: AcceleratedCheckoutConfiguration.shared.available)
}
@objc func isApplePayAvailable() -> NSNumber {
guard #available(iOS 16.0, *) else {
return NSNumber(value: false)
}
let available = AcceleratedCheckoutConfiguration.shared.available && AcceleratedCheckoutConfiguration.shared.applePayAvailable
return NSNumber(value: available)
}
@objc func respondToGeolocationRequest(_: Bool) {
// No-op on iOS — geolocation permission is handled natively
}
// MARK: - Private
@available(iOS 16.0, *)
private func contactFieldsToRequiredContactFields(_ contactFields: [String]) throws -> [ShopifyAcceleratedCheckouts.RequiredContactFields] {
return try contactFields.compactMap {
guard let field = ShopifyAcceleratedCheckouts.RequiredContactFields(rawValue: $0), field != nil else {
let message = "Unknown contactField option: \(String(describing: $0))"
print("[ShopifyCheckoutKit] \(message)")
throw NSError(domain: "ShopifyCheckoutKit", code: 1, userInfo: ["message": message])
}
return field
}
}
private func logLevelToString(_ logLevel: LogLevel) -> String {
switch logLevel {
case .all, .debug:
return "debug"
case .error:
return "error"
default:
return "error"
}
}
}
// MARK: - CheckoutDelegate
extension RCTShopifyCheckoutKit: CheckoutDelegate {
/// Fired by the iOS SDK when the buyer dismisses the checkout sheet
/// without a terminal error. Mirrors
/// `CustomCheckoutListener.onCheckoutCanceled()` on Android.
///
/// The iOS SDK dismisses the presented checkout when the buyer taps
/// the close button; this wrapper also clears its local reference so
/// future presentations start from a clean state.
func checkoutDidCancel() {
emitDispatchEnvelope(type: .close, payload: nil)
dismissCheckoutSheet()
}
/// Fired by the iOS SDK when checkout terminates with an error.
/// Mirrors `CustomCheckoutListener.onCheckoutFailed()` on Android.
/// The error is serialised into the JS-side `CheckoutNativeError`
/// shape (`__typename` / `message` / `code` / optional
/// `statusCode`) so it can be coerced into the matching
/// `CheckoutException` subclass on the JS side.
///
/// The sheet is left visible — consumers may want to render a
/// recovery UI on top of the still-presented checkout, or decide to
/// dismiss it explicitly via `ShopifyCheckoutKit.dismiss()` from
/// their `onFail` handler. Mirrors the Android behaviour where
/// `onCheckoutFailed` also does not auto-dismiss the dialog.
func checkoutDidFail(error: CheckoutError) {
emitDispatchEnvelope(type: .fail, payload: Self.errorPayload(from: error))
}
/// Dismisses the currently-presented checkout sheet on the main
/// queue and releases our reference to it. Safe to call when no
/// sheet is presented — `checkoutSheet` will simply be `nil`.
private func dismissCheckoutSheet() {
DispatchQueue.main.async { [weak self] in
self?.checkoutSheet?.dismiss(animated: true)
self?.checkoutSheet = nil
}
}
}
// MARK: - Dispatch envelope helpers
extension RCTShopifyCheckoutKit {
private func emitDispatchEvent(_ json: String) {
perform(NSSelectorFromString("emitOnDispatchFromSwift:"), with: json)
}
/// Builds a `{ "type": ..., "payload": ... }` envelope and forwards
/// it to the JS dispatch event stream.
private func emitDispatchEnvelope(type: DispatchEventType, payload: [String: Any]?) {
var envelope: [String: Any] = ["type": type.rawValue]
if let payload {
envelope["payload"] = payload
}
do {
let data = try JSONSerialization.data(withJSONObject: envelope, options: [])
guard let json = String(data: data, encoding: .utf8) else {
NSLog("[ShopifyCheckoutKit] Failed to encode dispatch envelope for \(type.rawValue): non-UTF8 result")
return
}
emitDispatchEvent(json)
} catch {
NSLog("[ShopifyCheckoutKit] Failed to serialize dispatch envelope for \(type.rawValue): \(error)")
}
}
/// Maps an iOS `CheckoutError` into the JSON-friendly dictionary
/// shape the JS dispatcher expects. Field names match Android's
/// `CustomCheckoutListener.populateErrorDetails` so the JS-side
/// `parseCheckoutError` works identically on both platforms.
fileprivate static func errorPayload(from error: CheckoutError) -> [String: Any] {
switch error {
case let .sdkError(underlying):
return [
"__typename": "InternalError",
"message": underlying.localizedDescription,
"code": CheckoutErrorCode.unknown.rawValue
]
case let .checkoutUnavailable(message, code):
switch code {
case let .clientError(clientCode):
return [
"__typename": "CheckoutClientError",
"message": message,
"code": clientCode.rawValue
]
case let .httpError(statusCode):
return [
"__typename": "CheckoutHTTPError",
"message": message,
// Matches the JS-side `CheckoutErrorCode.httpError`
// string and Android's HttpException code value.
"code": "http_error",
"statusCode": statusCode
]
}
case let .checkoutExpired(message, code):
return [
"__typename": "CheckoutExpiredError",
"message": message,
"code": code.rawValue
]
}
}
}