-
Notifications
You must be signed in to change notification settings - Fork 50
/
StripeTerminalReactNative.swift
826 lines (713 loc) · 39.1 KB
/
StripeTerminalReactNative.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
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
import StripeTerminal
import Foundation
enum ReactNativeConstants: String, CaseIterable {
case UPDATE_DISCOVERED_READERS = "didUpdateDiscoveredReaders"
case FINISH_DISCOVERING_READERS = "didFinishDiscoveringReaders"
case REPORT_UNEXPECTED_READER_DISCONNECT = "didReportUnexpectedReaderDisconnect"
case REPORT_AVAILABLE_UPDATE = "didReportAvailableUpdate"
case START_INSTALLING_UPDATE = "didStartInstallingUpdate"
case REPORT_UPDATE_PROGRESS = "didReportReaderSoftwareUpdateProgress"
case FINISH_INSTALLING_UPDATE = "didFinishInstallingUpdate"
case FETCH_TOKEN_PROVIDER = "onFetchTokenProviderListener"
case REQUEST_READER_INPUT = "didRequestReaderInput"
case REQUEST_READER_DISPLAY_MESSAGE = "didRequestReaderDisplayMessage"
case CHANGE_PAYMENT_STATUS = "didChangePaymentStatus"
case CHANGE_CONNECTION_STATUS = "didChangeConnectionStatus"
}
@objc(StripeTerminalReactNative)
class StripeTerminalReactNative: RCTEventEmitter, DiscoveryDelegate, BluetoothReaderDelegate, LocalMobileReaderDelegate, TerminalDelegate {
var discoveredReadersList: [Reader]? = nil
var paymentIntents: [AnyHashable : PaymentIntent] = [:]
var setupIntents: [AnyHashable : SetupIntent] = [:]
override func supportedEvents() -> [String]! {
return ReactNativeConstants.allCases.map {
$0.rawValue
}
}
@objc override func constantsToExport() -> [AnyHashable : Any]! {
return ReactNativeConstants.allCases.reduce(into: [String: String]()) {
$0[String(describing: $1)] = $1.rawValue
}
}
@objc override static func requiresMainQueueSetup() -> Bool {
return false
}
var discoverCancelable: Cancelable? = nil
var collectPaymentMethodCancelable: Cancelable? = nil
var collectRefundPaymentMethodCancelable: Cancelable? = nil
var collectSetupIntentCancelable: Cancelable? = nil
var installUpdateCancelable: Cancelable? = nil
var readReusableCardCancelable: Cancelable? = nil
var loggingToken: String? = nil
func terminal(_ terminal: Terminal, didUpdateDiscoveredReaders readers: [Reader]) {
discoveredReadersList = readers
guard terminal.connectionStatus == .notConnected else { return }
sendEvent(withName: ReactNativeConstants.UPDATE_DISCOVERED_READERS.rawValue, body: ["readers": Mappers.mapFromReaders(readers)])
}
@objc(initialize:resolver:rejecter:)
func initialize(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) -> Void {
var connectedReader: NSDictionary? = nil
TokenProvider.delegate = self
let logLevel = Mappers.mapToLogLevel(params["logLevel"] as? String)
if (Terminal.hasTokenProvider()) {
if let reader = Terminal.shared.connectedReader {
connectedReader = Mappers.mapFromReader(reader)
}
Terminal.shared.logLevel = logLevel
} else {
Terminal.setTokenProvider(TokenProvider.shared)
Terminal.shared.logLevel = logLevel
}
if Terminal.shared.responds(to: NSSelectorFromString("setReactNativeSdkVersion:")) && params["reactNativeVersion"] != nil {
Terminal.shared.performSelector(
inBackground: NSSelectorFromString("setReactNativeSdkVersion:"),
with: params["reactNativeVersion"]
)
}
Terminal.shared.delegate = self
resolve(["reader": connectedReader])
}
@objc(cancelCollectPaymentMethod:rejecter:)
func cancelCollectPaymentMethod(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let cancelable = collectPaymentMethodCancelable else {
resolve(Errors.createError(code: ErrorCode.cancelFailedAlreadyCompleted, message: "collectPaymentMethod could not be canceled because the command has already been canceled or has completed."))
return
}
cancelable.cancel() { error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
}
else {
resolve([:])
}
self.collectPaymentMethodCancelable = nil
}
}
@objc(cancelCollectRefundPaymentMethod:rejecter:)
func cancelCollectRefundPaymentMethod(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let cancelable = collectRefundPaymentMethodCancelable else {
resolve(Errors.createError(code: ErrorCode.cancelFailedAlreadyCompleted, message: "collectRefundPaymentMethod could not be canceled because the command has already been canceled or has completed."))
return
}
cancelable.cancel() { error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
}
else {
resolve([:])
}
self.collectRefundPaymentMethodCancelable = nil
}
}
@objc(cancelCollectSetupIntent:rejecter:)
func cancelCollectSetupIntent(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let cancelable = collectSetupIntentCancelable else {
resolve(Errors.createError(code: ErrorCode.cancelFailedAlreadyCompleted, message: "collectSetupIntent could not be canceled because the command has already been canceled or has completed."))
return
}
cancelable.cancel() { error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
}
else {
resolve([:])
}
self.collectSetupIntentCancelable = nil
}
}
@objc(cancelReadReusableCard:rejecter:)
func cancelReadReusableCard(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let cancelable = readReusableCardCancelable else {
resolve(Errors.createError(code: ErrorCode.cancelFailedAlreadyCompleted, message: "readReusableCard could not be canceled because the command has already been canceled or has completed."))
return
}
cancelable.cancel() { error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
}
else {
resolve([:])
}
self.readReusableCardCancelable = nil
}
}
@objc(simulateReaderUpdate:resolver:rejecter:)
func simulateReaderUpdate(update: String, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) -> Void {
Terminal.shared.simulatorConfiguration.availableReaderUpdate = Mappers.mapToSimulateReaderUpdate(update)
resolve([:])
}
@objc(setSimulatedCard:resolver:rejecter:)
func setSimulatedCard(cardNumber: String, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) -> Void {
Terminal.shared.simulatorConfiguration.simulatedCard = SimulatedCard(testCardNumber: cardNumber)
resolve([:])
}
@objc(setConnectionToken:resolver:rejecter:)
func setConnectionToken(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) -> Void {
let token = params["token"] as? String
let error = params["error"] as? String
TokenProvider.shared.setConnectionToken(token: token, error: error)
resolve([:])
}
@objc(discoverReaders:resolver:rejecter:)
func discoverReaders(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
let simulated = params["simulated"] as? Bool
let discoveryMethod = params["discoveryMethod"] as? String
let config = DiscoveryConfiguration(
discoveryMethod: Mappers.mapToDiscoveryMethod(discoveryMethod),
simulated: simulated ?? false
)
guard discoverCancelable == nil else {
let message = busyMessage(command: "discoverReaders", by: "discoverReaders")
resolve(Errors.createError(code: ErrorCode.busy, message: message))
return
}
self.discoverCancelable = Terminal.shared.discoverReaders(config, delegate: self) { error in
if let error = error as NSError? {
let _error = Errors.createError(nsError: error)
resolve(_error)
self.sendEvent(withName: ReactNativeConstants.FINISH_DISCOVERING_READERS.rawValue, body: ["result": _error])
self.discoverCancelable = nil
} else {
resolve([:])
self.sendEvent(withName: ReactNativeConstants.FINISH_DISCOVERING_READERS.rawValue, body: ["result": ["error": nil]])
self.discoverCancelable = nil
}
}
}
@objc(cancelDiscovering:rejecter:)
func cancelDiscovering(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let cancelable = discoverCancelable else {
resolve(Errors.createError(code: ErrorCode.cancelFailedAlreadyCompleted, message: "discoverReaders could not be canceled because the command has already been canceled or has completed."))
return
}
cancelable.cancel() { error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
self.discoverCancelable = nil
} else {
resolve([:])
self.discoverCancelable = nil
}
}
}
@objc(connectBluetoothReader:resolver:rejecter:)
func connectBluetoothReader(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let reader = params["reader"] as? NSDictionary else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide a reader object"))
return
}
// since simulated readers don't contain `id` property we take serialNumber as a fallback
let readerId = reader["serialNumber"] as? String
guard let selectedReader = discoveredReadersList?.first(where: { $0.serialNumber == readerId }) else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "Could not find reader with id \(readerId ?? "")"))
return
}
let locationId = params["locationId"] as? String
let connectionConfig = BluetoothConnectionConfiguration(
locationId: locationId ?? selectedReader.locationId ?? ""
)
Terminal.shared.connectBluetoothReader(selectedReader, delegate: self, connectionConfig: connectionConfig) { reader, error in
if let reader = reader {
resolve(["reader": Mappers.mapFromReader(reader)])
} else if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else {
resolve([:])
}
}
}
@objc(connectInternetReader:resolver:rejecter:)
func connectInternetReader(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let reader = params["reader"] as? NSDictionary else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide a reader object"))
return
}
// since simulated readers don't contain `id` property we take serialNumber as a fallback
let readerId = reader["serialNumber"] as? String
guard let selectedReader = discoveredReadersList?.first(where: { $0.serialNumber == readerId }) else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "Could not find reader with id \(readerId ?? "")"))
return
}
let connectionConfig = InternetConnectionConfiguration(failIfInUse: params["failIfInUse"] as? Bool ?? false)
Terminal.shared.connectInternetReader(selectedReader, connectionConfig: connectionConfig) { reader, error in
if let reader = reader {
resolve(["reader": Mappers.mapFromReader(reader)])
} else if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
}
}
}
@objc(connectLocalMobileReader:resolver:rejecter:)
func connectLocalMobileReader(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let reader = params["reader"] as? NSDictionary else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide a reader object"))
return
}
// since simulated readers don't contain `id` property we take serialNumber as a fallback
let readerId = reader["serialNumber"] as? String
guard let selectedReader = discoveredReadersList?.first(where: { $0.serialNumber == readerId }) else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "Could not find reader with id \(readerId ?? "")"))
return
}
let locationId = params["locationId"] as? String
let onBehalfOf: String? = params["onBehalfOf"] as? String
let connectionConfig = LocalMobileConnectionConfiguration(
locationId: locationId ?? selectedReader.locationId ?? "",
merchantDisplayName: nil, // use the location name,
onBehalfOf: onBehalfOf ?? nil
)
Terminal.shared.connectLocalMobileReader(selectedReader, delegate: self, connectionConfig: connectionConfig) { reader, error in
if let reader = reader {
resolve(["reader": Mappers.mapFromReader(reader)])
} else if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else {
resolve([:])
}
}
}
@objc(disconnectReader:rejecter:)
func disconnectReader(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
Terminal.shared.disconnectReader() { error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else {
self.paymentIntents = [:]
resolve([:])
}
}
}
func terminal(_ terminal: Terminal, didReportUnexpectedReaderDisconnect reader: Reader) {
let error = Errors.createError(code: ErrorCode.unexpectedSdkError, message: "Reader has been disconnected unexpectedly")
sendEvent(withName: ReactNativeConstants.REPORT_UNEXPECTED_READER_DISCONNECT.rawValue, body: error)
}
@objc(createPaymentIntent:resolver:rejecter:)
func createPaymentIntent(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
let amount = params["amount"] as? NSNumber ?? 0
let currency = params["currency"] as? String ?? ""
let setupFutureUsage = params["setupFutureUsage"] as? String
let paymentMethodTypes = params["paymentMethodTypes"] as? [String] ?? []
let onBehalfOf = params["onBehalfOf"] as? String
let transferDataDestination = params["transferDataDestination"] as? String
let applicationFeeAmount = params["applicationFeeAmount"] as? NSNumber
let stripeDescription = params["stripeDescription"] as? String
let statementDescriptor = params["statementDescriptor"] as? String
let receiptEmail = params["receiptEmail"] as? String
let customer = params["customer"] as? String
let transferGroup = params["transferGroup"] as? String
let metadata = params["metadata"] as? [String : String]
let paymentMethodOptions = params["paymentMethodOptions"] as? [AnyHashable : Any] ?? [:]
let extendedAuth = paymentMethodOptions["requestExtendedAuthorization"] as? Bool ?? false
let incrementalAuth = paymentMethodOptions["requestIncrementalAuthorizationSupport"] as? Bool ?? false
let requestedPriority = paymentMethodOptions["requestedPriority"] as? String
let captureMethod = params["captureMethod"] as? String
let paymentIntentParams = PaymentIntentParameters(
amount: UInt(truncating: amount),
currency: currency,
paymentMethodTypes: paymentMethodTypes,
captureMethod: captureMethod == "automatic" ? .automatic : .manual
)
paymentIntentParams.setupFutureUsage = setupFutureUsage
paymentIntentParams.onBehalfOf = onBehalfOf
paymentIntentParams.transferDataDestination = transferDataDestination
paymentIntentParams.applicationFeeAmount = applicationFeeAmount
paymentIntentParams.stripeDescription = stripeDescription
paymentIntentParams.statementDescriptor = statementDescriptor
paymentIntentParams.receiptEmail = receiptEmail
paymentIntentParams.customer = customer
paymentIntentParams.transferGroup = transferGroup
paymentIntentParams.metadata = metadata
var cardPresentParams = CardPresentParameters(requestExtendedAuthorization: extendedAuth, requestIncrementalAuthorizationSupport: incrementalAuth)
switch requestedPriority {
case "domestic":
cardPresentParams.requestedPriority = CardPresentRouting.domestic.rawValue as NSNumber
case "international":
cardPresentParams.requestedPriority = CardPresentRouting.international.rawValue as NSNumber
default:
break
}
paymentIntentParams.paymentMethodOptionsParameters = PaymentMethodOptionsParameters(cardPresentParameters: cardPresentParams)
Terminal.shared.createPaymentIntent(paymentIntentParams) { pi, error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else if let pi = pi {
let paymentIntent = Mappers.mapFromPaymentIntent(pi)
self.paymentIntents[pi.stripeId] = pi
resolve(["paymentIntent": paymentIntent])
}
}
}
@objc(createSetupIntent:resolver:rejecter:)
func createSetupIntent(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
let setupIntentParams = SetupIntentParameters(customer: params["customerId"] as? String)
Terminal.shared.createSetupIntent(setupIntentParams) { si, error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else if let si = si {
let setupIntent = Mappers.mapFromSetupIntent(si)
self.setupIntents[si.stripeId] = si
resolve(["setupIntent": setupIntent])
}
}
}
@objc(collectPaymentMethod:resolver:rejecter:)
func collectPaymentMethod(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let id = params["paymentIntentId"] as? String else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide paymentIntentId."))
return
}
guard let paymentIntent = paymentIntents[id] else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "There is no associated paymentIntent with id \(id)"))
return
}
let skipTipping = params["skipTipping"] as? Bool ?? false
let updatePaymentIntent = params["updatePaymentIntent"] as? Bool ?? false
let collectConfig = CollectConfiguration(skipTipping: skipTipping, updatePaymentIntent: updatePaymentIntent)
if let eligibleAmount = params["tipEligibleAmount"] as? Int {
let tippingConfig = TippingConfiguration(eligibleAmount: eligibleAmount)
collectConfig.tippingConfiguration = tippingConfig
}
self.collectPaymentMethodCancelable = Terminal.shared.collectPaymentMethod(
paymentIntent,
collectConfig: collectConfig
) { pi, collectError in
if let error = collectError as NSError? {
resolve(Errors.createError(nsError: error))
} else if let paymentIntent = pi {
let paymentIntent = Mappers.mapFromPaymentIntent(paymentIntent)
resolve(["paymentIntent": paymentIntent])
}
self.collectPaymentMethodCancelable = nil
}
}
@objc(retrievePaymentIntent:resolver:rejecter:)
func retrievePaymentIntent(secret: String?, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let clientSecret = secret else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide cliectSecret."))
return
}
Terminal.shared.retrievePaymentIntent(clientSecret: clientSecret) { pi, error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else if let pi = pi {
let paymentIntent = Mappers.mapFromPaymentIntent(pi)
self.paymentIntents[pi.stripeId] = pi
resolve(["paymentIntent": paymentIntent])
}
}
}
@objc(getLocations:resolver:rejecter:)
func getLocations(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
let limit = params["limit"] as? NSNumber
let endingBefore = params["endingBefore"] as? String
let startingAfter = params["startingAfter"] as? String
let listParameters = ListLocationsParameters(limit: limit, endingBefore: endingBefore, startingAfter: startingAfter)
Terminal.shared.listLocations(parameters: listParameters) { locations, hasMore, error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else if let locations = locations {
let list = Mappers.mapFromLocationsList(locations)
resolve(["locations": list, "hasMore": hasMore])
}
}
}
@objc(processPayment:resolver:rejecter:)
func processPayment(paymentIntentId: String?, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let id = paymentIntentId else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide paymentIntentId."))
return
}
guard let paymentIntent = paymentIntents[id] else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "There is no associated paymentIntent with id \(id)"))
return
}
Terminal.shared.processPayment(paymentIntent) { pi, error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else if let pi = pi {
let paymentIntent = Mappers.mapFromPaymentIntent(pi)
self.paymentIntents = [:]
resolve(["paymentIntent": paymentIntent])
}
}
}
func terminal(_ terminal: Terminal, didChangePaymentStatus status: PaymentStatus) {
let result = Mappers.mapFromPaymentStatus(status)
sendEvent(withName: ReactNativeConstants.CHANGE_PAYMENT_STATUS.rawValue, body: ["result": result])
}
func terminal(_ terminal: Terminal, didChangeConnectionStatus status: ConnectionStatus) {
let result = Mappers.mapFromConnectionStatus(status)
sendEvent(withName: ReactNativeConstants.CHANGE_CONNECTION_STATUS.rawValue, body: ["result": result])
}
@objc(cancelPaymentIntent:resolver:rejecter:)
func cancelPaymentIntent(paymentIntentId: String?, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let id = paymentIntentId else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide paymentIntentId."))
return
}
guard let paymentIntent = paymentIntents[id] else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "There is no associated paymentIntent with id \(id)"))
return
}
Terminal.shared.cancelPaymentIntent(paymentIntent) { pi, collectError in
if let error = collectError as NSError? {
resolve(Errors.createError(nsError: error))
} else if let pi = pi {
let paymentIntent = Mappers.mapFromPaymentIntent(pi)
self.paymentIntents[pi.stripeId] = nil
resolve(["paymentIntent": paymentIntent])
}
}
}
@objc(installAvailableUpdate:rejecter:)
func installAvailableUpdate(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
Terminal.shared.installAvailableUpdate()
resolve([:])
}
@objc(cancelInstallingUpdate:rejecter:)
func cancelInstallingUpdate(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
self.installUpdateCancelable?.cancel() { error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else {
resolve([:])
}
}
}
@objc(setReaderDisplay:resolver:rejecter:)
func setReaderDisplay(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
let invalidParams = Errors.validateRequiredParameters(params: params, requiredParams: ["currency", "tax", "total"])
guard invalidParams == nil else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide \(invalidParams!) parameters."))
return
}
let currency = params["currency"] as? String
let tax = params["tax"] as? NSNumber
let total = params["total"] as? NSNumber
let cart = Cart(currency: currency!, tax: Int(truncating: tax!), total: Int(truncating: total!))
let cartLineItems = Mappers.mapToCartLineItems(params["lineItems"] as? NSArray ?? NSArray())
guard let lineItems = (cartLineItems as NSArray).mutableCopy() as? NSMutableArray else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "Unknown error occured."))
return
}
cart.lineItems = lineItems
Terminal.shared.setReaderDisplay(cart) { error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else {
resolve([:])
}
}
}
@objc(cancelSetupIntent:resolver:rejecter:)
func cancelSetupIntent(setupIntentId: String?, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let id = setupIntentId else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide setupIntentId."))
return
}
guard let setupIntent = setupIntents[id] else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "There is no associated setupIntentId with id \(id)"))
return
}
Terminal.shared.cancelSetupIntent(setupIntent) { si, collectError in
if let error = collectError as NSError? {
resolve(Errors.createError(nsError: error))
} else if let si = si {
let setupIntent = Mappers.mapFromSetupIntent(si)
self.setupIntents[si.stripeId] = nil
resolve(["setupIntent": setupIntent])
}
}
}
@objc(clearReaderDisplay:rejecter:)
func clearReaderDisplay(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
Terminal.shared.clearReaderDisplay() { error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else {
resolve([:])
}
}
}
@objc(retrieveSetupIntent:resolver:rejecter:)
func retrieveSetupIntent(secret: String?, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let clientSecret = secret else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide cliectSecret."))
return
}
Terminal.shared.retrieveSetupIntent(clientSecret: clientSecret) { si, error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else if let si = si {
self.setupIntents[si.stripeId] = si
let si = Mappers.mapFromSetupIntent(si)
resolve(["setupIntent": si])
}
}
}
@objc(collectSetupIntentPaymentMethod:resolver:rejecter:)
func collectSetupIntentPaymentMethod(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
let setupIntentId = params["setupIntentId"] as? String
guard let id = setupIntentId else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide setupIntentId."))
return
}
guard let setupIntent = setupIntents[id] else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "There is no created setupIntent with id \(id)"))
return
}
let customerConsentCollected = params["customerConsentCollected"] as? Bool ?? false
self.collectSetupIntentCancelable = Terminal.shared.collectSetupIntentPaymentMethod(setupIntent, customerConsentCollected: customerConsentCollected) { si, collectError in
if let error = collectError as NSError? {
resolve(Errors.createError(nsError: error))
} else if let setupIntent = si {
let setupIntent = Mappers.mapFromSetupIntent(setupIntent)
resolve(["setupIntent": setupIntent])
}
self.collectSetupIntentCancelable = nil
}
}
@objc(confirmSetupIntent:resolver:rejecter:)
func confirmSetupIntent(setupIntentId: String?, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
guard let id = setupIntentId else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide setupIntentId."))
return
}
guard let setupIntent = setupIntents[id] else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "There is no created setupIntent with id \(id)"))
return
}
Terminal.shared.confirmSetupIntent(setupIntent) { si, collectError in
if let error = collectError as NSError? {
resolve(Errors.createError(nsError: error))
} else if let setupIntent = si {
let setupIntent = Mappers.mapFromSetupIntent(setupIntent)
resolve(["setupIntent": setupIntent])
}
}
}
@objc(collectRefundPaymentMethod:resolver:rejecter:)
func collectRefundPaymentMethod(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
let invalidParams = Errors.validateRequiredParameters(params: params, requiredParams: ["chargeId", "amount", "currency"])
guard invalidParams == nil else {
resolve(Errors.createError(code: CommonErrorType.InvalidRequiredParameter, message: "You must provide \(invalidParams!) parameters."))
return
}
let chargeId = params["chargeId"] as? String
let amount = params["amount"] as? NSNumber
let currency = params["currency"] as? String
let intAmount = UInt(truncating: amount!);
let refundApplicationFee = params["refundApplicationFee"] as? NSNumber
let reverseTransfer = params["reverseTransfer"] as? NSNumber
let refundParams = RefundParameters(chargeId: chargeId!, amount: intAmount, currency: currency!)
refundParams.refundApplicationFee = refundApplicationFee
refundParams.reverseTransfer = reverseTransfer
self.collectRefundPaymentMethodCancelable = Terminal.shared.collectRefundPaymentMethod(refundParams) { error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else {
resolve([:])
}
self.collectRefundPaymentMethodCancelable = nil
}
}
@objc(processRefund:rejecter:)
func processRefund(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
Terminal.shared.processRefund() { rf, error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else {
let refund = Mappers.mapFromRefund(rf!)
resolve(["refund": refund])
}
}
}
@objc(readReusableCard:resolver:rejecter:)
func readReusableCard(params: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
let readReusableCardParams = ReadReusableCardParameters();
if let customerId = params["customer"] as? String {
readReusableCardParams.customer = customerId
}
readReusableCardCancelable = Terminal.shared.readReusableCard(readReusableCardParams) { pm, error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else {
let pm = Mappers.mapFromPaymentMethod(pm!)
resolve(["paymentMethod": pm])
}
}
}
@objc(clearCachedCredentials:rejecter:)
func clearCachedCredentials(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
Terminal.shared.clearCachedCredentials()
self.paymentIntents = [:]
resolve([:])
}
@objc(getLoggingToken:rejecter:)
func getLoggingToken(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
resolve(["token": self.loggingToken])
}
func reader(_ reader: Reader, didReportAvailableUpdate update: ReaderSoftwareUpdate) {
sendEvent(withName: ReactNativeConstants.REPORT_AVAILABLE_UPDATE.rawValue, body: ["result": Mappers.mapFromReaderSoftwareUpdate(update) ?? [:]])
}
func reader(_ reader: Reader, didStartInstallingUpdate update: ReaderSoftwareUpdate, cancelable: Cancelable?) {
self.installUpdateCancelable = cancelable
sendEvent(withName: ReactNativeConstants.START_INSTALLING_UPDATE.rawValue, body: ["result": Mappers.mapFromReaderSoftwareUpdate(update) ?? [:]])
}
func reader(_ reader: Reader, didReportReaderSoftwareUpdateProgress progress: Float) {
let result: [AnyHashable : Any?] = [
"progress": String(progress),
]
sendEvent(withName: ReactNativeConstants.REPORT_UPDATE_PROGRESS.rawValue, body: ["result": result])
}
func reader(_ reader: Reader, didFinishInstallingUpdate update: ReaderSoftwareUpdate?, error: Error?) {
var result = Mappers.mapFromReaderSoftwareUpdate(update) ?? [:]
if let nsError = error as NSError? {
let errorAsDictionary = Errors.createError(nsError: nsError)
// createError will return a dictionary of ["error": {the error}]
// so merge that with the result so we have a single result.error
result = result.merging(errorAsDictionary, uniquingKeysWith: { _, error in
error
})
}
sendEvent(withName: ReactNativeConstants.FINISH_INSTALLING_UPDATE.rawValue, body: ["result": result])
}
func reader(_ reader: Reader, didRequestReaderInput inputOptions: ReaderInputOptions = []) {
let result = Mappers.mapFromReaderInputOptions(inputOptions)
sendEvent(withName: ReactNativeConstants.REQUEST_READER_INPUT.rawValue, body: ["result": result])
}
func reader(_ reader: Reader, didRequestReaderDisplayMessage displayMessage: ReaderDisplayMessage) {
let result = Mappers.mapFromReaderDisplayMessage(displayMessage)
sendEvent(withName: ReactNativeConstants.REQUEST_READER_DISPLAY_MESSAGE.rawValue, body: ["result": result])
}
func localMobileReader(_ reader: Reader, didStartInstallingUpdate update: ReaderSoftwareUpdate, cancelable: Cancelable?) {
self.installUpdateCancelable = cancelable
sendEvent(withName: ReactNativeConstants.START_INSTALLING_UPDATE.rawValue, body: ["result": Mappers.mapFromReaderSoftwareUpdate(update) ?? [:]])
}
func localMobileReader(_ reader: Reader, didReportReaderSoftwareUpdateProgress progress: Float) {
let result: [AnyHashable : Any?] = [
"progress": String(progress),
]
sendEvent(withName: ReactNativeConstants.REPORT_UPDATE_PROGRESS.rawValue, body: ["result": result])
}
func localMobileReader(_ reader: Reader, didFinishInstallingUpdate update: ReaderSoftwareUpdate?, error: Error?) {
var result = Mappers.mapFromReaderSoftwareUpdate(update) ?? [:]
if let nsError = error as NSError? {
let errorAsDictionary = Errors.createError(nsError: nsError)
// createError will return a dictionary of ["error": {the error}]
// so merge that with the result so we have a single result.error
result = result.merging(errorAsDictionary, uniquingKeysWith: { _, error in
error
})
}
sendEvent(withName: ReactNativeConstants.FINISH_INSTALLING_UPDATE.rawValue, body: ["result": result])
}
func localMobileReader(_ reader: Reader, didRequestReaderInput inputOptions: ReaderInputOptions = []) {
let result = Mappers.mapFromReaderInputOptions(inputOptions)
sendEvent(withName: ReactNativeConstants.REQUEST_READER_INPUT.rawValue, body: ["result": result])
}
func localMobileReader(_ reader: Reader, didRequestReaderDisplayMessage displayMessage: ReaderDisplayMessage) {
let result = Mappers.mapFromReaderDisplayMessage(displayMessage)
sendEvent(withName: ReactNativeConstants.REQUEST_READER_DISPLAY_MESSAGE.rawValue, body: ["result": result])
}
}