CheckoutViewController.m 18.3 KB
Newer Older
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
//
//  CheckoutViewController.m
//  Mobile Buy SDK Advanced Sample
//
//  Created by Shopify.
//  Copyright (c) 2015 Shopify Inc. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#import "CheckoutViewController.h"
#import "GetCompletionStatusOperation.h"
#import "SummaryItemsTableViewCell.h"
30 31
#import "ProductListViewController.h"

32 33 34 35 36 37 38 39 40 41
@import Buy;
@import PassKit;
@import SafariServices;

NSString * const CheckoutCallbackNotification = @"CheckoutCallbackNotification";

@interface CheckoutViewController () <GetCompletionStatusOperationDelegate, SFSafariViewControllerDelegate, PKPaymentAuthorizationViewControllerDelegate>

@property (nonatomic, strong) BUYCheckout *checkout;
@property (nonatomic, strong) BUYClient *client;
42
@property (nonatomic, strong) BUYShop *shop;
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
@property (nonatomic, strong) NSArray *summaryItems;
@property (nonatomic, strong) BUYApplePayHelpers *applePayHelper;

@end

@implementation CheckoutViewController

- (instancetype)initWithClient:(BUYClient *)client checkout:(BUYCheckout *)checkout;
{
    NSParameterAssert(client);
    NSParameterAssert(checkout);
    
    self = [super initWithStyle:UITableViewStyleGrouped];
    
    if (self) {
        self.checkout = checkout;
        self.client = client;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"Checkout";
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 164)];
    
    UIButton *creditCardButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [creditCardButton setTitle:@"Checkout with Credit Card" forState:UIControlStateNormal];
    creditCardButton.backgroundColor = [UIColor colorWithRed:0.48f green:0.71f blue:0.36f alpha:1.0f];
    creditCardButton.layer.cornerRadius = 6;
    [creditCardButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    creditCardButton.translatesAutoresizingMaskIntoConstraints = NO;
    [creditCardButton addTarget:self action:@selector(checkoutWithCreditCard) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:creditCardButton];
    
    UIButton *webCheckoutButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [webCheckoutButton setTitle:@"Web Checkout" forState:UIControlStateNormal];
    webCheckoutButton.backgroundColor = [UIColor colorWithRed:0.48f green:0.71f blue:0.36f alpha:1.0f];
    webCheckoutButton.layer.cornerRadius = 6;
    [webCheckoutButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    webCheckoutButton.translatesAutoresizingMaskIntoConstraints = NO;
    [webCheckoutButton addTarget:self action:@selector(checkoutOnWeb) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:webCheckoutButton];
    
    UIButton *applePayButton = [BUYPaymentButton buttonWithType:BUYPaymentButtonTypeBuy style:BUYPaymentButtonStyleBlack];
    applePayButton.translatesAutoresizingMaskIntoConstraints = NO;
    [applePayButton addTarget:self action:@selector(checkoutWithApplePay) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:applePayButton];
    
    NSDictionary *views = NSDictionaryOfVariableBindings(creditCardButton, webCheckoutButton, applePayButton);
    [footerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[creditCardButton]-|" options:0 metrics:nil views:views]];
    [footerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[webCheckoutButton]-|" options:0 metrics:nil views:views]];
    [footerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[applePayButton]-|" options:0 metrics:nil views:views]];
    
    [footerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[creditCardButton(44)]-[webCheckoutButton(==creditCardButton)]-[applePayButton(==creditCardButton)]-|" options:0 metrics:nil views:views]];
    
    self.tableView.tableFooterView = footerView;
    
    [self.tableView registerClass:[SummaryItemsTableViewCell class] forCellReuseIdentifier:@"SummaryCell"];
105 106 107 108 109
    
    // Prefetch the shop object for Apple Pay
    [self.client getShop:^(BUYShop *shop, NSError *error) {
        _shop = shop;
    }];
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
}

- (void)setCheckout:(BUYCheckout *)checkout
{
    _checkout = checkout;
    self.summaryItems = [checkout buy_summaryItems];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.summaryItems count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SummaryCell" forIndexPath:indexPath];
    PKPaymentSummaryItem *summaryItem = self.summaryItems[indexPath.row];
    cell.textLabel.text = summaryItem.label;
    cell.detailTextLabel.text = [self.currencyFormatter stringFromNumber:summaryItem.amount];
    // Only show a line above the last cell
    if (indexPath.row != [self.summaryItems count] - 2) {
        cell.separatorInset = UIEdgeInsetsMake(0.f, 0.f, 0.f, cell.bounds.size.width);
    }
    
    return cell;
}

- (void)addCreditCardToCheckout:(void (^)(BOOL success))callback
{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
Rune Madsen committed
145
    
146 147 148
    [self.client storeCreditCard:[self creditCard] checkout:self.checkout completion:^(BUYCheckout *checkout, NSString *paymentSessionId, NSError *error) {
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
Rune Madsen committed
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
        if (error == nil && checkout) {
            
            NSLog(@"Successfully added credit card to checkout");
            self.checkout = checkout;
        }
        else {
            NSLog(@"Error applying credit card: %@", error);
        }
        
        callback(error == nil && checkout);
    }];
}

- (BUYCreditCard *)creditCard
{
    BUYCreditCard *creditCard = [[BUYCreditCard alloc] init];
    creditCard.number = @"4242424242424242";
    creditCard.expiryMonth = @"12";
    creditCard.expiryYear = @"2020";
    creditCard.cvv = @"123";
    creditCard.nameOnCard = @"John Smith";
    
    return creditCard;
}

- (void)showCheckoutConfirmation
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Checkout complete" message:nil preferredStyle:UIAlertControllerStyleAlert];;
    
179
    [alertController addAction:[UIAlertAction actionWithTitle:@"Start over"
180 181 182
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          [self.navigationController popToRootViewControllerAnimated:YES];
183 184 185 186 187
                                                      }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"Show order status page"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          SFSafariViewController *safariViewController = [[SFSafariViewController alloc] initWithURL:self.checkout.order.statusURL];
188
                                                          safariViewController.delegate = self;
189
                                                          [self presentViewController:safariViewController animated:YES completion:NULL];
190 191 192 193 194
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

195 196 197 198
#pragma mark - SafariViewControllerDelegate

- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller
{
199
    [self getCompletedCheckout:^{
Rune Madsen committed
200 201
        if (self.checkout.order) {
            dispatch_async(dispatch_get_main_queue(), ^{
202
                [self showCheckoutConfirmation];
Rune Madsen committed
203 204
            });
        }
205
    }];
206 207
}

208 209 210 211 212 213 214 215 216 217 218 219
#pragma mark Native Checkout

- (void)checkoutWithCreditCard
{
    __weak CheckoutViewController *welf = self;
    
    // First, the credit card must be stored on the checkout
    [self addCreditCardToCheckout:^(BOOL success) {
        
        if (success) {
            
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
Rune Madsen committed
220
            
221 222 223 224 225 226 227 228 229 230
            // Upon successfully adding the credit card to the checkout, complete checkout must be called immediately
            [welf.client completeCheckout:welf.checkout completion:^(BUYCheckout *checkout, NSError *error) {
                
                if (error == nil && checkout) {
                    
                    NSLog(@"Successfully completed checkout");
                    welf.checkout = checkout;
                    
                    GetCompletionStatusOperation *completionOperation = [[GetCompletionStatusOperation alloc] initWithClient:welf.client withCheckout:welf.checkout];
                    completionOperation.delegate = welf;
Rune Madsen committed
231
                    
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
                    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
                    [[NSOperationQueue mainQueue] addOperation:completionOperation];
                }
                else {
                    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                    NSLog(@"Error completing checkout: %@", error);
                }
            }];
        }
    }];
}

- (void)operation:(GetCompletionStatusOperation *)operation didReceiveCompletionStatus:(BUYStatus)completionStatus
{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
Rune Madsen committed
247
    
248 249
    NSLog(@"Successfully got completion status: %lu", (unsigned long)completionStatus);
    
250
    [self getCompletedCheckout:NULL];
251 252 253 254 255
}

- (void)operation:(GetCompletionStatusOperation *)operation failedToReceiveCompletionStatus:(NSError *)error
{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
Rune Madsen committed
256
    
257 258 259 260 261 262 263 264 265 266
    NSLog(@"Error getting completion status: %@", error);
}

#pragma mark - Apple Pay Checkout

- (void)checkoutWithApplePay
{
    PKPaymentRequest *request = [self paymentRequest];
    
    PKPaymentAuthorizationViewController *paymentController = [[PKPaymentAuthorizationViewController alloc] initWithPaymentRequest:request];
267 268
    
    self.applePayHelper = [[BUYApplePayHelpers alloc] initWithClient:self.client checkout:self.checkout shop:self.shop];
269 270 271 272 273 274
    paymentController.delegate = self;
    
    /**
     *  Alternatively we can set the delegate to self.applePayHelper.
     *  If you do not care about any PKPaymentAuthorizationViewControllerDelegate callbacks
     *  uncomment the code below to let BUYApplePayHelpers take care of them automatically.
Rune Madsen committed
275
     *  You can then also safely remove the PKPaymentAuthorizationViewControllerDelegate
276 277 278 279
     *  methods below.
     *
     *  // paymentController.delegate = self.applePayHelper
     *
Rune Madsen committed
280 281 282 283
     *  If you keep self as the delegate, you have a chance to intercept the
     *  PKPaymentAuthorizationViewControllerDelegate callbacks and add any additional logging
     *  and method calls as you need. Ensure that you forward them to the BUYApplePayHelpers
     *  class by calling the delegate methods on BUYApplePayHelpers which already implements
284 285 286 287 288 289 290 291 292 293 294
     *  the PKPaymentAuthorizationViewControllerDelegate protocol.
     *
     */
    
    [self presentViewController:paymentController animated:YES completion:nil];
}

- (PKPaymentRequest *)paymentRequest
{
    PKPaymentRequest *paymentRequest = [[PKPaymentRequest alloc] init];
    
295
    [paymentRequest setMerchantIdentifier:MERCHANT_ID];
296 297 298 299
    [paymentRequest setRequiredBillingAddressFields:PKAddressFieldAll];
    [paymentRequest setRequiredShippingAddressFields:self.checkout.requiresShipping ? PKAddressFieldAll : PKAddressFieldEmail|PKAddressFieldPhone];
    [paymentRequest setSupportedNetworks:@[PKPaymentNetworkVisa, PKPaymentNetworkMasterCard]];
    [paymentRequest setMerchantCapabilities:PKMerchantCapability3DS];
300 301
    [paymentRequest setCountryCode:self.shop.country ?: @"US"];
    [paymentRequest setCurrencyCode:self.shop.currency ?: @"USD"];
302
    
303
    [paymentRequest setPaymentSummaryItems:[self.checkout buy_summaryItemsWithShopName:self.shop.name]];
304 305 306 307 308 309 310 311 312 313 314 315
    
    return paymentRequest;
}

#pragma mark - PKPaymentAuthorizationViewControllerDelegate

- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
                       didAuthorizePayment:(PKPayment *)payment
                                completion:(void (^)(PKPaymentAuthorizationStatus status))completion
{
    // Add additional methods if needed and forward the callback to BUYApplePayHelpers
    [self.applePayHelper paymentAuthorizationViewController:controller didAuthorizePayment:payment completion:completion];
Rune Madsen committed
316
    
317
    self.checkout = self.applePayHelper.checkout;
Rune Madsen committed
318
    [self getCompletedCheckout:NULL];
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
}

- (void)paymentAuthorizationViewControllerDidFinish:(PKPaymentAuthorizationViewController *)controller
{
    // Add additional methods if needed and forward the callback to BUYApplePayHelpers
    [self.applePayHelper paymentAuthorizationViewControllerDidFinish:controller];
}

-(void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller didSelectShippingAddress:(ABRecordRef)address completion:(void (^)(PKPaymentAuthorizationStatus, NSArray<PKShippingMethod *> * _Nonnull, NSArray<PKPaymentSummaryItem *> * _Nonnull))completion
{
    // Add additional methods if needed and forward the callback to BUYApplePayHelpers
    [self.applePayHelper paymentAuthorizationViewController:controller didSelectShippingAddress:address completion:completion];
}

-(void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller didSelectShippingContact:(PKContact *)contact completion:(void (^)(PKPaymentAuthorizationStatus, NSArray<PKShippingMethod *> * _Nonnull, NSArray<PKPaymentSummaryItem *> * _Nonnull))completion
{
    // Add additional methods if needed and forward the callback to BUYApplePayHelpers
    [self.applePayHelper paymentAuthorizationViewController:controller didSelectShippingContact:contact completion:completion];
}

-(void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller didSelectShippingMethod:(PKShippingMethod *)shippingMethod completion:(void (^)(PKPaymentAuthorizationStatus, NSArray<PKPaymentSummaryItem *> * _Nonnull))completion
{
    // Add additional methods if needed and forward the callback to BUYApplePayHelpers
    [self.applePayHelper paymentAuthorizationViewController:controller didSelectShippingMethod:shippingMethod completion:completion];
}

# pragma mark - Web checkout

- (void)checkoutOnWeb
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveCallbackURLNotification:) name:CheckoutCallbackNotification object:nil];
Rune Madsen committed
350
    
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
    // On iOS 9+ we should use the SafariViewController to display the checkout in-app
    if ([SFSafariViewController class]) {
        
        SFSafariViewController *safariViewController = [[SFSafariViewController alloc] initWithURL:self.checkout.webCheckoutURL];
        safariViewController.delegate = self;
        
        [self presentViewController:safariViewController animated:YES completion:nil];
    }
    else {
        [[UIApplication sharedApplication] openURL:self.checkout.webCheckoutURL];
    }
}

- (void)didReceiveCallbackURLNotification:(NSNotification *)notification
{
    NSURL *url = notification.userInfo[@"url"];
    
368
    if ([self.presentedViewController isKindOfClass:[SFSafariViewController class]]) {
Rune Madsen committed
369 370 371
        [self dismissViewControllerAnimated:self.presentedViewController completion:^{
            [self getCompletionStatusAndCompletedCheckoutWithURL:url];
        }];
372
    } else {
Rune Madsen committed
373
        [self getCompletionStatusAndCompletedCheckoutWithURL:url];
374
    }
Rune Madsen committed
375 376 377
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CheckoutCallbackNotification object:nil];
}
378

Rune Madsen committed
379 380
- (void)getCompletionStatusAndCompletedCheckoutWithURL:(NSURL*)url
{
381 382
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
Rune Madsen committed
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    __weak CheckoutViewController *welf = self;
    
    [self.client getCompletionStatusOfCheckoutURL:url completion:^(BUYStatus status, NSError *error) {
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
        if (error == nil && status == BUYStatusComplete) {
            NSLog(@"Successfully completed checkout");
            [welf getCompletedCheckout:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showCheckoutConfirmation];
                });
            }];
        }
        else {
            NSLog(@"Error completing checkout: %@", error);
        }
    }];
401
}
402

403
- (void)getCompletedCheckout:(void (^)(void))completionBlock
404 405 406 407 408 409
{
    __weak CheckoutViewController *welf = self;
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    [self.client getCheckout:self.checkout completion:^(BUYCheckout *checkout, NSError *error) {
Rune Madsen committed
410
        
411 412 413 414 415 416 417 418 419 420
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
        if (error) {
            NSLog(@"Unable to get completed checkout");
            NSLog(@"%@", error);
        }
        if (checkout) {
            welf.checkout = checkout;
            NSLog(@"%@", checkout);
        }
421 422 423 424
        
        if (completionBlock) {
            completionBlock();
        }
425 426 427
    }];
}

428
@end