/
BTDropInViewController.m
649 lines (524 loc) · 28.7 KB
/
BTDropInViewController.m
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
#import "BTDropInViewController.h"
#import "BTDropInContentView.h"
#import "BTDropInSelectPaymentMethodViewController.h"
#import "BTUICardFormView.h"
#import "BTUIScrollView.h"
#import "BTDropInUtil.h"
#import "Braintree-API.h"
#import "BTClient+BTPayPal.h"
#import "BTDropInErrorState.h"
#import "BTDropInErrorAlert.h"
#import "BTDropInLocalizedString.h"
#import "btpaymentmethodcreationdelegate.h"
#import "BTClient_Metadata.h"
@interface BTDropInViewController () < BTDropInSelectPaymentMethodViewControllerDelegate, BTUIScrollViewScrollRectToVisibleDelegate, BTUICardFormViewDelegate, BTPaymentMethodCreationDelegate, BTDropInViewControllerDelegate>
@property (nonatomic, strong) BTDropInContentView *dropInContentView;
@property (nonatomic, strong) BTDropInViewController *addPaymentMethodDropInViewController;
@property (nonatomic, strong) BTUIScrollView *scrollView;
@property (nonatomic, assign) NSInteger selectedPaymentMethodIndex;
@property (nonatomic, strong) UIBarButtonItem *submitBarButtonItem;
/// Whether current visible.
@property (nonatomic, assign) BOOL visible;
@property (nonatomic, assign) NSTimeInterval visibleStartTime;
/// If YES, fetch and display payment methods on file, summary view, CTA control.
/// If NO, do not fetch payment methods, and just show UI to add a new method.
///
/// Defaults to `YES`.
@property (nonatomic, assign) BOOL fullForm;
/// Strong reference to a BTDropInErrorAlert. Reference is needed to
/// handle user input from UIAlertView.
@property (nonatomic, strong) BTDropInErrorAlert *fetchPaymentMethodsErrorAlert;
/// Strong reference to BTDropInErrorAlert. Reference is needed to
/// handle user input from UIAlertView.
@property (nonatomic, strong) BTDropInErrorAlert *savePayPalAccountErrorAlert;
@end
@implementation BTDropInViewController
- (instancetype)initWithClient:(BTClient *)client {
self = [self init];
if (self) {
self.theme = [BTUI braintreeTheme];
self.dropInContentView = [[BTDropInContentView alloc] init];
self.client = [client copyWithMetadata:^(BTClientMutableMetadata *metadata) {
metadata.integration = BTClientMetadataIntegrationDropIn;
}];
self.dropInContentView.paymentButton.client = self.client;
self.dropInContentView.paymentButton.delegate = self;
self.dropInContentView.hidePayPal = !self.client.btPayPal_isPayPalEnabled;
self.selectedPaymentMethodIndex = NSNotFound;
self.dropInContentView.state = BTDropInContentViewStateActivity;
self.fullForm = YES;
_callToActionText = BTDropInLocalizedString(DEFAULT_CALL_TO_ACTION);
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.edgesForExtendedLayout = UIRectEdgeNone;
self.view.backgroundColor = self.theme.viewBackgroundColor;
// Configure Subviews
self.scrollView = [[BTUIScrollView alloc] init];
self.scrollView.scrollRectToVisibleDelegate = self;
self.scrollView.bounces = YES;
self.scrollView.scrollsToTop = YES;
self.scrollView.alwaysBounceVertical = YES;
self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
self.scrollView.delaysContentTouches = NO;
self.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
self.dropInContentView.translatesAutoresizingMaskIntoConstraints = NO;
self.dropInContentView.cardForm.delegate = self;
self.dropInContentView.cardForm.alphaNumericPostalCode = YES;
self.dropInContentView.cardForm.optionalFields = self.optionalFieldsFromClientToken;
[self.dropInContentView.changeSelectedPaymentMethodButton addTarget:self
action:@selector(tappedChangePaymentMethod)
forControlEvents:UIControlEventTouchUpInside];
[self.dropInContentView.ctaControl addTarget:self
action:@selector(tappedSubmitForm)
forControlEvents:UIControlEventTouchUpInside];
self.dropInContentView.cardFormSectionHeader.textColor = self.theme.sectionHeaderTextColor;
self.dropInContentView.cardFormSectionHeader.font = self.theme.sectionHeaderFont;
self.dropInContentView.cardFormSectionHeader.text = BTDropInLocalizedString(CARD_FORM_SECTION_HEADER);
// Call the setters explicitly
[self setCallToActionText:_callToActionText];
[self setSummaryDescription:_summaryDescription];
[self setSummaryTitle:_summaryTitle];
[self setDisplayAmount:_displayAmount];
[self setShouldHideCallToAction:_shouldHideCallToAction];
[self.dropInContentView setNeedsUpdateConstraints];
// Add Subviews
[self.view addSubview:self.scrollView];
[self.scrollView addSubview:self.dropInContentView];
// Add initial constraints
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|"
options:0
metrics:nil
views:@{@"scrollView": self.scrollView}]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|"
options:0
metrics:nil
views:@{@"scrollView": self.scrollView}]];
[self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:self.dropInContentView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.scrollView
attribute:NSLayoutAttributeWidth
multiplier:1
constant:0]];
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[dropInContentView]|"
options:0
metrics:nil
views:@{@"dropInContentView": self.dropInContentView}]];
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[dropInContentView]|"
options:0
metrics:nil
views:@{@"dropInContentView": self.dropInContentView}]];
if (!self.fullForm) {
self.dropInContentView.state = BTDropInContentViewStateForm;
}
[self updateValidity];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.visible = YES;
self.visibleStartTime = [NSDate timeIntervalSinceReferenceDate];
// Ensure dropInContentView is visible. See viewWillDisappear below
self.dropInContentView.alpha = 1.0f;
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// Quickly fade out the content view to prevent a jarring effect
// as keyboard dimisses.
[UIView animateWithDuration:self.theme.quickTransitionDuration animations:^{
self.dropInContentView.alpha = 0.0f;
}];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
self.visible = NO;
}
#pragma mark - BTUIScrollViewScrollRectToVisibleDelegate implementation
// Delegate implementation to handle "custom" autoscrolling via the BTUIScrollView class
//
// Scroll priorities are:
// 1. Attempt to display the submit button, even if it means the card form title is not visible.
// 2. If that isn't possible, at least attempt to show the card form title.
// 3. If that fails, fail just do the default behavior (relevant in landscape).
//
// Some cleanup here could attempt to parameterize or make sane some of the magic number pixel nudging.
- (void)scrollView:(BTUIScrollView *)scrollView requestsScrollRectToVisible:(CGRect)rect animated:(BOOL)animated {
CGRect targetRect = rect;
CGRect desiredVisibleTopRect = [self.scrollView convertRect:self.dropInContentView.cardFormSectionHeader.frame fromView:self.dropInContentView];
desiredVisibleTopRect.origin.y -= 7;
CGRect desiredVisibleBottomRect;
if (self.dropInContentView.ctaControl.hidden) {
desiredVisibleBottomRect = desiredVisibleTopRect;
} else {
desiredVisibleBottomRect = [self.scrollView convertRect:self.dropInContentView.ctaControl.frame fromView:self.dropInContentView];
}
CGFloat visibleAreaHeight = self.scrollView.frame.size.height - self.scrollView.contentInset.bottom - self.scrollView.contentInset.top;
CGRect weightedBottomRect = CGRectUnion(targetRect, desiredVisibleBottomRect);
if (weightedBottomRect.size.height <= visibleAreaHeight) {
targetRect = weightedBottomRect;
}
CGRect weightedTopRect = CGRectUnion(targetRect, desiredVisibleTopRect);
if (weightedTopRect.size.height <= visibleAreaHeight) {
targetRect = weightedTopRect;
targetRect.size.height = MIN(visibleAreaHeight, CGRectGetMaxY(weightedBottomRect) - CGRectGetMinY(targetRect));
}
[scrollView defaultScrollRectToVisible:targetRect animated:animated];
}
#pragma mark - Keyboard behavior
- (void)keyboardWillHide:(__unused NSNotification *)inputViewNotification {
UIEdgeInsets ei = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0);
[UIView animateWithDuration:self.theme.transitionDuration animations:^{
self.scrollView.scrollIndicatorInsets = ei;
self.scrollView.contentInset = ei;
}];
}
- (void)keyboardWillShow:(__unused NSNotification *)inputViewNotification {
CGRect inputViewFrame = [[[inputViewNotification userInfo] valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect inputViewFrameInView = [self.view convertRect:inputViewFrame fromView:nil];
CGRect intersection = CGRectIntersection(self.scrollView.frame, inputViewFrameInView);
UIEdgeInsets ei = UIEdgeInsetsMake(0.0, 0.0, intersection.size.height, 0.0);
self.scrollView.scrollIndicatorInsets = ei;
self.scrollView.contentInset = ei;
}
#pragma mark - Handlers
- (void)tappedChangePaymentMethod {
UIViewController *rootViewController;
if (self.paymentMethods.count == 1) {
rootViewController = self.addPaymentMethodDropInViewController;
} else {
BTDropInSelectPaymentMethodViewController *selectPaymentMethod = [[BTDropInSelectPaymentMethodViewController alloc] init];
selectPaymentMethod.title = BTDropInLocalizedString(SELECT_PAYMENT_METHOD_TITLE);
selectPaymentMethod.theme = self.theme;
selectPaymentMethod.paymentMethods = self.paymentMethods;
selectPaymentMethod.selectedPaymentMethodIndex = self.selectedPaymentMethodIndex;
selectPaymentMethod.delegate = self;
selectPaymentMethod.client = self.client;
rootViewController = selectPaymentMethod;
}
rootViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self
action:@selector(didCancelChangePaymentMethod)];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
[self presentViewController:navController animated:YES completion:nil];
}
- (void)tappedSubmitForm {
[self showLoadingState:YES];
BTPaymentMethod *paymentMethod = [self selectedPaymentMethod];
if (paymentMethod != nil) {
[self informDelegateWillComplete];
[self informDelegateDidAddPaymentMethod:paymentMethod];
} else if (!self.dropInContentView.cardForm.hidden) {
BTUICardFormView *cardForm = self.dropInContentView.cardForm;
void (^cardFail)(NSError *) = ^(NSError *error) {
[self showLoadingState:NO];
if (error && [error.domain isEqualToString:BTBraintreeAPIErrorDomain] && error.code == BTCustomerInputErrorInvalid) {
[self informUserDidFailWithError:error];
} else {
NSString *localizedAlertTitle = BTDropInLocalizedString(ERROR_SAVING_CARD_ALERT_TITLE);
NSString *localizedAlertMessage = BTDropInLocalizedString(ERROR_SAVING_CARD_MESSAGE);
NSString *localizedCancel = BTDropInLocalizedString(ERROR_ALERT_OK_BUTTON_TEXT);
[[[UIAlertView alloc] initWithTitle:localizedAlertTitle
message:localizedAlertMessage
delegate:nil
cancelButtonTitle:localizedCancel
otherButtonTitles:nil] show];
}
};
if (cardForm.valid) {
[self informDelegateWillComplete];
BTClient *client = [self.client copyWithMetadata:^(BTClientMutableMetadata *metadata) {
metadata.source = BTClientMetadataSourceForm;
}];
[client saveCardWithNumber:cardForm.number
expirationMonth:cardForm.expirationMonth
expirationYear:cardForm.expirationYear
cvv:cardForm.cvv
postalCode:cardForm.postalCode
validate:YES
success:^(BTCardPaymentMethod *card) {
[self showLoadingState:NO];
[self informDelegateDidAddPaymentMethod:card];
}
failure:cardFail];
} else {
cardFail(nil);
}
}
}
- (void)didCancelChangePaymentMethod {
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark Progress UI
- (void)showLoadingState:(BOOL)loadingState {
[self.dropInContentView.ctaControl showLoadingState:loadingState];
self.submitBarButtonItem.enabled = !loadingState;
if (self.submitBarButtonItem != nil) {
[BTUI activityIndicatorViewStyleForBarTintColor:self.navigationController.navigationBar.barTintColor];
UIActivityIndicatorView *submitInProgressActivityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[submitInProgressActivityIndicator startAnimating];
UIBarButtonItem *submitInProgressActivityIndicatorBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:submitInProgressActivityIndicator];
[self.navigationItem setRightBarButtonItem:(loadingState ? submitInProgressActivityIndicatorBarButtonItem : self.submitBarButtonItem) animated:YES];
}
}
#pragma mark Error UI
- (void)informUserDidFailWithError:(__unused NSError *)error {
BTDropInErrorState *state = [[BTDropInErrorState alloc] initWithError:error];
[self.dropInContentView.cardForm showTopLevelError:state.errorTitle];
for (NSNumber *fieldNumber in state.highlightedFields) {
BTUICardFormField field = [fieldNumber unsignedIntegerValue];
[self.dropInContentView.cardForm showErrorForField:field];
}
}
#pragma mark Card Form Delegate methods
- (void)cardFormViewDidChange:(__unused BTUICardFormView *)cardFormView {
[self updateValidity];
}
#pragma mark Drop In Select Payment Method Table View Controller Delegate methods
- (void)selectPaymentMethodViewController:(BTDropInSelectPaymentMethodViewController *)viewController
didSelectPaymentMethodAtIndex:(NSUInteger)index {
self.selectedPaymentMethodIndex = index;
[viewController.navigationController dismissViewControllerAnimated:YES completion:nil];
}
- (void)selectPaymentMethodViewControllerDidRequestNew:(BTDropInSelectPaymentMethodViewController *)viewController {
[viewController.navigationController pushViewController:self.addPaymentMethodDropInViewController animated:YES];
}
#pragma mark BTDropInViewControllerDelegate implementation
- (void)dropInViewController:(BTDropInViewController *)viewController didSucceedWithPaymentMethod:(BTPaymentMethod *)paymentMethod {
[viewController.navigationController dismissViewControllerAnimated:YES completion:nil];
NSMutableArray *newPaymentMethods = [NSMutableArray arrayWithArray:self.paymentMethods];
[newPaymentMethods insertObject:paymentMethod atIndex:0];
self.paymentMethods = newPaymentMethods;
}
- (void)dropInViewControllerDidCancel:(BTDropInViewController *)viewController {
[viewController.navigationController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark Payment Method Authorizer Delegate methods
- (void)paymentMethodCreator:(id)sender requestsPresentationOfViewController:(UIViewController *)viewController {
if (sender != self.dropInContentView.paymentButton) {
[self.presentedViewController presentViewController:viewController animated:YES completion:nil];
} else {
[self presentViewController:viewController animated:YES completion:nil];
}
}
- (void)paymentMethodCreator:(__unused id)sender requestsDismissalOfViewController:(__unused UIViewController *)viewController {
// If there is a presented view controller, dismiss it.
if ([self presentedViewController]) {
[self dismissViewControllerAnimated:YES completion:nil];
}
}
- (void)paymentMethodCreatorWillPerformAppSwitch:(id)sender {
NSLog(@"DropIn paymentAuthorizerWillRequestAuthorizationWithAppSwitch:%@", sender);
}
- (void)paymentMethodCreatorWillProcess:(__unused id)sender {
self.dropInContentView.state = BTDropInContentViewStateActivity;
// If there is a presented view controller, dismiss it.
if ([self presentedViewController]) {
[self dismissViewControllerAnimated:YES completion:nil];
}
}
- (void)paymentMethodCreator:(__unused id)sender didCreatePaymentMethod:(BTPaymentMethod *)paymentMethod {
NSMutableArray *newPaymentMethods = [NSMutableArray arrayWithArray:self.paymentMethods];
[newPaymentMethods insertObject:paymentMethod atIndex:0];
self.paymentMethods = newPaymentMethods;
// Let the addPaymentMethodDropInViewController release
self.addPaymentMethodDropInViewController = nil;
}
- (void)paymentMethodCreator:(id)sender didFailWithError:(__unused NSError *)error {
NSString *savePaymentMethodErrorAlertTitle = BTDropInLocalizedString(ERROR_SAVING_PAYMENT_METHOD_ALERT_TITLE);
if (sender != self.dropInContentView.paymentButton) {
// If there is a presented view controller, dismiss it.
if ([self presentedViewController]) {
[self dismissViewControllerAnimated:YES completion:nil];
}
self.savePayPalAccountErrorAlert = [[BTDropInErrorAlert alloc] initWithCancel:^{
// Use the paymentMethods setter to update state
[self setPaymentMethods:_paymentMethods];
self.savePayPalAccountErrorAlert = nil;
} retry:nil];
self.savePayPalAccountErrorAlert.title = savePaymentMethodErrorAlertTitle;
self.savePayPalAccountErrorAlert.message = BTDropInLocalizedString(ERROR_SAVING_PAYMENT_METHOD_ALERT_TITLE);
[self.savePayPalAccountErrorAlert show];
} else {
self.savePayPalAccountErrorAlert = [[BTDropInErrorAlert alloc] initWithCancel:^{
// Use the paymentMethods setter to update state
[self setPaymentMethods:_paymentMethods];
self.savePayPalAccountErrorAlert = nil;
} retry:^{
[sender sendActionsForControlEvents:UIControlEventTouchUpInside];
[self setPaymentMethods:_paymentMethods];
self.savePayPalAccountErrorAlert = nil;
}];
self.savePayPalAccountErrorAlert.title = savePaymentMethodErrorAlertTitle;
[self.savePayPalAccountErrorAlert show];
}
// Let the addPaymentMethodDropInViewController release
self.addPaymentMethodDropInViewController = nil;
}
- (void)paymentMethodCreatorDidCancel:(__unused id)sender {
// If there is a presented view controller, dismiss it.
if ([self presentedViewController]) {
[self dismissViewControllerAnimated:YES completion:nil];
}
// Refresh payment methods display
self.paymentMethods = self.paymentMethods;
// Let the addPaymentMethodDropInViewController release
self.addPaymentMethodDropInViewController = nil;
}
#pragma mark Delegate Notifications
- (void)informDelegateWillComplete {
if ([self.delegate respondsToSelector:@selector(dropInViewControllerWillComplete:)]) {
[self.delegate dropInViewControllerWillComplete:self];
}
}
- (void)informDelegateDidAddPaymentMethod:(BTPaymentMethod *)paymentMethod {
if ([self.delegate respondsToSelector:@selector(dropInViewController:didSucceedWithPaymentMethod:)]) {
[self.delegate dropInViewController:self
didSucceedWithPaymentMethod:paymentMethod];
}
}
- (void)informDelegateDidCancel {
if ([self.delegate respondsToSelector:@selector(dropInViewControllerDidCancel:)]) {
[self.delegate dropInViewControllerDidCancel:self];
}
}
#pragma mark User Supplied Parameters
- (void)setFullForm:(BOOL)fullForm {
_fullForm = fullForm;
if (!self.fullForm) {
self.dropInContentView.state = BTDropInContentViewStateForm;
}
}
- (void)setShouldHideCallToAction:(BOOL)shouldHideCallToAction {
_shouldHideCallToAction = shouldHideCallToAction;
self.dropInContentView.hideCTA = shouldHideCallToAction;
self.submitBarButtonItem = shouldHideCallToAction ? [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave
target:self
action:@selector(tappedSubmitForm)] : nil;
self.submitBarButtonItem.style = UIBarButtonItemStyleDone;
self.navigationItem.rightBarButtonItem = self.submitBarButtonItem;
}
- (void)setSummaryTitle:(NSString *)summaryTitle {
_summaryTitle = summaryTitle;
self.dropInContentView.summaryView.slug = summaryTitle;
self.dropInContentView.hideSummary = (self.summaryTitle == nil || self.summaryDescription == nil);
}
- (void)setSummaryDescription:(__unused NSString *)summaryDescription {
_summaryDescription = summaryDescription;
self.dropInContentView.summaryView.summary = summaryDescription;
self.dropInContentView.hideSummary = (self.summaryTitle == nil || self.summaryDescription == nil);
}
- (void)setDisplayAmount:(__unused NSString *)displayAmount {
_displayAmount = displayAmount;
self.dropInContentView.summaryView.amount = displayAmount;
}
- (void)setCallToActionText:(__unused NSString *)callToActionText {
_callToActionText = callToActionText;
self.dropInContentView.ctaControl.callToAction = callToActionText;
}
#pragma mark Data
- (void)setPaymentMethods:(NSArray *)paymentMethods {
_paymentMethods = paymentMethods;
BTDropInContentViewStateType newState;
if ([self.paymentMethods count] == 0) {
self.selectedPaymentMethodIndex = NSNotFound;
newState = BTDropInContentViewStateForm;
} else {
self.selectedPaymentMethodIndex = 0;
newState = BTDropInContentViewStatePaymentMethodsOnFile;
}
if (self.visible) {
NSTimeInterval elapsed = [NSDate timeIntervalSinceReferenceDate] - self.visibleStartTime;
if (elapsed < self.theme.minimumVisibilityTime) {
NSTimeInterval delay = self.theme.minimumVisibilityTime - elapsed;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.dropInContentView setState:newState animate:YES];
[self updateValidity];
});
return;
}
}
[self.dropInContentView setState:newState animate:self.visible];
[self updateValidity];
}
- (void)setSelectedPaymentMethodIndex:(NSInteger)selectedPaymentMethodIndex {
_selectedPaymentMethodIndex = selectedPaymentMethodIndex;
if (selectedPaymentMethodIndex != NSNotFound) {
BTPaymentMethod *defaultPaymentMethod = [self selectedPaymentMethod];
if ([defaultPaymentMethod isKindOfClass:[BTCardPaymentMethod class]]) {
BTUIPaymentMethodType uiPaymentMethodType = [BTDropInUtil uiForCardType:((BTCardPaymentMethod *)defaultPaymentMethod).type];
self.dropInContentView.selectedPaymentMethodView.type = uiPaymentMethodType;
} else if ([defaultPaymentMethod isKindOfClass:[BTPayPalPaymentMethod class]]) {
self.dropInContentView.selectedPaymentMethodView.type = BTUIPaymentMethodTypePayPal;
} else {
self.dropInContentView.selectedPaymentMethodView.type = BTUIPaymentMethodTypeUnknown;
}
self.dropInContentView.selectedPaymentMethodView.detailDescription = defaultPaymentMethod.description;
}
[self updateValidity];
}
- (BTPaymentMethod *)selectedPaymentMethod {
return self.selectedPaymentMethodIndex != NSNotFound ? self.paymentMethods[self.selectedPaymentMethodIndex] : nil;
}
- (void)updateValidity {
BTPaymentMethod *paymentMethod = [self selectedPaymentMethod];
BOOL valid = (paymentMethod != nil) || (!self.dropInContentView.cardForm.hidden && self.dropInContentView.cardForm.valid);
[self.navigationItem.rightBarButtonItem setEnabled:valid];
[UIView animateWithDuration:self.theme.quickTransitionDuration animations:^{
self.dropInContentView.ctaControl.enabled = valid;
}];
}
- (BTUICardFormOptionalFields)optionalFieldsFromClientToken {
NSSet *challenges = self.client.challenges;
static NSString *cvvChallenge = @"cvv";
static NSString *postalCodeChallenge = @"postal_code";
if ([challenges containsObject:cvvChallenge] && [challenges containsObject:postalCodeChallenge]) {
return BTUICardFormOptionalFieldsAll;
} else if ([challenges containsObject:cvvChallenge]) {
return BTUICardFormOptionalFieldsCvv;
} else if ([challenges containsObject:postalCodeChallenge]) {
return BTUICardFormOptionalFieldsPostalCode;
} else {
return BTUICardFormOptionalFieldsNone;
}
}
- (void)fetchPaymentMethods {
BOOL networkActivityIndicatorState = [[UIApplication sharedApplication] isNetworkActivityIndicatorVisible];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[self.client fetchPaymentMethodsWithSuccess:^(NSArray *paymentMethods) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorState];
self.paymentMethods = paymentMethods;
} failure:^(__unused NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorState];
self.fetchPaymentMethodsErrorAlert = [[BTDropInErrorAlert alloc] initWithCancel:^{
[self informDelegateDidCancel];
self.fetchPaymentMethodsErrorAlert = nil;
} retry:^{
[self fetchPaymentMethods];
self.fetchPaymentMethodsErrorAlert = nil;
}];
[self.fetchPaymentMethodsErrorAlert show];
}];
}
#pragma mark - Helpers
- (BTDropInViewController *)addPaymentMethodDropInViewController {
if (!_addPaymentMethodDropInViewController) {
_addPaymentMethodDropInViewController = [[BTDropInViewController alloc] initWithClient:self.client];
_addPaymentMethodDropInViewController.title = BTDropInLocalizedString(ADD_PAYMENT_METHOD_VIEW_CONTROLLER_TITLE);
_addPaymentMethodDropInViewController.fullForm = NO;
_addPaymentMethodDropInViewController.shouldHideCallToAction = YES;
_addPaymentMethodDropInViewController.delegate = self;
_addPaymentMethodDropInViewController.dropInContentView.paymentButton.delegate = self;
}
return _addPaymentMethodDropInViewController;
}
@end