This repository has been archived by the owner on Dec 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
PaymentAdapter.swift
executable file
·249 lines (202 loc) · 11 KB
/
PaymentAdapter.swift
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
// Copyright © 2019 VenueNext, Inc. All rights reserved.
import Foundation
import os.log
import VenueNextCore
import VenueNextPayment
import VenueNextOrderData
import BraintreeDropIn // Import
import BraintreeApplePay // Import
import BraintreePaymentFlow // Import
@objc class PaymentAdapter: NSObject, PaymentProcessable, PaymentMethodRepresentable {
var cardType: String = ""
var lastFour: String = ""
var instrument: PaymentMethodInstrument = .creditCard
var cardholderName: String? = ""
var nonce: String = ""
private var applePayError: NSError?
private var braintreeApiClient: BTAPIClient?
private var queue = OperationQueue()
func processPayment(from viewController: UIViewController?, productType: ProductType, displayType: PaymentDisplayType, completion: @escaping (PaymentMethodRepresentable?, NSError?) -> Void) {
resetToDefaults()
VNPayment.shared.getPaymentToken() { (result) in
switch result {
case .success(let token):
DispatchQueue.main.async {
let request = BTDropInRequest()
request.paypalDisabled = true
request.vaultManager = true
/*
ApplePay should be enabled only for .checkout
*/
let applePayDisabled = displayType != .checkout
request.applePayDisabled = applePayDisabled
let dropIn = BTDropInController(authorization: token, request: request) { [weak self] (controller, result, error) in
guard let self = self else { return }
defer {
controller.dismiss(animated: true, completion: nil)
}
guard error == nil else {
completion(nil , error as NSError?)
return
}
guard result?.isCancelled == false else {
completion(nil, nil)
return
}
guard let result = result else {
// Use the BTDropInResult properties to update your UI
completion(nil, nil)
return
}
// Handle Payment Types
switch result.paymentOptionType {
case .applePay:
self.applePayError = nil
self.braintreeApiClient = BTAPIClient(authorization: token)
self.queue.isSuspended = true
let blockOp = BlockOperation {
if let error = self.applePayError {
completion(nil, error)
return
}
self.instrument = .applePay
completion(self, nil)
}
self.queue.addOperation(blockOp)
guard let viewController = viewController else {
completion(nil, NSError(source: self, code: 422, userInfo: [NSLocalizedDescriptionKey: "PKPaymentAuthorizationViewController must be launched from a viewcontroller"]))
return
}
DispatchQueue.main.async { [weak self] in
self?.tappedApplePay(from: viewController, productType: productType, completion: completion)
}
default:
self.instrument = .creditCard
guard let nonce = result.paymentMethod?.nonce else {
let error = NSError(source: self, code: 404, userInfo: [NSLocalizedDescriptionKey: "Payment Method did not provide a nonce"])
completion(nil, error)
return
}
self.nonce = nonce
completion(self, nil)
}
}
viewController?.present(dropIn!, animated: true, completion: nil)
}
case .failure(let error):
print(error.error.localizedDescription)
let error = NSError(source: self, code: 404, userInfo: [NSLocalizedDescriptionKey: error.localizedDescription])
completion(nil, error)
}
}
}
func postPaymentMethod(paymentMethod: PaymentMethodRepresentable, completion: @escaping ((NSError?) -> Void)) {
print("postPaymentMethod: not implemented")
completion(nil)
}
func defaultPaymentMethod(completion: @escaping ((PaymentMethodRepresentable?) -> Void)) {
resetToDefaults()
VNPayment.shared.getPaymentToken() { [weak self] (result) in
switch result {
case .success(let token):
guard let btAPIClient = BTAPIClient(authorization: token) else {
completion(nil)
return
}
//Fetch the default payment method
btAPIClient.fetchPaymentMethodNonces(true, completion: { (paymentMethods, error) in
guard let paymentMethod = paymentMethods?.first, paymentMethod.isDefault else {
completion(nil)
return
}
self?.nonce = paymentMethod.nonce
completion(self)
})
case .failure(let error):
print(error.error.localizedDescription)
}
}
}
private func resetToDefaults() {
braintreeApiClient = nil
nonce = ""
applePayError = nil
}
}
extension PaymentAdapter: PKPaymentAuthorizationViewControllerDelegate {
func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
if nonce.isEmpty {
applePayError = NSError(source: self, code: -1, userInfo: [NSLocalizedDescriptionKey : "User canceled ApplePay"])
}
queue.isSuspended = false
controller.presentingViewController?.dismiss(animated: true, completion: nil)
}
func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController,
didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {
guard let braintreeApiClient = braintreeApiClient else {
// Indicate failure via completion callback.
completion(PKPaymentAuthorizationStatus.failure)
return
}
let applePayClient = BTApplePayClient(apiClient: braintreeApiClient)
applePayClient.tokenizeApplePay(payment) { [weak self] tokenizedApplePayPayment, error in
guard let tokenizedApplePayPayment = tokenizedApplePayPayment else {
// Tokenization failed. Check `error` for the cause of the failure.
guard let self = self else { return }
self.applePayError = error as NSError?
// Indicate failure via completion callback.
completion(PKPaymentAuthorizationStatus.failure)
return
}
print("nonce = \(tokenizedApplePayPayment.nonce)")
self?.nonce = tokenizedApplePayPayment.nonce
self?.instrument = .applePay
// Then indicate success or failure via the completion callback, e.g.
completion(PKPaymentAuthorizationStatus.success)
}
}
func setupPaymentRequest(for productType: ProductType, completion: @escaping (PKPaymentRequest?, Error?) -> Void) {
guard let braintreeApiClient = braintreeApiClient else {
let error = NSError(source: self, code: 404, userInfo: [NSLocalizedDescriptionKey: "Could not setup Apple Pay payments because BTAPIClient is nil"])
completion(nil, error)
return
}
let applePayClient = BTApplePayClient(apiClient: braintreeApiClient)
// You can use the following helper method to create a PKPaymentRequest which will set the `countryCode`,
// `currencyCode`, `merchantIdentifier`, and `supportedNetworks` properties.
// You can also create the PKPaymentRequest manually. Be aware that you'll need to keep these in
// sync with the gateway settings if you go this route.
applePayClient.paymentRequest { (paymentRequest, error) in
guard let paymentRequest = paymentRequest else {
completion(nil, error)
return
}
// We recommend collecting billing address information, at minimum
// billing postal code, and passing that billing postal code with all
// Apple Pay transactions as a best practice.
paymentRequest.requiredBillingContactFields = [.postalAddress]
let paymentSummaryItems = VNOrderData.shared.cart.paymentSummaryItems(for: productType)
// Set other PKPaymentRequest properties here
paymentRequest.merchantCapabilities = .capability3DS
paymentRequest.paymentSummaryItems = paymentSummaryItems
completion(paymentRequest, nil)
}
}
func tappedApplePay(from viewController: UIViewController, productType: ProductType, completion: @escaping (PaymentMethodRepresentable?, NSError?) -> Void) {
self.setupPaymentRequest(for: productType) { (paymentRequest, error) in
if let error = error {
completion(nil, error as NSError)
return
}
guard let request = paymentRequest else { return }
// Example: Promote PKPaymentAuthorizationViewController to optional so that we can verify
// that our paymentRequest is valid. Otherwise, an invalid paymentRequest would crash our app.
if let vc = PKPaymentAuthorizationViewController(paymentRequest: request) as PKPaymentAuthorizationViewController? {
vc.delegate = self
viewController.present(vc, animated: true, completion: nil)
} else {
print("Error: Payment request is invalid.")
}
}
}
}