CheckoutViewController.m 16.9 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
//
//  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.
//

27 28
@import Buy;

29 30
#import "CheckoutViewController.h"
#import "SummaryItemsTableViewCell.h"
31
#import "UIButton+PaymentButton.h"
32 33

NSString * const CheckoutCallbackNotification = @"CheckoutCallbackNotification";
34
NSString * const MerchantId = @"";
35

36
@interface CheckoutViewController () <SFSafariViewControllerDelegate, PKPaymentAuthorizationViewControllerDelegate>
37 38 39

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

@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];
    
88
    UIButton *applePayButton = [UIButton paymentButtonWithType:PaymentButtonTypeBuy style:PaymentButtonStyleBlack];
89 90 91 92 93 94 95 96 97 98 99 100 101 102
    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"];
103 104 105 106 107
    
    // Prefetch the shop object for Apple Pay
    [self.client getShop:^(BUYShop *shop, NSError *error) {
        _shop = shop;
    }];
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
}

- (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;
}

140
- (void)addCreditCardToCheckout:(void (^)(BOOL success, id<BUYPaymentToken> token))callback
141
{
142 143
    [self.client storeCreditCard:[self creditCard] checkout:self.checkout completion:^(id<BUYPaymentToken> token, NSError *error) {
        if (error == nil && token) {
144 145 146 147 148 149
            NSLog(@"Successfully added credit card to checkout");
        }
        else {
            NSLog(@"Error applying credit card: %@", error);
        }
        
150
        callback(error == nil && token, token);
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    }];
}

- (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];;
    
170
    [alertController addAction:[UIAlertAction actionWithTitle:@"Start over"
171 172 173
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          [self.navigationController popToRootViewControllerAnimated:YES];
174 175 176 177 178
                                                      }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"Show order status page"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          SFSafariViewController *safariViewController = [[SFSafariViewController alloc] initWithURL:self.checkout.order.statusURL];
179
                                                          safariViewController.delegate = self;
180
                                                          [self presentViewController:safariViewController animated:YES completion:NULL];
181 182 183 184 185
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

186 187 188 189
#pragma mark - SafariViewControllerDelegate

- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller
{
190
    [self getCompletedCheckout:^{
Rune Madsen committed
191 192
        if (self.checkout.order) {
            dispatch_async(dispatch_get_main_queue(), ^{
193
                [self showCheckoutConfirmation];
Rune Madsen committed
194 195
            });
        }
196
    }];
197 198
}

199
#pragma mark - Native Checkout
200 201 202

- (void)checkoutWithCreditCard
{
203 204
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

205 206 207
    __weak CheckoutViewController *welf = self;
    
    // First, the credit card must be stored on the checkout
208
    [self addCreditCardToCheckout:^(BOOL success, id<BUYPaymentToken> token) {
209 210
        
        if (success) {
211
            [welf.client completeCheckoutWithToken:welf.checkout.token paymentToken:token completion:^(BUYCheckout *checkout, NSError *error) {
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
                
                if (error == nil && checkout) {
                    NSLog(@"Successfully completed checkout");
                    welf.checkout = checkout;
                }
                else {
                    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                    NSLog(@"Error completing checkout: %@", error);
                }
            }];
        }
    }];
}

#pragma mark - Apple Pay Checkout

- (void)checkoutWithApplePay
{
    PKPaymentRequest *request = [self paymentRequest];
    
    PKPaymentAuthorizationViewController *paymentController = [[PKPaymentAuthorizationViewController alloc] initWithPaymentRequest:request];
233
    
234
    self.applePayHelper = [[BUYApplePayAuthorizationDelegate alloc] initWithClient:self.client checkout:self.checkout shopName:self.shop.name];
235 236 237 238 239 240
    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
241
     *  You can then also safely remove the PKPaymentAuthorizationViewControllerDelegate
242 243 244 245
     *  methods below.
     *
     *  // paymentController.delegate = self.applePayHelper
     *
Rune Madsen committed
246 247 248 249
     *  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
250 251 252 253 254 255 256 257 258 259 260
     *  the PKPaymentAuthorizationViewControllerDelegate protocol.
     *
     */
    
    [self presentViewController:paymentController animated:YES completion:nil];
}

- (PKPaymentRequest *)paymentRequest
{
    PKPaymentRequest *paymentRequest = [[PKPaymentRequest alloc] init];
    
261
    [paymentRequest setMerchantIdentifier:MerchantId];
262 263 264 265
    [paymentRequest setRequiredBillingAddressFields:PKAddressFieldAll];
    [paymentRequest setRequiredShippingAddressFields:self.checkout.requiresShipping ? PKAddressFieldAll : PKAddressFieldEmail|PKAddressFieldPhone];
    [paymentRequest setSupportedNetworks:@[PKPaymentNetworkVisa, PKPaymentNetworkMasterCard]];
    [paymentRequest setMerchantCapabilities:PKMerchantCapability3DS];
266 267
    [paymentRequest setCountryCode:self.shop.country ?: @"US"];
    [paymentRequest setCurrencyCode:self.shop.currency ?: @"USD"];
268
    
269
    [paymentRequest setPaymentSummaryItems:[self.checkout buy_summaryItemsWithShopName:self.shop.name]];
270 271 272 273 274 275 276 277 278 279 280 281
    
    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
282
    
283
    self.checkout = self.applePayHelper.checkout;
Rune Madsen committed
284
    [self getCompletedCheckout:NULL];
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
}

- (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
316
    
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    // 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"];
    
334
    if ([self.presentedViewController isKindOfClass:[SFSafariViewController class]]) {
Rune Madsen committed
335 336 337
        [self dismissViewControllerAnimated:self.presentedViewController completion:^{
            [self getCompletionStatusAndCompletedCheckoutWithURL:url];
        }];
338
    } else {
Rune Madsen committed
339
        [self getCompletionStatusAndCompletedCheckoutWithURL:url];
340
    }
Rune Madsen committed
341 342 343
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CheckoutCallbackNotification object:nil];
}
344

Rune Madsen committed
345 346
- (void)getCompletionStatusAndCompletedCheckoutWithURL:(NSURL*)url
{
347 348
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
Rune Madsen committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    __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);
        }
    }];
367
}
368

369
- (void)getCompletedCheckout:(void (^)(void))completionBlock
370 371 372 373 374
{
    __weak CheckoutViewController *welf = self;
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
375
    [self.client getCheckoutWithToken:self.checkout.token completion:^(BUYCheckout *checkout, NSError *error) {
Rune Madsen committed
376
        
377 378 379 380 381 382 383 384 385 386
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
        if (error) {
            NSLog(@"Unable to get completed checkout");
            NSLog(@"%@", error);
        }
        if (checkout) {
            welf.checkout = checkout;
            NSLog(@"%@", checkout);
        }
387 388 389 390
        
        if (completionBlock) {
            completionBlock();
        }
391 392 393
    }];
}

394
@end