-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathCardClient.swift
More file actions
268 lines (239 loc) · 13.1 KB
/
CardClient.swift
File metadata and controls
268 lines (239 loc) · 13.1 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
import Foundation
import AuthenticationServices
#if canImport(CorePayments)
import CorePayments
#endif
public class CardClient: NSObject {
private let checkoutOrdersAPI: CheckoutOrdersAPI
private let vaultAPI: VaultPaymentTokensAPI
private let config: CoreConfig
private let webAuthenticationSession: WebAuthenticationSession
private var analyticsService: AnalyticsService?
/// Initialize a CardClient to process card payment
/// - Parameter config: The CoreConfig object
public init(config: CoreConfig) {
self.config = config
self.checkoutOrdersAPI = CheckoutOrdersAPI(coreConfig: config)
self.vaultAPI = VaultPaymentTokensAPI(coreConfig: config)
self.webAuthenticationSession = WebAuthenticationSession()
}
/// For internal use for testing/mocking purpose
init(
config: CoreConfig,
checkoutOrdersAPI: CheckoutOrdersAPI,
vaultAPI: VaultPaymentTokensAPI,
webAuthenticationSession: WebAuthenticationSession
) {
self.config = config
self.checkoutOrdersAPI = checkoutOrdersAPI
self.vaultAPI = vaultAPI
self.webAuthenticationSession = webAuthenticationSession
}
/// Updates a setup token with a payment method. Performs
/// 3DS verification if required. If verification is performed, SDK returns a property `didAttemptThreeDSecureAuthentication`.
/// If `didAttempt3DSecureVerification` is `true`, check verification status with `/v3/vault/setup-token/{id}` in your server.
/// - Parameters:
/// - vaultRequest: The request containing setupTokenID and card
/// - completion: A completion block that is invoked when the request is completed. If the request succeeds,
/// a `CardVaultResult` with `setupTokenID` and `status` are returned and `error` will be `nil`;
/// if it fails, `CardVaultResult will be `nil` and `error` will describe the failure
public func vault(_ vaultRequest: CardVaultRequest, completion: @escaping (CardVaultResult?, Error?) -> Void) {
analyticsService = AnalyticsService(coreConfig: config, setupToken: vaultRequest.setupTokenID)
analyticsService?.sendEvent("card-payments:vault-wo-purchase:started")
Task {
do {
let result = try await vaultAPI.updateSetupToken(cardVaultRequest: vaultRequest).updateVaultSetupToken
if result.status == "PAYER_ACTION_REQUIRED",
let urlString = result.links.first(where: { $0.rel == "approve" })?.href {
guard urlString.contains("helios"), let url = URL(string: urlString) else {
self.notifyVaultFailure(with: CardClientError.threeDSecureURLError, completion: completion)
return
}
analyticsService?.sendEvent("card-payments:vault-wo-purchase:challenge-required")
startVaultThreeDSecureChallenge(url: url, setupTokenID: vaultRequest.setupTokenID, completion: completion)
} else {
let vaultResult = CardVaultResult(setupTokenID: result.id, status: result.status, didAttemptThreeDSecureAuthentication: false)
notifyVaultSuccess(for: vaultResult, completion: completion)
}
} catch let error as CoreSDKError {
notifyVaultFailure(with: error, completion: completion)
} catch {
notifyVaultFailure(with: CardClientError.vaultTokenError, completion: completion)
}
}
}
/// Updates a setup token with a payment method. Performs
/// 3DS verification if required. If verification is performed, SDK returns a property `didAttemptThreeDSecureAuthentication`.
/// If `didAttempt3DSecureVerification` is `true`, check verification status with `/v3/vault/setup-token/{id}` in your server.
/// - Parameters:
/// - vaultRequest: The request containing setupTokenID and card
/// - Returns: `CardVaultResult` if successful
/// - Throws: An `Error` describing failure
public func vault(_ vaultRequest: CardVaultRequest) async throws -> CardVaultResult {
try await withCheckedThrowingContinuation { continuation in
vault(vaultRequest) { result, error in
if let error {
continuation.resume(throwing: error)
} else if let result {
continuation.resume(returning: result)
}
}
}
}
/// Approve an order with a card, which validates buyer's card, and if valid, attaches the card as the payment source to the order.
/// After the order has been successfully approved, you will need to handle capturing/authorizing the order in your server.
/// - Parameters:
/// - orderId: Order id for approval
/// - request: The request containing the card
/// - completion: A completion block that is invoked when the request is completed. If the request succeeds,
/// a `CardResult` with `orderID` , `status` and `didAttemptThreeDSecureAuthentication` are returned and `error` will be `nil`;
/// if it fails, `CardResult will be `nil` and `error` will describe the failure
public func approveOrder(request: CardRequest, completion: @escaping (CardResult?, Error?) -> Void) {
analyticsService = AnalyticsService(coreConfig: config, orderID: request.orderID)
analyticsService?.sendEvent("card-payments:3ds:started")
Task {
do {
let result = try await checkoutOrdersAPI.confirmPaymentSource(cardRequest: request)
if result.status == "PAYER_ACTION_REQUIRED",
let url = result.links?.first(where: { $0.rel == "payer-action" })?.href {
guard getQueryStringParameter(url: url, param: "flow") == "3ds",
url.contains("helios"),
let url = URL(string: url) else {
self.notifyCheckoutFailure(with: CardClientError.threeDSecureURLError, completion: completion)
return
}
analyticsService?.sendEvent("card-payments:3ds:confirm-payment-source:challenge-required")
startThreeDSecureChallenge(url: url, orderId: result.id, completion: completion)
} else {
analyticsService?.sendEvent("card-payments:3ds:confirm-payment-source:succeeded")
let cardResult = CardResult(orderID: result.id, status: result.status, didAttemptThreeDSecureAuthentication: false)
notifyCheckoutSuccess(for: cardResult, completion: completion)
}
} catch let error as CoreSDKError {
analyticsService?.sendEvent("card-payments:3ds:confirm-payment-source:failed")
notifyCheckoutFailure(with: error, completion: completion)
} catch {
analyticsService?.sendEvent("card-payments:3ds:confirm-payment-source:failed")
notifyCheckoutFailure(with: CardClientError.unknownError, completion: completion)
}
}
}
/// Approve an order with a card, which validates buyer's card, and if valid, attaches the card as the payment source to the order.
/// After the order has been successfully approved, you will need to handle capturing/authorizing the order in your server.
/// - Parameters:
/// - orderId: Order id for approval
/// - request: The request containing the card
/// - Returns: `CardResult` if successful
/// - Throws: An `Error` describing failure
public func approveOrder(request: CardRequest) async throws -> CardResult {
try await withCheckedThrowingContinuation { continuation in
approveOrder(request: request) { result, error in
if let error {
continuation.resume(throwing: error)
} else if let result {
continuation.resume(returning: result)
}
}
}
}
private func startThreeDSecureChallenge(
url: URL,
orderId: String,
completion: @escaping (CardResult?, Error?) -> Void
) {
webAuthenticationSession.start(
url: url,
context: self,
sessionDidDisplay: { [weak self] didDisplay in
if didDisplay {
self?.analyticsService?.sendEvent("card-payments:3ds:challenge-presentation:succeeded")
} else {
self?.analyticsService?.sendEvent("card-payments:3ds:challenge-presentation:failed")
}
},
sessionDidComplete: { _, error in
if let error = error {
switch error {
case ASWebAuthenticationSessionError.canceledLogin:
self.notifyCheckoutCancelWithError(with: CardClientError.threeDSecureCanceled, completion: completion)
return
default:
self.notifyCheckoutFailure(with: CardClientError.threeDSecureError(error), completion: completion)
return
}
}
let cardResult = CardResult(orderID: orderId, status: nil, didAttemptThreeDSecureAuthentication: true)
self.notifyCheckoutSuccess(for: cardResult, completion: completion)
}
)
}
private func getQueryStringParameter(url: String, param: String) -> String? {
guard let url = URLComponents(string: url) else { return nil }
return url.queryItems?.first { $0.name == param }?.value
}
private func startVaultThreeDSecureChallenge(url: URL, setupTokenID: String, completion: @escaping (CardVaultResult?, Error?) -> Void) {
webAuthenticationSession.start(
url: url,
context: self,
sessionDidDisplay: { [weak self] didDisplay in
if didDisplay {
// TODO: analytics for card vault
self?.analyticsService?.sendEvent("card-payments:3ds:challenge-presentation:succeeded")
} else {
self?.analyticsService?.sendEvent("card-payments:3ds:challenge-presentation:failed")
}
},
sessionDidComplete: { _, error in
if let error = error {
switch error {
case ASWebAuthenticationSessionError.canceledLogin:
self.notifyVaultCancelWithError(with: CardClientError.threeDSecureCanceled, completion: completion)
return
default:
self.notifyVaultFailure(with: CardClientError.threeDSecureError(error), completion: completion)
return
}
}
let cardVaultResult = CardVaultResult(setupTokenID: setupTokenID, status: nil, didAttemptThreeDSecureAuthentication: true)
self.notifyVaultSuccess(for: cardVaultResult, completion: completion)
}
)
}
private func notifyCheckoutSuccess(for result: CardResult, completion: (CardResult?, Error?) -> Void) {
analyticsService?.sendEvent("card-payments:3ds:succeeded")
completion(result, nil)
}
private func notifyCheckoutFailure(with error: CoreSDKError, completion: (CardResult?, Error?) -> Void) {
analyticsService?.sendEvent("card-payments:3ds:failed")
completion(nil, error)
}
private func notifyCheckoutCancelWithError(with error: CoreSDKError, completion: (CardResult?, Error?) -> Void) {
analyticsService?.sendEvent("card-payments:3ds:challenge:user-canceled")
completion(nil, error)
}
private func notifyVaultSuccess(for vaultResult: CardVaultResult, completion: (CardVaultResult?, Error?) -> Void) {
analyticsService?.sendEvent("card-payments:vault-wo-purchase:succeeded")
completion(vaultResult, nil)
}
private func notifyVaultFailure(with vaultError: CoreSDKError, completion: (CardVaultResult?, Error?) -> Void) {
analyticsService?.sendEvent("card-payments:vault-wo-purchase:failed")
completion(nil, vaultError)
}
private func notifyVaultCancelWithError(with vaultError: CoreSDKError, completion: (CardVaultResult?, Error?) -> Void) {
analyticsService?.sendEvent("card-payments:vault-wo-purchase:challenge:canceled")
completion(nil, vaultError)
}
}
// MARK: - ASWebAuthenticationPresentationContextProviding conformance
extension CardClient: ASWebAuthenticationPresentationContextProviding {
public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
if #available(iOS 15, *) {
let firstScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
let window = firstScene?.windows.first { $0.isKeyWindow }
return window ?? ASPresentationAnchor()
} else {
let window = UIApplication.shared.windows.first { $0.isKeyWindow }
return window ?? ASPresentationAnchor()
}
}
}