-
Notifications
You must be signed in to change notification settings - Fork 976
/
STPPaymentHandler.swift
1569 lines (1403 loc) · 61.4 KB
/
STPPaymentHandler.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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// STPPaymentHandler.swift
// StripeiOS
//
// Created by Cameron Sabol on 5/10/19.
// Copyright © 2019 Stripe, Inc. All rights reserved.
//
import Foundation
import PassKit
import SafariServices
import Stripe3DS2
/// `STPPaymentHandlerActionStatus` represents the possible outcomes of requesting an action by `STPPaymentHandler`. An action could be confirming and/or handling the next action for a PaymentIntent.
@objc public enum STPPaymentHandlerActionStatus: Int {
/// The action succeeded.
case succeeded
/// The action was cancelled by the cardholder/user.
case canceled
/// The action failed. See the error code for more details.
case failed
}
/// Error codes generated by `STPPaymentHandler`
@objc public enum STPPaymentHandlerErrorCode: Int {
/// Indicates that the action requires an authentication method not recognized or supported by the SDK.
@objc(STPPaymentHandlerUnsupportedAuthenticationErrorCode)
case unsupportedAuthenticationErrorCode
/// Attach a payment method to the PaymentIntent or SetupIntent before using `STPPaymentHandler`.
@objc(STPPaymentHandlerRequiresPaymentMethodErrorCode)
case requiresPaymentMethodErrorCode
/// The PaymentIntent or SetupIntent status cannot be resolved by `STPPaymentHandler`.
@objc(STPPaymentHandlerIntentStatusErrorCode)
case intentStatusErrorCode
/// The action timed out.
@objc(STPPaymentHandlerTimedOutErrorCode)
case timedOutErrorCode
/// There was an error in the Stripe3DS2 SDK.
@objc(STPPaymentHandlerStripe3DS2ErrorCode)
case stripe3DS2ErrorCode
/// The transaction did not authenticate (e.g. user entered the wrong code).
@objc(STPPaymentHandlerNotAuthenticatedErrorCode)
case notAuthenticatedErrorCode
/// `STPPaymentHandler` does not support concurrent actions.
@objc(STPPaymentHandlerNoConcurrentActionsErrorCode)
case noConcurrentActionsErrorCode
/// Payment requires a valid `STPAuthenticationContext`. Make sure your presentingViewController isn't already presenting.
@objc(STPPaymentHandlerRequiresAuthenticationContextErrorCode)
case requiresAuthenticationContextErrorCode
/// There was an error confirming the Intent.
/// Inspect the `paymentIntent.lastPaymentError` or `setupIntent.lastSetupError` property.
@objc(STPPaymentHandlerPaymentErrorCode)
case paymentErrorCode
/// The provided PaymentIntent of SetupIntent client secret does not match the expected pattern for client secrets.
/// Make sure that your server is returning the correct value and that is being passed to `STPPaymentHandler`.
@objc(STPPaymentHandlerInvalidClientSecret)
case invalidClientSecret
}
/// Completion block typedef for use in `STPPaymentHandler` methods for Payment Intents.
public typealias STPPaymentHandlerActionPaymentIntentCompletionBlock = (
STPPaymentHandlerActionStatus, STPPaymentIntent?, NSError?
) -> Void
/// Completion block typedef for use in `STPPaymentHandler` methods for Setup Intents.
public typealias STPPaymentHandlerActionSetupIntentCompletionBlock = (
STPPaymentHandlerActionStatus, STPSetupIntent?, NSError?
) -> Void
/// `STPPaymentHandler` is a utility class that confirms PaymentIntents/SetupIntents and handles any authentication required, such as 3DS1/3DS2 for Strong Customer Authentication.
/// It can present authentication UI on top of your app or redirect users out of your app (to e.g. their banking app).
/// - seealso: https://stripe.com/docs/mobile/ios/authentication
@available(iOSApplicationExtension, unavailable)
public class STPPaymentHandler: NSObject, SFSafariViewControllerDelegate, STPURLCallbackListener
{
/// The error domain for errors in `STPPaymentHandler`.
@objc public static let errorDomain = "STPPaymentHandlerErrorDomain"
private var currentAction: STPPaymentHandlerActionParams?
/// YES from when a public method is first called until its associated completion handler is called.
private var inProgress = false
private var safariViewController: SFSafariViewController?
/// The globally shared instance of `STPPaymentHandler`.
@objc public static let sharedHandler: STPPaymentHandler = STPPaymentHandler()
/// The globally shared instance of `STPPaymentHandler`.
@objc
public class func shared() -> STPPaymentHandler {
return STPPaymentHandler.sharedHandler
}
/// `STPPaymentHandler` should not be directly initialized.
private override init() {
self.apiClient = STPAPIClient.shared
self.threeDSCustomizationSettings = STPThreeDSCustomizationSettings()
super.init()
}
/// By default `sharedHandler` initializes with STPAPIClient.shared.
@objc public var apiClient: STPAPIClient
/// Customizable settings to use when performing 3DS2 authentication.
/// Note: Configure this before calling any methods.
/// Defaults to `STPThreeDSCustomizationSettings.defaultSettings()`.
@objc public var threeDSCustomizationSettings: STPThreeDSCustomizationSettings
/// Confirms the PaymentIntent with the provided parameters and handles any `nextAction` required
/// to authenticate the PaymentIntent.
/// Call this method if you are using automatic confirmation. - seealso: https://stripe.com/docs/payments/payment-intents/ios
/// - Parameters:
/// - paymentParams: The params used to confirm the PaymentIntent. Note that this method overrides the value of `paymentParams.useStripeSDK` to `@YES`.
/// - authenticationContext: The authentication context used to authenticate the payment.
/// - completion: The completion block. If the status returned is `STPPaymentHandlerActionStatusSucceeded`, the PaymentIntent status will always be either STPPaymentIntentStatusSucceeded or STPPaymentIntentStatusRequiresCapture if you are using manual capture. In the latter case, capture the PaymentIntent to complete the payment.
@objc(confirmPayment:withAuthenticationContext:completion:)
public func confirmPayment(
_ paymentParams: STPPaymentIntentParams,
with authenticationContext: STPAuthenticationContext,
completion: @escaping STPPaymentHandlerActionPaymentIntentCompletionBlock
) {
if inProgress {
completion(.failed, nil, _error(for: .noConcurrentActionsErrorCode, userInfo: nil))
return
} else if !STPPaymentIntentParams.isClientSecretValid(paymentParams.clientSecret) {
completion(.failed, nil, _error(for: .invalidClientSecret, userInfo: nil))
return
}
inProgress = true
weak var weakSelf = self
// wrappedCompletion ensures we perform some final logic before calling the completion block.
let wrappedCompletion: STPPaymentHandlerActionPaymentIntentCompletionBlock = {
status, paymentIntent, error in
guard let strongSelf = weakSelf else {
return
}
// Reset our internal state
strongSelf.inProgress = false
// Ensure the .succeeded case returns a PaymentIntent in the expected state.
if let paymentIntent = paymentIntent,
status == .succeeded
{
let successIntentState =
paymentIntent.status == .succeeded || paymentIntent.status == .requiresCapture
|| (paymentIntent.status == .processing
&& STPPaymentHandler._isProcessingIntentSuccess(
for: paymentIntent.paymentMethod?.type ?? .unknown))
if error == nil && successIntentState {
completion(.succeeded, paymentIntent, nil)
} else {
assert(false, "Calling completion with invalid state")
completion(
.failed, paymentIntent,
error ?? strongSelf._error(for: .intentStatusErrorCode, userInfo: nil))
}
return
}
completion(status, paymentIntent, error)
}
let confirmCompletionBlock: STPPaymentIntentCompletionBlock = { paymentIntent, error in
guard let strongSelf = weakSelf else {
return
}
if let paymentIntent = paymentIntent,
error == nil
{
strongSelf._handleNextAction(
forPayment: paymentIntent,
with: authenticationContext,
returnURL: paymentParams.returnURL
) { status, completedPaymentIntent, completedError in
wrappedCompletion(status, completedPaymentIntent, completedError)
}
} else {
wrappedCompletion(.failed, paymentIntent, error as NSError?)
}
}
var params = paymentParams
// We always set useStripeSDK = @YES in STPPaymentHandler
if !(params.useStripeSDK?.boolValue ?? false) {
params = paymentParams.copy() as! STPPaymentIntentParams
params.useStripeSDK = NSNumber(value: true)
}
apiClient.confirmPaymentIntent(
with: params,
expand: ["payment_method"],
completion: confirmCompletionBlock)
}
/// :nodoc:
@available(*, deprecated, message: "Use confirmPayment(_:with:completion:) instead", renamed: "confirmPayment(_:with:completion:)")
public func confirmPayment(
withParams: STPPaymentIntentParams,
authenticationContext: STPAuthenticationContext,
completion: @escaping STPPaymentHandlerActionPaymentIntentCompletionBlock
) {
self.confirmPayment(withParams, with: authenticationContext, completion: completion)
}
/// Handles any `nextAction` required to authenticate the PaymentIntent.
/// Call this method if you are using manual confirmation. - seealso: https://stripe.com/docs/payments/payment-intents/ios
/// - Parameters:
/// - paymentIntentClientSecret: The client secret of the PaymentIntent to handle next actions for.
/// - authenticationContext: The authentication context used to authenticate the payment.
/// - returnURL: An optional URL to redirect your customer back to after they authenticate or cancel in a webview. This should match the returnURL you specified during PaymentIntent confirmation.
/// - completion: The completion block. If the status returned is `STPPaymentHandlerActionStatusSucceeded`, the PaymentIntent status will always be either STPPaymentIntentStatusSucceeded, or STPPaymentIntentStatusRequiresConfirmation, or STPPaymentIntentStatusRequiresCapture if you are using manual capture. In the latter two cases, confirm or capture the PaymentIntent on your backend to complete the payment.
@objc(handleNextActionForPayment:withAuthenticationContext:returnURL:completion:)
public func handleNextAction(
forPayment paymentIntentClientSecret: String,
with authenticationContext: STPAuthenticationContext,
returnURL: String?,
completion: @escaping STPPaymentHandlerActionPaymentIntentCompletionBlock
) {
if inProgress {
assert(false, "Should not handle multiple payments at once.")
completion(.failed, nil, _error(for: .noConcurrentActionsErrorCode, userInfo: nil))
return
} else if !STPPaymentIntentParams.isClientSecretValid(paymentIntentClientSecret) {
completion(.failed, nil, _error(for: .invalidClientSecret, userInfo: nil))
return
}
inProgress = true
weak var weakSelf = self
// wrappedCompletion ensures we perform some final logic before calling the completion block.
let wrappedCompletion: STPPaymentHandlerActionPaymentIntentCompletionBlock = {
status, paymentIntent, error in
guard let strongSelf = weakSelf else {
return
}
// Reset our internal state
strongSelf.inProgress = false
// Ensure the .succeeded case returns a PaymentIntent in the expected state.
if let paymentIntent = paymentIntent,
status == .succeeded
{
let successIntentState =
paymentIntent.status == .succeeded ||
paymentIntent.status == .requiresCapture ||
(paymentIntent.status == .processing
&& STPPaymentHandler._isProcessingIntentSuccess(
for: paymentIntent.paymentMethod?.type ?? .unknown) ||
(paymentIntent.status == .requiresAction && strongSelf._isPaymentIntentNextActionVoucherBased(nextAction: paymentIntent.nextAction)))
if error == nil && successIntentState {
completion(.succeeded, paymentIntent, nil)
} else {
assert(false, "Calling completion with invalid state")
completion(
.failed, paymentIntent,
error ?? strongSelf._error(for: .intentStatusErrorCode, userInfo: nil))
}
return
}
completion(status, paymentIntent, error)
}
let retrieveCompletionBlock: STPPaymentIntentCompletionBlock = { paymentIntent, error in
guard let strongSelf = weakSelf else {
return
}
if let paymentIntent = paymentIntent,
error == nil
{
if paymentIntent.status == .requiresConfirmation {
// The caller forgot to confirm the paymentIntent on the backend before calling this method
wrappedCompletion(
.failed, paymentIntent,
strongSelf._error(
for: .intentStatusErrorCode,
userInfo: [
STPError.errorMessageKey:
"Confirm the PaymentIntent on the backend before calling handleNextActionForPayment:withAuthenticationContext:completion."
]))
} else {
strongSelf._handleNextAction(
forPayment: paymentIntent,
with: authenticationContext,
returnURL: returnURL
) { status, completedPaymentIntent, completedError in
wrappedCompletion(status, completedPaymentIntent, completedError)
}
}
} else {
wrappedCompletion(.failed, paymentIntent, error as NSError?)
}
}
apiClient.retrievePaymentIntent(
withClientSecret: paymentIntentClientSecret,
expand: ["payment_method"],
completion: retrieveCompletionBlock)
}
/// Confirms the SetupIntent with the provided parameters and handles any `nextAction` required
/// to authenticate the SetupIntent.
/// - seealso: https://stripe.com/docs/payments/cards/saving-cards#saving-card-without-payment
/// - Parameters:
/// - setupIntentConfirmParams: The params used to confirm the SetupIntent. Note that this method overrides the value of `setupIntentConfirmParams.useStripeSDK` to `@YES`.
/// - authenticationContext: The authentication context used to authenticate the SetupIntent.
/// - completion: The completion block. If the status returned is `STPPaymentHandlerActionStatusSucceeded`, the SetupIntent status will always be STPSetupIntentStatusSucceeded.
@objc(confirmSetupIntent:withAuthenticationContext:completion:)
public func confirmSetupIntent(
_ setupIntentConfirmParams: STPSetupIntentConfirmParams,
with authenticationContext: STPAuthenticationContext,
completion: @escaping STPPaymentHandlerActionSetupIntentCompletionBlock
) {
if inProgress {
assert(false, "Should not handle multiple payments at once.")
completion(.failed, nil, _error(for: .noConcurrentActionsErrorCode, userInfo: nil))
return
} else if !STPSetupIntentConfirmParams.isClientSecretValid(
setupIntentConfirmParams.clientSecret)
{
completion(.failed, nil, _error(for: .invalidClientSecret, userInfo: nil))
return
}
inProgress = true
weak var weakSelf = self
// wrappedCompletion ensures we perform some final logic before calling the completion block.
let wrappedCompletion: STPPaymentHandlerActionSetupIntentCompletionBlock = {
status, setupIntent, error in
guard let strongSelf = weakSelf else {
return
}
// Reset our internal state
strongSelf.inProgress = false
if status == .succeeded {
// Ensure the .succeeded case returns a PaymentIntent in the expected state.
if let setupIntent = setupIntent,
error == nil,
setupIntent.status == .succeeded
{
completion(.succeeded, setupIntent, nil)
} else {
assert(false, "Calling completion with invalid state")
completion(
.failed, setupIntent,
error ?? strongSelf._error(for: .intentStatusErrorCode, userInfo: nil))
}
} else {
completion(status, setupIntent, error)
}
}
let confirmCompletionBlock: STPSetupIntentCompletionBlock = { setupIntent, error in
guard let strongSelf = weakSelf else {
return
}
if let setupIntent = setupIntent,
error == nil
{
let action = STPPaymentHandlerSetupIntentActionParams(
apiClient: self.apiClient,
authenticationContext: authenticationContext,
threeDSCustomizationSettings: self.threeDSCustomizationSettings,
setupIntent: setupIntent,
returnURL: setupIntentConfirmParams.returnURL
) { status, resultSetupIntent, resultError in
guard let strongSelf2 = weakSelf else {
return
}
strongSelf2.currentAction = nil
wrappedCompletion(status, resultSetupIntent, resultError)
}
strongSelf.currentAction = action
let requiresAction = strongSelf._handleSetupIntentStatus(forAction: action)
if requiresAction {
strongSelf._handleAuthenticationForCurrentAction()
}
} else {
wrappedCompletion(.failed, setupIntent, error as NSError?)
}
}
var params = setupIntentConfirmParams
if !(params.useStripeSDK?.boolValue ?? false) {
params = setupIntentConfirmParams.copy() as! STPSetupIntentConfirmParams
params.useStripeSDK = NSNumber(value: true)
}
apiClient.confirmSetupIntent(with: params, completion: confirmCompletionBlock)
}
/// Handles any `nextAction` required to authenticate the SetupIntent.
/// Call this method if you are confirming the SetupIntent on your backend and get a status of requires_action.
/// - Parameters:
/// - setupIntentClientSecret: The client secret of the SetupIntent to handle next actions for.
/// - authenticationContext: The authentication context used to authenticate the SetupIntent.
/// - returnURL: An optional URL to redirect your customer back to after they authenticate or cancel in a webview. This should match the returnURL you specified during SetupIntent confirmation.
/// - completion: The completion block. If the status returned is `STPPaymentHandlerActionStatusSucceeded`, the SetupIntent status will always be STPSetupIntentStatusSucceeded.
@objc(handleNextActionForSetupIntent:withAuthenticationContext:returnURL:completion:)
public func handleNextAction(
forSetupIntent setupIntentClientSecret: String,
with authenticationContext: STPAuthenticationContext,
returnURL: String?,
completion: @escaping STPPaymentHandlerActionSetupIntentCompletionBlock
) {
if inProgress {
assert(false, "Should not handle multiple payments at once.")
completion(.failed, nil, _error(for: .noConcurrentActionsErrorCode, userInfo: nil))
return
} else if !STPSetupIntentConfirmParams.isClientSecretValid(setupIntentClientSecret) {
completion(.failed, nil, _error(for: .invalidClientSecret, userInfo: nil))
return
}
inProgress = true
weak var weakSelf = self
// wrappedCompletion ensures we perform some final logic before calling the completion block.
let wrappedCompletion: STPPaymentHandlerActionSetupIntentCompletionBlock = {
status, setupIntent, error in
guard let strongSelf = weakSelf else {
return
}
// Reset our internal state
strongSelf.inProgress = false
if status == .succeeded {
// Ensure the .succeeded case returns a PaymentIntent in the expected state.
if let setupIntent = setupIntent,
error == nil,
setupIntent.status == .succeeded
{
completion(.succeeded, setupIntent, nil)
} else {
assert(false, "Calling completion with invalid state")
completion(
.failed, setupIntent,
error ?? strongSelf._error(for: .intentStatusErrorCode, userInfo: nil))
}
} else {
completion(status, setupIntent, error)
}
}
let retrieveCompletionBlock: STPSetupIntentCompletionBlock = { setupIntent, error in
guard let strongSelf = weakSelf else {
return
}
if let setupIntent = setupIntent,
error == nil
{
if setupIntent.status == .requiresConfirmation {
// The caller forgot to confirm the setupIntent on the backend before calling this method
wrappedCompletion(
.failed, setupIntent,
strongSelf._error(
for: .intentStatusErrorCode,
userInfo: [
STPError.errorMessageKey:
"Confirm the SetupIntent on the backend before calling handleNextActionForSetupIntent:withAuthenticationContext:completion."
]))
} else {
strongSelf._handleNextAction(
for: setupIntent,
with: authenticationContext,
returnURL: returnURL
) { status, completedSetupIntent, completedError in
wrappedCompletion(status, completedSetupIntent, completedError)
}
}
} else {
wrappedCompletion(.failed, setupIntent, error as NSError?)
}
}
apiClient.retrieveSetupIntent(
withClientSecret: setupIntentClientSecret, completion: retrieveCompletionBlock)
}
// MARK: - Private Helpers
/// Depending on the PaymentMethod Type, after handling next action and confirming,
/// we should either expect a success state on the PaymentIntent, or for certain asynchronous
/// PaymentMethods like SEPA Debit, processing is considered a completed PaymentIntent flow
/// because the funds can take up to 14 days to transfer from the customer's bank.
class func _isProcessingIntentSuccess(for type: STPPaymentMethodType) -> Bool {
switch type {
/* Asynchronous */
case .SEPADebit,
.bacsDebit /* Bacs Debit takes 2-3 business days */,
.AUBECSDebit,
.sofort:
return true
/* Synchronous */
case .alipay,
.card,
.iDEAL,
.FPX,
.cardPresent,
.giropay,
.EPS,
.payPal,
.przelewy24,
.bancontact,
.OXXO,
.grabPay:
return false
case .unknown:
return false
@unknown default:
return false
}
}
func _handleNextAction(
forPayment paymentIntent: STPPaymentIntent,
with authenticationContext: STPAuthenticationContext,
returnURL returnURLString: String?,
completion: @escaping STPPaymentHandlerActionPaymentIntentCompletionBlock
) {
guard paymentIntent.status != .requiresPaymentMethod else {
// The caller forgot to attach a paymentMethod.
completion(
.failed, paymentIntent, _error(for: .requiresPaymentMethodErrorCode, userInfo: nil))
return
}
weak var weakSelf = self
let action = STPPaymentHandlerPaymentIntentActionParams(
apiClient: apiClient,
authenticationContext: authenticationContext,
threeDSCustomizationSettings: threeDSCustomizationSettings,
paymentIntent: paymentIntent,
returnURL: returnURLString
) { status, resultPaymentIntent, error in
guard let strongSelf = weakSelf else {
return
}
strongSelf.currentAction = nil
completion(status, resultPaymentIntent, error)
}
currentAction = action
let requiresAction = _handlePaymentIntentStatus(forAction: action)
if requiresAction {
_handleAuthenticationForCurrentAction()
}
}
func _handleNextAction(
for setupIntent: STPSetupIntent,
with authenticationContext: STPAuthenticationContext,
returnURL returnURLString: String?,
completion: @escaping STPPaymentHandlerActionSetupIntentCompletionBlock
) {
guard setupIntent.status != .requiresPaymentMethod else {
// The caller forgot to attach a paymentMethod.
completion(.failed, setupIntent, _error(for: .requiresPaymentMethodErrorCode, userInfo: nil))
return
}
weak var weakSelf = self
let action = STPPaymentHandlerSetupIntentActionParams(
apiClient: apiClient,
authenticationContext: authenticationContext,
threeDSCustomizationSettings: threeDSCustomizationSettings,
setupIntent: setupIntent,
returnURL: returnURLString
) { status, resultSetupIntent, resultError in
guard let strongSelf = weakSelf else {
return
}
strongSelf.currentAction = nil
completion(status, resultSetupIntent, resultError)
}
currentAction = action
let requiresAction = _handleSetupIntentStatus(forAction: action)
if requiresAction {
_handleAuthenticationForCurrentAction()
}
}
/// Calls the current action's completion handler for the SetupIntent status, or returns YES if the status is ...RequiresAction.
func _handleSetupIntentStatus(forAction action: STPPaymentHandlerSetupIntentActionParams) -> Bool
{
guard let setupIntent = action.setupIntent else {
assert(false, "Calling _handleSetupIntentStatus without a setupIntent")
return false
}
switch setupIntent.status {
case .unknown:
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(
for: .intentStatusErrorCode,
userInfo: [
"STPSetupIntent": setupIntent.description
]))
case .requiresPaymentMethod:
// If the user forgot to attach a PaymentMethod, they get an error before this point.
// If confirmation fails (eg not authenticated, card declined) the SetupIntent transitions to this state.
if let lastSetupError = setupIntent.lastSetupError {
if lastSetupError.code == STPSetupIntentLastSetupError.CodeAuthenticationFailure {
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(for: .notAuthenticatedErrorCode, userInfo: nil))
} else if lastSetupError.type == .card {
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(
for: .paymentErrorCode,
userInfo: [
NSLocalizedDescriptionKey: lastSetupError.message ?? ""
]))
} else {
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(for: .paymentErrorCode, userInfo: nil))
}
} else {
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(for: .paymentErrorCode, userInfo: nil))
}
case .requiresConfirmation:
action.complete(with: STPPaymentHandlerActionStatus.succeeded, error: nil)
case .requiresAction:
return true
case .processing:
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(for: .intentStatusErrorCode, userInfo: nil))
case .succeeded:
action.complete(with: STPPaymentHandlerActionStatus.succeeded, error: nil)
case .canceled:
action.complete(with: STPPaymentHandlerActionStatus.canceled, error: nil)
@unknown default:
fatalError()
}
return false
}
/// Calls the current action's completion handler for the PaymentIntent status, or returns YES if the status is ...RequiresAction.
func _handlePaymentIntentStatus(forAction action: STPPaymentHandlerPaymentIntentActionParams)
-> Bool
{
guard let paymentIntent = action.paymentIntent else {
assert(false, "Calling _handlePaymentIntentStatus without a paymentIntent")
return false
}
switch paymentIntent.status {
case .unknown:
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(
for: .intentStatusErrorCode,
userInfo: [
"STPPaymentIntent": paymentIntent.description
]))
case .requiresPaymentMethod:
// If the user forgot to attach a PaymentMethod, they get an error before this point.
// If confirmation fails (eg not authenticated, card declined) the PaymentIntent transitions to this state.
if let lastPaymentError = paymentIntent.lastPaymentError {
if lastPaymentError.code == STPPaymentIntentLastPaymentError.ErrorCodeAuthenticationFailure
{
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(for: .notAuthenticatedErrorCode, userInfo: nil))
} else if lastPaymentError.type == .card {
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(
for: .paymentErrorCode,
userInfo: [
NSLocalizedDescriptionKey: lastPaymentError.message ?? ""
]))
} else {
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(for: .paymentErrorCode, userInfo: nil))
}
} else {
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(for: .paymentErrorCode, userInfo: nil))
}
case .requiresConfirmation:
action.complete(with: STPPaymentHandlerActionStatus.succeeded, error: nil)
case .requiresAction:
return true
case .processing:
if let type = paymentIntent.paymentMethod?.type,
STPPaymentHandler._isProcessingIntentSuccess(for: type)
{
action.complete(with: STPPaymentHandlerActionStatus.succeeded, error: nil)
} else {
action.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(for: .intentStatusErrorCode, userInfo: nil))
}
case .succeeded:
action.complete(with: STPPaymentHandlerActionStatus.succeeded, error: nil)
case .requiresCapture:
action.complete(with: STPPaymentHandlerActionStatus.succeeded, error: nil)
case .canceled:
action.complete(with: STPPaymentHandlerActionStatus.canceled, error: nil)
case .requiresSource:
fatalError()
case .requiresSourceAction:
fatalError()
}
return false
}
func _handleAuthenticationForCurrentAction() {
guard let currentAction = currentAction,
let authenticationAction = currentAction.nextAction()
else {
return
}
switch authenticationAction.type {
case .unknown:
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(
for: .unsupportedAuthenticationErrorCode,
userInfo: [
"STPIntentAction": authenticationAction.description
]))
case .redirectToURL:
if let redirectToURL = authenticationAction.redirectToURL {
_handleRedirect(to: redirectToURL.url, withReturn: redirectToURL.returnURL)
} else {
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(
for: .unsupportedAuthenticationErrorCode,
userInfo: [
"STPIntentAction": authenticationAction.description
]))
}
case .alipayHandleRedirect:
if let alipayHandleRedirect = authenticationAction.alipayHandleRedirect {
_handleRedirect(
to: alipayHandleRedirect.nativeURL, fallbackURL: alipayHandleRedirect.url,
return: alipayHandleRedirect.returnURL)
} else {
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(
for: .unsupportedAuthenticationErrorCode,
userInfo: [
"STPIntentAction": authenticationAction.description
]))
}
case .OXXODisplayDetails:
if let hostedVoucherURL = authenticationAction.oxxoDisplayDetails?.hostedVoucherURL {
self._handleRedirect(to: hostedVoucherURL, withReturn: nil)
} else {
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(
for: .unsupportedAuthenticationErrorCode,
userInfo: [
"STPIntentAction": authenticationAction.description
]))
}
case .useStripeSDK:
if let useStripeSDK = authenticationAction.useStripeSDK {
switch useStripeSDK.type {
case .unknown:
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(
for: .unsupportedAuthenticationErrorCode,
userInfo: [
"STPIntentAction": authenticationAction.description
]))
case .threeDS2Fingerprint:
guard let threeDSService = currentAction.threeDS2Service else {
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(
for: .stripe3DS2ErrorCode,
userInfo: [
"description": "Failed to initialize STDSThreeDS2Service."
]))
return
}
var transaction: STDSTransaction?
var authRequestParams: STDSAuthenticationRequestParameters?
STDSSwiftTryCatch.try(
{
transaction = threeDSService.createTransaction(
forDirectoryServer: useStripeSDK.directoryServerID ?? "",
serverKeyID: useStripeSDK.directoryServerKeyID,
certificateString: useStripeSDK.directoryServerCertificate ?? "",
rootCertificateStrings: useStripeSDK.rootCertificateStrings ?? [],
withProtocolVersion: "2.1.0")
authRequestParams = transaction?.createAuthenticationRequestParameters()
},
catch: { exception in
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed,
error: self._error(
for: .stripe3DS2ErrorCode,
userInfo: [
"exception": exception.description
]))
},
finallyBlock: {
})
STPAnalyticsClient.sharedClient.log3DS2AuthenticateAttempt(
with: currentAction.apiClient.configuration,
intentID: currentAction.intentStripeID ?? "")
if let authParams = authRequestParams,
let transaction = transaction
{
currentAction.apiClient.authenticate3DS2(
authParams,
sourceIdentifier: useStripeSDK.threeDSSourceID ?? "",
returnURL: currentAction.returnURLString,
maxTimeout: currentAction.threeDSCustomizationSettings.authenticationTimeout
) { (authenticateResponse, error) in
if let authenticateResponse = authenticateResponse,
error == nil
{
if let aRes = authenticateResponse.authenticationResponse {
if aRes.isChallengeRequired {
let challengeParameters = STDSChallengeParameters(authenticationResponse: aRes)
let doChallenge: STPVoidBlock = {
var presentationError: NSError?
if !self._canPresent(
with: currentAction.authenticationContext, error: &presentationError)
{
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed, error: presentationError)
} else {
STDSSwiftTryCatch.try(
{
transaction.doChallenge(
with: currentAction.authenticationContext
.authenticationPresentingViewController(),
challengeParameters: challengeParameters,
challengeStatusReceiver: self,
timeout: TimeInterval(
currentAction.threeDSCustomizationSettings.authenticationTimeout
* 60))
},
catch: { exception in
self.currentAction?.complete(
with: STPPaymentHandlerActionStatus.failed,
error: self._error(
for: .stripe3DS2ErrorCode,
userInfo: [
"exception": exception
]))
},
finallyBlock: {
})
}
}
if currentAction.authenticationContext.responds(
to: #selector(STPAuthenticationContext.prepare(forPresentation:)))
{
currentAction.authenticationContext.prepare?(forPresentation: doChallenge)
} else {
doChallenge()
}
} else {
// Challenge not required, finish the flow.
transaction.close()
STPAnalyticsClient.sharedClient.log3DS2FrictionlessFlow(
with: currentAction.apiClient.configuration,
intentID: currentAction.intentStripeID ?? "")
self._retrieveAndCheckIntentForCurrentAction()
}
} else if let fallbackURL = authenticateResponse.fallbackURL {
self._handleRedirect(
to: fallbackURL, withReturn: URL(string: currentAction.returnURLString ?? ""))
} else {
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed,
error: self._error(
for: .unsupportedAuthenticationErrorCode,
userInfo: [
"STPIntentAction": authenticationAction.description
]))
}
} else {
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed, error: (error as NSError?))
}
}
} else {
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed,
error: self._error(
for: .unsupportedAuthenticationErrorCode,
userInfo: [
"STPIntentAction": authenticationAction.description
]))
}
case .threeDS2Redirect:
if let redirectURL = useStripeSDK.redirectURL {
let returnURL: URL?
if let returnURLString = currentAction.returnURLString {
returnURL = URL(string: returnURLString)
} else {
returnURL = nil
}
_handleRedirect(to: redirectURL, withReturn: returnURL)
} else {
// TOOD : Error
}
@unknown default:
fatalError()
}
} else {
currentAction.complete(
with: STPPaymentHandlerActionStatus.failed,
error: _error(
for: .unsupportedAuthenticationErrorCode,
userInfo: [
"STPIntentAction": authenticationAction.description
]))
}
@unknown default:
fatalError()
}
}
func _retrieveAndCheckIntentForCurrentAction() {
// Alipay requires us to hit an endpoint before retrieving the PI, to ensure the status is up to date.
let pingMarlinIfNecessary:
((STPPaymentHandlerPaymentIntentActionParams, @escaping STPVoidBlock) -> Void) = {
currentAction, completionBlock in
if let paymentMethod = currentAction.paymentIntent?.paymentMethod,
paymentMethod.type == .alipay,
let alipayHandleRedirect = currentAction.nextAction()?.alipayHandleRedirect
{
let alipayReturnURL = alipayHandleRedirect.returnURL
// Make a request to the return URL
let request: URLRequest = URLRequest(url: alipayReturnURL)
let task: URLSessionDataTask = URLSession.shared.dataTask(
with: request,