KWMBeforePayVC.m 29.5 KB
Newer Older
houweibin committed
1 2 3 4 5 6 7 8 9 10 11
//
//  KWMBeforePayVC.m
//  iCemarose
//
//  Created by HouWeiBin on 16/9/2.
//  Copyright © 2016年 kollway. All rights reserved.
//

#import "KWMBeforePayVC.h"
#import "KWMDiscountVC.h"
#import "KWMSelectAddressVC.h"
houweibin committed
12
#import "KWMCustomsClearanceVC.h"
houweibin committed
13 14 15 16 17 18 19
#import "KWMPaySuccessVC.h"
#import "KWMShopCartModel.h"
#import "KWMStringUtil.h"
#import "KWMCheckoutWebViewVC.h"
#import "KWMPaySuccessVC.h"
#import "KWMStringUtil.h"
#import "UIColor+SAMAdditions.h"
lee committed
20
#import <RegexKitLite/RegexKitLite.h>
lee committed
21
#import "KWMHttpUtil.h"
lee committed
22
#import "KWMValidateUtil.h"
23
#import "KWMPayUtil.h"
lee committed
24
#import "KWMShopCartData.h"
u  
lee committed
25
#import "KWMShoppingCart.h"
houweibin committed
26 27

@interface KWMBeforePayVC ()
28
@property (nonatomic) BOOL isEditingDiscount;
houweibin committed
29
@property (nonatomic) BUYCustomer *customer;
lee committed
30
@property (weak, nonatomic) IBOutlet UIButton *submit;
houweibin committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
@end

@implementation KWMBeforePayVC

+(NSString *)kwmTag{
    return @"KWMBeforePayVC";
}

- (void)setAddress:(BUYAddress *)address{
    if (address) {
        _address = address;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self initDefaultData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
52
    [self initDiscountHintText];
houweibin committed
53
    self.title = @"提交订单";
u  
lee committed
54
    self.payType = [self.userDao.currencyCode isEqualToString:@"EUR"]?TypeWebpay:TypeAlipay;
houweibin committed
55
    self.beforePayData = [KWMBeforePayData new];
56
    //支付成功回调广播接收者 ##通过广播接受appdelegate中的支付回调。
houweibin committed
57
    //app active回调广播接受者 ##判断订单支付状态.
58 59
    NSNotificationCenter *notifi = [NSNotificationCenter defaultCenter];
    [notifi addObserver:self selector:@selector(paySuccess) name:KWMPaySuccess object:nil];
houweibin committed
60
    [notifi addObserver:self selector:@selector(requestOrderPayResult) name:UIApplicationDidBecomeActiveNotification object:nil];
lee committed
61
    
62 63 64
}

-(void)dealloc{
houweibin committed
65
    //注销广播接收者
66 67 68 69
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self
                                  name:KWMPaySuccess
                                object:nil];
houweibin committed
70 71 72
    [notificationCenter removeObserver:self
                                  name:UIApplicationDidBecomeActiveNotification
                                object:nil];
73 74 75 76
}

-(void)setPayType:(KWMPayType)payType{
    _payType = payType;
houweibin committed
77 78 79 80 81
    //web支付,隐藏选择支付栏
    if(payType == TypeWebpay){
        self.heightPayType.constant = 0;
        self.vPayType.hidden = YES;
    }
houweibin committed
82 83 84 85 86 87 88 89 90 91 92
}

-(void)initDefaultData{
    if (!_address) {
        [self initDefaultAddress];
    }
    if (!self.checkout){
        [self initCheckOut];
    }
}

lee committed
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
- (void)kwm_setAddress:(BUYAddress *)address {
    if (!address) {
        self.checkout.billingAddress = nil;
        self.checkout.shippingAddress = nil;
        [self initData];
        return;
    }
    if (!self.checkout) {
        self.address = address;
        // viewWillAppear中已经调用了 initCheckOut
//        [self initCheckOut];
        return;
    }
    if(address.identifier.integerValue != self.checkout.billingAddress.identifier.integerValue){
        if(address!=nil && [KWMStringUtil isEmpty:self.address.firstName]){
            self.address.firstName = @"";
        }
        self.checkout.billingAddress = address;
        self.checkout.shippingAddress = address;

        [self showLoading];
        __weak typeof(self) this = self;
        [self.client updateCheckout:self.checkout completion:^(NSDictionary *dictionary, BUYCheckout *checkout, NSError *error) {
            [this hideLoading];
            if (error == nil && checkout) {
                this.address = address;
                this.checkout = checkout;
120
                
lee committed
121
                [this showToast:@"更新地址成功"];
lee committed
122 123
                [this flushCheckout:dictionary];
//                [this initData];
lee committed
124 125 126 127 128 129 130 131 132 133 134
//                [this.userDao saveCheckoutCache:checkout.JSONDictionary];
            }
            else {
                [this showError:error];
//                [self showToast:@"更新地址失败"];
                NSLog(@"Error applying checkout: %@", error);
            }
        }];
    }
}

houweibin committed
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
//因为没有地址后进入的地址页面
-(void)kwm_getAddress:(BUYAddress *)address{
    self.address = address;
}

//创建订单后进入的地址页面
-(void)kwm_selectAddress:(BUYCheckout *)checkout{
    self.checkout = checkout;
    self.checkout.shippingRate = nil;
    self.checkout.shippingRateId = nil;
    [self initData];
}

-(void)kwm_selectShippingRate:(BUYCheckout *)checkout{
    self.checkout = checkout;
    [self initData];
}

- (void)kwm_addedGiftCard:(BUYCheckout *)checkout{
    self.checkout = checkout;
    [self initData];
}

- (void)kwm_removedGiftCard:(BUYCheckout *)checkout{
    self.checkout = checkout;
    [self initData];
}

163 164
-(void)kwm_onSelectPayType:(KWMPayType)payType{
    self.payType = payType;
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    if(payType == TypeWechatPay){
        self.ivAliPay.image = [UIImage imageNamed:@"ic_choose_nor"];
        self.ivWechatPay.image = [UIImage imageNamed:@"ic_choose_sel"];
    }else if(payType == TypeAlipay){
        self.ivAliPay.image = [UIImage imageNamed:@"ic_choose_sel"];
        self.ivWechatPay.image = [UIImage imageNamed:@"ic_choose_nor"];
    }
}

-(void)initDiscountHintText{
    NSString *holderText = @"请输入优惠码";
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:holderText];
    [placeholder addAttribute:NSForegroundColorAttributeName
                        value:[UIColor sam_colorWithHex:@"393939"]
                        range:NSMakeRange(0, holderText.length)];
    self.tfDiscount.attributedPlaceholder = placeholder;
181 182
}

houweibin committed
183 184 185 186 187 188 189 190 191 192 193 194 195
- (void)initData{
    if(self.checkout == nil){
        [self showToast:@"未成功创建订单"];
        return;
    }
    //地址
    if(self.checkout.billingAddress){
        BUYAddress *address = self.checkout.billingAddress;
        self.vAddressHeight.constant = 90;
        self.vHasAddress.hidden = NO;
        self.lbNoAddress.hidden = YES;
        _lbName.text = address.lastName;
        _lbPhone.text = address.phone;
196
        if(address.province){ //省份有可能为空
houweibin committed
197
            //城市 省份
198
            _lbAddress.text = [NSString stringWithFormat:@"%@, %@, %@",address.city,address.province,address.country];
houweibin committed
199 200
        }else{
            //具体地址 补充
201
            _lbAddress.text = [NSString stringWithFormat:@"%@, %@",address.city,address.country];
houweibin committed
202 203 204 205 206 207 208 209 210 211 212 213 214
        }
        _lbAddressDetail.text = [NSString stringWithFormat:@"%@  %@",address.address1,address.address2 == nil?@"":address.address2];
        self.lbShippingRate.textColor = [UIColor sam_colorWithHex:@"393939"];
        self.lbShippingRate.text = @"请选择配送方式";
    }else{
        self.vAddressHeight.constant = 37;
        self.vHasAddress.hidden = YES;
        self.lbNoAddress.hidden = NO;
        self.lbShippingRate.textColor = [UIColor grayColor];
        self.lbShippingRate.text = @"请先选择地址";
    }

    //优惠码
215 216
    if(self.checkout.discount){
        self.tfDiscount.text = self.checkout.discount.code;
houweibin committed
217
    }else{
218 219 220 221 222 223 224 225
        self.tfDiscount.text = @"";
    }
    //优惠码编辑相关
    self.tfDiscount.enabled = self.isEditingDiscount;
    [self.tfDiscount endEditing:!self.isEditingDiscount];
    [self.btnDiscountCancel setHidden:!self.isEditingDiscount];
    [self.btnDiscountConfirm setHidden:!self.isEditingDiscount];
    [self.btnDiscountEdit setHidden:self.isEditingDiscount];
houweibin committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    //礼品卡
    if(self.checkout.giftCardsArray!=nil && self.checkout.giftCardsArray.count>0){
        BUYGiftCard *giftCard = [self.checkout.giftCardsArray objectAtIndex:0];
        self.lbGiftCard.text = [NSString stringWithFormat:@"******%@",giftCard.lastCharacters];
    }else{
        self.lbGiftCard.text = @"请输入礼品卡";
    }
    //配送方式
    if(self.checkout.shippingRate!=nil){
        self.lbShippingRate.text = self.checkout.shippingRate.title;
    }else{
        self.lbShippingRate.text = @"请选择配送方式";
    }
    //总价
    if(self.checkout!=nil){
lee committed
241 242
//        self.lbTotalPrice.text =  [NSString stringWithFormat:@"¥%@",[KWMStringUtil getEUR2CNYstring:self.checkout.totalPrice]];
        self.lbTotalPrice.text = self.checkout.totalPrice.priceValueFormatted;
houweibin committed
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
    }
}

- (void)initDefaultAddress{
    NSDictionary *customerDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"customer"];
    _customer = [[BUYCustomer alloc] initWithModelManager:self.client.modelManager JSONDictionary:customerDict];
    if (_customer) {
        NSDictionary *defaultAddress =  [customerDict objectForKey:@"default_address"];
        if (defaultAddress) {
            _address = [[BUYAddress alloc] initWithModelManager:self.client.modelManager JSONDictionary:defaultAddress];
        }
    }
    if(_address){
        self.vAddressHeight.constant = 90;
        self.vHasAddress.hidden = NO;
        self.lbNoAddress.hidden = YES;
        _lbName.text = _address.lastName;
        _lbPhone.text = _address.phone;
        if(_address.province != nil){
            //城市 省份
            _lbAddress.text = [NSString stringWithFormat:@"%@, %@",_address.city,_address.province];
        }else{
            //具体地址 补充
            _lbAddress.text = _address.city;
        }
        _lbAddressDetail.text = [NSString stringWithFormat:@"%@  %@",_address.address1,_address.address2 == nil?@"":_address.address2];
        self.lbShippingRate.textColor = [UIColor sam_colorWithHex:@"393939"];
        self.lbShippingRate.text = @"请选择配送方式";
    }else{
        self.vAddressHeight.constant = 37;
        self.vHasAddress.hidden = YES;
        self.lbNoAddress.hidden = NO;
        self.lbShippingRate.textColor = [UIColor grayColor];
        self.lbShippingRate.text = @"请先选择地址";
    }
}

//初始化订单
-(void)initBuyCart{
    if(self.fastPayCart!=nil){
        self.cart = self.fastPayCart;
        return;
    }
    if(self.shopcartArray == nil || self.shopcartArray.count == 0){
        [self showToast:@"购物车还没有商品,不能下单哦~"];
        return;
    }
    self.cart = [self.client.modelManager insertCartWithJSONDictionary:nil];
    //将商品加入
    for (KWMShopCartModel *shopcartModel in self.shopcartArray) {
        if(shopcartModel.shopCartDict == nil){
            return;
        }
        BUYProduct *product = [self.client.modelManager insertProductWithJSONDictionary:shopcartModel.shopCartDict];
        if(product == nil || product.identifier == nil){
            return;
        }
        //将商品加入buycart中,每个商品就是一个商品规格model
        if(product.variantsArray!=nil && product.variantsArray.count>0){
            for(BUYProductVariant *mVariant in product.variantsArray){
                if([mVariant.title isEqualToString:shopcartModel.size]){
                    [self.cart setVariant:mVariant withTotalQuantity:shopcartModel.quantity];
                    break;
                }
            }
        }
    }
}

//初始化订单
-(void)initCheckOut{
lee committed
314 315
//    直接使用session cart所以不需要init了之后可以做代码清除
//    [self initBuyCart];
houweibin committed
316
    //如果已登录
lee committed
317 318
//    if(self.cart && self.customer){
    if(self.customer){
houweibin committed
319
        
lee committed
320 321 322 323 324 325 326 327 328 329 330 331
//        BUYCheckout *checkout = nil;
//        //如果self.checkout1=nil,则为缓存订单,反正则为新建订单
//        NSDictionary *checkoutCache = [self.userDao checkOutCache];
//        // 这个if可能不需要了   下面下直接对session进行修改就可以
//        if(checkoutCache){
//            // update server
//            checkout = [[BUYCheckout alloc] initWithModelManager:self.client.modelManager JSONDictionary:checkoutCache];
//            [checkout updateWithCart:self.cart];
//        }else{
//            // init checkout 这里应该也没用了 因为self.cart不存在
//            checkout = [[BUYCheckout alloc] initWithModelManager:self.client.modelManager  cart:self.cart];
//        }
332
//        NSDictionary *checkoutCache = [self.userDao checkOutCache];
lee committed
333
        BUYCheckout *checkout = nil;
334
//        if (!checkoutCache || self.cartCookie) {
lee committed
335
            checkout = [[BUYCheckout alloc] initWithModelManager:self.client.modelManager JSONDictionary:nil];
336
//        }
lee committed
337
//        if(self.address){
houweibin committed
338
            if([self checkAddress:self.address]){
lee committed
339
                [self jumpToSelectAddress];
houweibin committed
340 341 342 343 344 345 346 347 348 349
                return;
            }
            if([KWMStringUtil isEmpty:self.address.firstName]){
                self.address.firstName = @"";
            }
            if([KWMStringUtil isEmpty:self.address.provinceCode]){
                self.address.provinceCode = @"0";
            }
            checkout.shippingAddress = self.address;
            checkout.billingAddress = self.address;
lee committed
350
//        }
houweibin committed
351
        checkout.email = self.customer.email;
352
        checkout.customerId = self.customer.identifier;
houweibin committed
353
//        self.client.urlScheme = @"CemaroseApp://";
lee committed
354 355 356 357 358 359 360 361 362
        // 走session的情况下应该不存在update 只是update cart自动会update到checkout
//        if(checkoutCache){
            // 更新订单
//            [self requestUpdateCheckout:checkout isCacheCheckout:YES];
//        }else{
            // 申请将session cart转成checkout
        [self requestCreateCheckout:checkout];
//            
//        }
houweibin committed
363 364 365
    }
}

lee committed
366 367 368 369 370 371
- (void) jumpToSelectAddress {
    KWMSelectAddressVC *addressVC = (KWMSelectAddressVC *)[KWMBaseVC findControllerBy:[KWMSelectAddressVC kwmTag] fromStoryboard:@"ShopCart"];
//    addressVC.checkout = checkout;
    addressVC.delegate = self;
    [self.navigationController pushViewController:addressVC animated:YES];
}
houweibin committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//选择地址页面
-(void)onClickAddress:(id)sender{
    if(self.checkout == nil){
        [self showToast:@"未成功创建订单"];
        return;
    }
    KWMSelectAddressVC *addressVC = (KWMSelectAddressVC *)[KWMBaseVC findControllerBy:[KWMSelectAddressVC kwmTag] fromStoryboard:@"ShopCart"];
    addressVC.checkout = self.checkout;
    addressVC.delegate = self;
    [self.navigationController pushViewController:addressVC animated:YES];
}

//支付方式页面
-(void)onClickPayType:(id)sender{
    if(self.checkout == nil){
        [self showToast:@"未成功创建订单"];
        return;
    }
395 396 397 398 399 400 401
    UITapGestureRecognizer *tapType = sender;
    UIView *vType = tapType.view;
    if(vType.tag == 1){
        [self kwm_onSelectPayType:TypeAlipay];
    }else if(vType.tag == 2){
        [self kwm_onSelectPayType:TypeWechatPay];
    }
houweibin committed
402 403 404 405 406 407 408 409
}

//优惠码页面
-(void)onClickDiscount:(id)sender{
    if(self.checkout == nil){
        [self showToast:@"未成功创建订单"];
        return;
    }
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
    self.isEditingDiscount = YES;
    [self initData];
    [self.tfDiscount becomeFirstResponder];
}

-(void)onClickDiscountCancel:(id)sender{
    self.isEditingDiscount = NO;
    [self initData];
    [self.tfDiscount resignFirstResponder];
}

-(void)onClickDiscountConfirm:(id)sender{
    if(self.checkout == nil){
        [self showToast:@"未成功创建订单"];
        return;
    }
    if([KWMStringUtil isBlank:self.tfDiscount.text]){
        [self showToast:@"优惠码不能为空"];
        return;
    }
    [self.tfDiscount resignFirstResponder];
    [self showLoading];
    __weak typeof(self) this = self;
    [self.client updateCheckout:self.checkout completion:^(NSDictionary *dictionary, BUYCheckout *checkout, NSError *error) {
        [this hideLoading];
        if (error == nil && checkout && checkout.discount) {
            this.checkout = checkout;
            [this showToast:@"添加优惠码成功"];
            [this flushCheckout:dictionary];
            this.isEditingDiscount = NO;
            [this initData];
        }else {
            [this showToast:@"添加优惠码失败"];
            [this showError:error];
        }
    }];
houweibin committed
446 447 448 449 450 451 452 453 454 455 456 457 458
}

//礼品卡页面
-(void)onClickGiftCard:(id)sender{
    if(self.checkout == nil){
        [self showToast:@"未成功创建订单"];
        return;
    }
    KWMGiftCardVC *giftCardVC = (KWMGiftCardVC *)[KWMBaseVC findControllerBy:[KWMGiftCardVC kwmTag] fromStoryboard:@"ShopCart"];
    giftCardVC.delegate = self;
    giftCardVC.checkout = self.checkout;
    [self.navigationController pushViewController:giftCardVC animated:YES];
}
houweibin committed
459 460 461 462 463
    
//清关信息填写页面
-(void)onClickCustomsClearance:(id)sender{
    
}
houweibin committed
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

//选择配送方式页面
-(void)onClickShipping:(id)sender{
    if(self.checkout == nil){
        [self showToast:@"未成功创建订单"];
        return;
    }
    if(self.checkout.billingAddress == nil){
        [self showToast:@"请先选择地址"];
        return;
    }
    KWMShippingVC *shippingVC = (KWMShippingVC *)[KWMBaseVC findControllerBy:[KWMShippingVC kwmTag] fromStoryboard:@"ShopCart"];
    shippingVC.delegate = self;
    shippingVC.checkout = self.checkout;
    [self.navigationController pushViewController:shippingVC animated:YES];
}

-(void)onClickPay:(id)sender{
    [self startCheckout];
}

-(void)startCheckout{
    if(self.checkout == nil){
        [self showToast:@"未成功初始化订单"];
        return;
    }
    if(self.checkout.shippingAddress == nil){
        [self showToast:@"请先选择地址"];
        return;
    }
494 495 496 497
    if(self.payType == TypeNone){
        [self showToast:@"请选择一种付款方式"];
        return;
    }
houweibin committed
498 499 500 501 502 503 504 505
    if(self.checkout.shippingRate == nil){
        [self showToast:@"请先选择配送方式"];
        return;
    }
    if(self.checkout.webCheckoutURL == nil){
        [self showToast:@"未成功创建支付链接"];
        return;
    }
506 507
    //不同的支付方式
    switch (self.payType) {
houweibin committed
508
        case TypeWebpay:
509 510 511 512 513 514 515 516 517 518 519
            [self goToWebPay];
            break;
        case TypeAlipay:
            [self requestAliPay];
            break;
        case TypeWechatPay:
            [self requestWeChatPay];
            break;
        default:
            break;
    }
houweibin committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
}

//设置配送费到订单
-(void)setShippingToCheckout:(BUYShippingRate *)shippingRate{
    if(self.checkout == nil){
        return;
    }
    if(shippingRate == nil){
        return;
    }
    [self.checkout setShippingRate:shippingRate];
    [self requestUpdateCheckout:self.checkout isCacheCheckout:NO];
}


-(BOOL)checkAddress:(BUYAddress *)address{
lee committed
536 537 538 539 540
    NSString *errorMsg = [KWMValidateUtil validateAddress:address];
    if (errorMsg) {
        [self showToast:errorMsg];
    }
    return errorMsg != nil;
houweibin committed
541 542 543 544 545 546
}


-(void)requestCreateCheckout:(BUYCheckout *)checkout{
    [self showLoading];
    //[self showToast:@"创建订单中"];
lee committed
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
//    __weak KWMBeforePayVC *weakSelf = self;
//    self.checkoutCreationOperation = [self.client createCheckout:checkout completion:^(NSDictionary *dictionary,BUYCheckout *checkout, NSError *error) {
//        [self hideLoading];
//        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
//        if (error == nil && checkout) {
//            weakSelf.checkout = checkout;
//            //[self showToast:@"创建订单成功"];
//            [weakSelf initData];
//            NSLog(@"saveDict: %@",dictionary);
//            [weakSelf.userDao saveCheckoutCache:dictionary];
//            if(weakSelf.checkout.shippingAddress!=nil){
//                [weakSelf requestShippingData];
//            }}
//        else {
//            [self hideLoading];
//            [weakSelf showError:error];
//            NSLog(@"Error creating checkout: %@", error);
//        }
//    }];
    
    __weak KWMBeforePayVC *this = self;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
lee committed
569 570
    if (self.cartCookie) {
        [manager.requestSerializer setHTTPShouldHandleCookies:NO];
lee committed
571 572 573 574 575 576
        NSString *cookie = [KWMHttpUtil buildRequestCookieString];
        if ([cookie isMatchedByRegex:@"cart=.*?;"]) {
            cookie = [cookie stringByReplacingOccurrencesOfRegex:@"cart=.*?;" withString:[NSString stringWithFormat:@"cart=%@;",self.cartCookie]];
        }else{
            cookie = [NSString stringWithFormat:@"cart=%@; %@",self.cartCookie,cookie];
        }
lee committed
577 578
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
lee committed
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    [manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
        if (!response) {
            return request;
        }
        NSString *checkoutId = [request.URL.absoluteString stringByMatching:@"checkouts/(.*?)\\?" capture:1];
        checkoutId = checkoutId ? checkoutId : [request.URL.absoluteString stringByMatching:@"checkouts/(.*)$" capture:1];
        NSString *URLString = [NSString stringWithFormat:@"https://%@/api/checkouts/%@.json",Shopify_SHOP_DOMAIN,checkoutId];
        NSMutableURLRequest *newReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URLString]];
        [newReq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [newReq setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        NSString *token = [NSString stringWithFormat:@"Basic %@",[[this.client.apiKey dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0]];
        [newReq setValue:token forHTTPHeaderField:@"Authorization"];
        if(this.client.customerToken) {
            [newReq setValue:this.client.customerToken.accessToken forHTTPHeaderField:@"X-Shopify-Customer-Access-Token"];
        }
        // 如果有checkout说明是新订单   直接更新订单地址就好  如果没有checkout说明是旧订单已经有地址所以无需更新
595 596
        // 170922 所有订单全部刷新地址
//        if (checkout || this.cartCookie) {
lee committed
597
            newReq.HTTPMethod = @"PATCH";
lee committed
598 599 600
//        checkout.shippingAddress.identifier = nil;
//        checkout.shippingAddress.provinceCode = nil;
//        checkout.billingAddress = checkout.shippingAddress;
lee committed
601
            [newReq setHTTPBody:[NSJSONSerialization dataWithJSONObject:[checkout jsonDictionaryForCheckout] options:0 error:nil]];
602
//        }
lee committed
603 604 605 606 607 608 609
        return  newReq;
    }];
    
    [manager GET:[NSString stringWithFormat:@"https://%@/checkout",Shopify_SHOP_DOMAIN] parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        [this hideLoading];
        BUYCheckout *checkout = [this.client.modelManager insertCheckoutWithJSONDictionary:responseObject[@"checkout"]];
        this.checkout = checkout;
lee committed
610
        [self flushCheckout:responseObject[@"checkout"]];
lee committed
611
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
lee committed
612 613 614 615 616 617
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[error userInfo][@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableLeaves error:nil];
        if (json[@"errors"][@"checkout"][@"shipping_address"]) {
            [this showToast:@"地址出现问题请重新选择"];
            [this jumpToSelectAddress];
            return;
        }
lee committed
618
        [this hideLoading];
lee committed
619
        [this showError:error];
houweibin committed
620 621 622
    }];
}

lee committed
623 624 625
-(void) flushCheckout:(NSDictionary *) dic {
    [self initData];
    [self.userDao saveCheckoutCache:dic];
u  
lee committed
626 627
    if (!self.checkout.shippingAddress && self.address) {
        [self kwm_setAddress:self.address];
lee committed
628
    }// else if(self.checkout.shippingAddress && !self.checkout.shippingRate) {
lee committed
629
        [self requestShippingData];
lee committed
630
    //}
lee committed
631 632
}

houweibin committed
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
-(void)requestShippingData{
    if(self.checkout==nil){
        return;
    }
    [self showLoading];
    __weak KWMBeforePayVC *weakSelf = self;
    [self.client getShippingRatesForCheckoutWithToken:self.checkout.token completion:^(NSArray *shippingRates, BUYStatus status, NSError *error) {
        [self hideLoading];
        //自动设置配送
        if (shippingRates && shippingRates.count > 0 && !error) {
            [weakSelf setShippingToCheckout:shippingRates.firstObject];
        }else {
            [self hideLoading];
            [weakSelf showError:error];
            NSLog(@"Failed to retrieve shipping rates: %@", error);
        }
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];
}

-(void)requestUpdateCheckout:(BUYCheckout *)checkout isCacheCheckout:(BOOL)isCacheCheckout{
    [self showLoading];
    __weak KWMBeforePayVC *weakSelf = self;
    [self.client updateCheckout:checkout completion:^(NSDictionary *dictionary, BUYCheckout *checkout, NSError *error) {
        [self hideLoading];
        if (error == nil && checkout) {
            weakSelf.checkout = checkout;
            [weakSelf initData];
            NSLog(@"saveDict: %@", checkout);
            [weakSelf.userDao saveCheckoutCache:dictionary];
        }
        else if(isCacheCheckout){//请求失败,并且为缓存订单更新,重新创建订单
            weakSelf.checkout = nil;
            [weakSelf.userDao deleteCheckoutCache];
            [weakSelf initDefaultData];
        }else{
            [self hideLoading];
            [weakSelf showError:error];
            NSLog(@"Error applying checkout: %@", error);
        }
    }];
}

houweibin committed
676
-(void)requestOrderPayResult{
677
    //微信支付,用户支付后,当用户没有点击完成按钮,而是直接使用home键,或者点击状态栏左上角返回APP订单页面时,微信的回调不会调用,而很容易出现本地订单结果回调丢失的情况,所以需要再确认一次订单是否完成。
houweibin committed
678
    //支付宝暂时没有这种问题。
679 680 681
    if(self.beforePayData && ![KWMStringUtil isEmpty:self.beforePayData.outTradeNo]  && self.checkout){
        NSDictionary *parameters = [KWMPayUtil payResultParameters:self.checkout tradeNo:self.beforePayData.outTradeNo];
        self.beforePayData.outTradeNo = @"";
houweibin committed
682
        __weak KWMBeforePayVC *weakSelf = self;
houweibin committed
683 684 685 686 687 688 689 690 691 692 693
        void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
            //[weakSelf showError:error];
        };
        void(^success)(NSURLSessionDataTask *,KWMCheckoutPayResult *) = ^(NSURLSessionDataTask *task,KWMCheckoutPayResult *result){
            if(!result){
                return;
            }
            if(!result.code || result.code.integerValue != 1000){
                return;
            }
            if(result.data){
694
                //KWMOrderPaid *data = (KWMOrderPaid *)result.data;
houweibin committed
695
                [weakSelf paySuccess];
houweibin committed
696
            }
houweibin committed
697
        };
houweibin committed
698
        [self.api appOrderQuery:parameters success:success failure:failure];
houweibin committed
699 700 701
    }
}

702 703 704 705 706 707 708 709 710 711
//支付宝支付
-(void)requestAliPay{
    NSDictionary *parameters = [KWMPayUtil aliPayParameters:self.checkout];
    __weak KWMBeforePayVC *weakSelf = self;
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
        [weakSelf hideLoading];
        [weakSelf showError:error];
    };
    void(^success)(NSURLSessionDataTask *,KWMCheckoutPayResult *) = ^(NSURLSessionDataTask *task,KWMCheckoutPayResult *result){
        [weakSelf hideLoading];
houweibin committed
712
        if(!(result && result.code)){
713 714
            return;
        }
houweibin committed
715 716 717
        if(result.code.integerValue != 1000){
            NSString *message = [KWMPayUtil payErrorMessage:weakSelf.checkout errorResult:result];
            [weakSelf showDialog:message];
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
            return;
        }
        NSString *alipayData = (NSString *)result.message;
        [KWMPayUtil aliPay:alipayData callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
            NSNumber *statue =  [resultDic objectForKey:@"resultStatus"];
            if (statue.integerValue == 9000) {
                [weakSelf paySuccess];
            }
        }];
    };
    [self.api aliPayUnifiedOrder:parameters success:success failure:failure];
    [self showLoading];
}

//微信支付
-(void)requestWeChatPay{
houweibin committed
735 736 737 738 739
    if (![WXApi isWXAppInstalled]) {
        NSLog(@"WeChat App is not installed!");
        [self showToast:@"您还没有安装微信"];
        return;
    }
740 741 742 743 744 745 746 747
    NSDictionary *parameters = [KWMPayUtil wechatPayParameters:self.checkout];
    __weak KWMBeforePayVC *weakSelf = self;
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
        [weakSelf hideLoading];
        [weakSelf showError:error];
    };
    void(^success)(NSURLSessionDataTask *,KWMCheckoutPayResult *) = ^(NSURLSessionDataTask *task,KWMCheckoutPayResult *result){
        [weakSelf hideLoading];
houweibin committed
748
        if(!(result && result.code)){
749 750
            return;
        }
houweibin committed
751 752 753
        if(result.code.integerValue != 1000){
            NSString *message = [KWMPayUtil payErrorMessage:weakSelf.checkout errorResult:result];
            [weakSelf showDialog:message];
754 755 756 757 758
            return;
        }
        if(result.data){
            KWMWechatPayData *data = (KWMWechatPayData *)result.data;
            [KWMPayUtil weChatPay:data];
759
            weakSelf.beforePayData.outTradeNo = data.outTradeNo;
760 761 762 763 764 765 766 767 768 769 770 771 772
        }
    };
    [self.api wechatPayUnifiedOrder:parameters success:success failure:failure];
    [self showLoading];
}

-(void)goToWebPay{
    KWMCheckoutWebViewVC *checkoutVC = (KWMCheckoutWebViewVC *)[KWMBaseVC findControllerBy:[KWMCheckoutWebViewVC kwmTag] fromStoryboard:@"ShopCart"];
    checkoutVC.payURL = self.checkout.webCheckoutURL;
    [self.navigationController pushViewController:checkoutVC animated:YES];
}

-(void)paySuccess{
lee committed
773
    [self clearCheckout];
774
    KWMPaySuccessVC *successVC = (KWMPaySuccessVC *)[KWMBaseVC findControllerBy:[KWMPaySuccessVC kwmTag] fromStoryboard:@"ShopCart"];
775
    successVC.paidCheckout = self.checkout;
776 777 778
    [self.navigationController pushViewController:successVC animated:YES];
}

779

lee committed
780 781
-(void) clearCheckout {
    self.cartCookie = nil;
782 783 784 785 786 787
    [KWMHttpUtil deleteCookie:@"cart"];
//    [[KWMShoppingCart sharedInstance] clearCartWithCallback:^(NSError *error, KWMCartResult *cart) {
////        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [KWMHttpUtil deleteCookie:@"cart"];
////        });
//    }];
u  
lee committed
788 789
//    [KWMHttpUtil deleteCookie:@"cart"];
//    [[KWMShopCartData alloc] removeAllItems];
lee committed
790 791 792
    [self.userDao deleteCheckoutCache];
}

793

houweibin committed
794
@end