KWMBeforePayVC.m 27.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 28

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

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

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

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

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

lee committed
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
- (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;
                [this showToast:@"更新地址成功"];
                
                [this initData];
//                [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 163 164 165 166 167
//因为没有地址后进入的地址页面
-(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_addedDiscount:(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];
}

168 169 170 171
-(void)kwm_onSelectPayType:(KWMPayType)payType{
    self.payType = payType;
}

houweibin committed
172 173 174 175 176 177 178 179 180 181 182 183 184
- (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;
185
        if(address.province){ //省份有可能为空
houweibin committed
186
            //城市 省份
187
            _lbAddress.text = [NSString stringWithFormat:@"%@, %@, %@",address.city,address.province,address.country];
houweibin committed
188 189
        }else{
            //具体地址 补充
190
            _lbAddress.text = [NSString stringWithFormat:@"%@, %@",address.city,address.country];
houweibin committed
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
        }
        _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 = @"请先选择地址";
    }

    //优惠码
    if(self.checkout.discount!=nil){
        self.lbDiscount.text = self.checkout.discount.code;
    }else{
        self.lbDiscount.text = @"请输入优惠码";
    }
    //礼品卡
    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
224 225
//        self.lbTotalPrice.text =  [NSString stringWithFormat:@"¥%@",[KWMStringUtil getEUR2CNYstring:self.checkout.totalPrice]];
        self.lbTotalPrice.text = self.checkout.totalPrice.priceValueFormatted;
houweibin committed
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
    }
}

- (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
297 298
//    直接使用session cart所以不需要init了之后可以做代码清除
//    [self initBuyCart];
houweibin committed
299
    //如果已登录
lee committed
300 301
//    if(self.cart && self.customer){
    if(self.customer){
houweibin committed
302
        
lee committed
303 304 305 306 307 308 309 310 311 312 313 314
//        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];
//        }
houweibin committed
315
        NSDictionary *checkoutCache = [self.userDao checkOutCache];
lee committed
316
        BUYCheckout *checkout = nil;
lee committed
317
        if (!checkoutCache || self.cartCookie) {
lee committed
318
            checkout = [[BUYCheckout alloc] initWithModelManager:self.client.modelManager JSONDictionary:nil];
houweibin committed
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        }
        if(self.address){
            if([self checkAddress:self.address]){
                KWMSelectAddressVC *addressVC = (KWMSelectAddressVC *)[KWMBaseVC findControllerBy:[KWMSelectAddressVC kwmTag] fromStoryboard:@"ShopCart"];
                addressVC.checkout = checkout;
                addressVC.delegate = self;
                [self.navigationController pushViewController:addressVC animated:YES];
                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;
        }
        checkout.email = self.customer.email;
338
        checkout.customerId = self.customer.identifier;
houweibin committed
339
//        self.client.urlScheme = @"CemaroseApp://";
lee committed
340 341 342 343 344 345 346 347 348
        // 走session的情况下应该不存在update 只是update cart自动会update到checkout
//        if(checkoutCache){
            // 更新订单
//            [self requestUpdateCheckout:checkout isCacheCheckout:YES];
//        }else{
            // 申请将session cart转成checkout
        [self requestCreateCheckout:checkout];
//            
//        }
houweibin committed
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
    }
}



- (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;
    }
    KWMPayTypeVC *typeVC = (KWMPayTypeVC *)[KWMBaseVC findControllerBy:[KWMPayTypeVC kwmTag] fromStoryboard:@"ShopCart"];
377
    typeVC.delegate = self;
houweibin committed
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
    [self.navigationController pushViewController:typeVC animated:YES];
}

//优惠码页面
-(void)onClickDiscount:(id)sender{
    if(self.checkout == nil){
        [self showToast:@"未成功创建订单"];
        return;
    }
    KWMDiscountVC *discountVC = (KWMDiscountVC *)[KWMBaseVC findControllerBy:[KWMDiscountVC kwmTag] fromStoryboard:@"ShopCart"];
    discountVC.checkout = self.checkout;
    discountVC.delegate = self;
    [self.navigationController pushViewController:discountVC animated:YES];
}

//礼品卡页面
-(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
404 405 406 407 408
    
//清关信息填写页面
-(void)onClickCustomsClearance:(id)sender{
    
}
houweibin committed
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

//选择配送方式页面
-(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;
    }
439 440 441 442
    if(self.payType == TypeNone){
        [self showToast:@"请选择一种付款方式"];
        return;
    }
houweibin committed
443 444 445 446 447 448 449 450
    if(self.checkout.shippingRate == nil){
        [self showToast:@"请先选择配送方式"];
        return;
    }
    if(self.checkout.webCheckoutURL == nil){
        [self showToast:@"未成功创建支付链接"];
        return;
    }
451 452
    //不同的支付方式
    switch (self.payType) {
houweibin committed
453
        case TypeWebpay:
454 455 456 457 458 459 460 461 462 463 464
            [self goToWebPay];
            break;
        case TypeAlipay:
            [self requestAliPay];
            break;
        case TypeWechatPay:
            [self requestWeChatPay];
            break;
        default:
            break;
    }
houweibin committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
}

//设置配送费到订单
-(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
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    NSString *errorMsg = [KWMValidateUtil validateAddress:address];
    if (errorMsg) {
        [self showToast:errorMsg];
    }
    return errorMsg != nil;
//    if(address == nil){
//        [self showToast:@"您的地址尚未有任何地址,请前往选择地址"];
//        return YES;
//    }else if([KWMStringUtil isEmpty:address.firstName] && [KWMStringUtil isEmpty:address.lastName]){
//        [self showToast:@"您的地址缺少收件人姓名,请前往完善地址"];
//        return YES;
//    }else if([KWMStringUtil isEmpty:address.city]){
//        [self showToast:@"您的地址缺少所在城市,请前往完善地址"];
//        return YES;
//    }else if([KWMStringUtil isEmpty:address.zip]){
//        [self showToast:@"您的地址缺少邮政编码,请前往完善地址"];
//        return YES;
//    }else if([KWMStringUtil isEmpty:address.phone]){
//        [self showToast:@"您的地址缺少收件人电话号码,请前往完善地址"];
//        return YES;
//    }
//    return NO;
houweibin committed
503 504 505 506 507 508
}


-(void)requestCreateCheckout:(BUYCheckout *)checkout{
    [self showLoading];
    //[self showToast:@"创建订单中"];
lee committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
//    __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
531 532
    if (self.cartCookie) {
        [manager.requestSerializer setHTTPShouldHandleCookies:NO];
lee committed
533 534 535 536 537 538
        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
539 540
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
lee committed
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    [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说明是旧订单已经有地址所以无需更新
lee committed
557
        if (checkout || this.cartCookie) {
lee committed
558 559 560 561 562 563 564 565 566 567 568 569
            newReq.HTTPMethod = @"PATCH";
            [newReq setHTTPBody:[NSJSONSerialization dataWithJSONObject:[checkout jsonDictionaryForCheckout] options:0 error:nil]];
        }
        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;
        [this initData];
        [this.userDao saveCheckoutCache:responseObject[@"checkout"]];
lee committed
570
        if(this.checkout.shippingAddress && !this.checkout.shippingRate) {
lee committed
571
            [this requestShippingData];
houweibin committed
572
        }
houweibin committed
573 574
        //排除已被支付的checkout的可能性
        [this requestOrderPayResult];
lee committed
575
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
lee committed
576
        [this hideLoading];
lee committed
577
        [this showError:error];
houweibin committed
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
    }];
}

-(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
624
-(void)requestOrderPayResult{
houweibin committed
625 626
    //微信支付,用户支付后,当用户没有点击完成按钮,而是直接使用home键,或者点击状态栏左上角返回APP订单页面时,微信的回调不会调用,而很容易出现订单结果丢失的情况,所以需要再确认一次订单是否完成。
    //支付宝暂时没有这种问题。
houweibin committed
627 628 629 630
    //另外用到的情况:上次被支付的订单,因某些突发原因没从缓存清除。
    //if(self.beforePayData && self.beforePayData.wechatPayData && self.checkout){
    if(self.checkout){
        NSDictionary *parameters = [KWMPayUtil payResultParameters:self.checkout];
houweibin committed
631 632
        self.beforePayData.wechatPayData = nil;
        __weak KWMBeforePayVC *weakSelf = self;
houweibin committed
633 634 635 636 637 638 639 640 641 642 643 644
        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){
                KWMOrderPaid *data = (KWMOrderPaid *)result.data;
houweibin committed
645
                [weakSelf paySuccess];
houweibin committed
646
            }
houweibin committed
647
        };
houweibin committed
648
        [self.api appOrderQuery:parameters success:success failure:failure];
houweibin committed
649 650 651
    }
}

652 653 654 655 656 657 658 659 660 661 662 663 664 665
//支付宝支付
-(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];
        if(!result){
            return;
        }
        if(!result.code || result.code.integerValue != 1000){
u  
lee committed
666
            NSLog(@"error: %@",result.message);
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
            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
684 685 686 687 688
    if (![WXApi isWXAppInstalled]) {
        NSLog(@"WeChat App is not installed!");
        [self showToast:@"您还没有安装微信"];
        return;
    }
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    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];
        if(!result){
            return;
        }
        if(!result.code || result.code.integerValue != 1000){
            return;
        }
        if(result.data){
            KWMWechatPayData *data = (KWMWechatPayData *)result.data;
            [KWMPayUtil weChatPay:data];
houweibin committed
706
            weakSelf.beforePayData.wechatPayData = data;
707 708 709 710 711 712 713 714 715 716 717 718 719
        }
    };
    [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
720
    [self clearCheckout];
721 722 723 724
    KWMPaySuccessVC *successVC = (KWMPaySuccessVC *)[KWMBaseVC findControllerBy:[KWMPaySuccessVC kwmTag] fromStoryboard:@"ShopCart"];
    [self.navigationController pushViewController:successVC animated:YES];
}

725

lee committed
726 727
-(void) clearCheckout {
    self.cartCookie = nil;
728 729 730 731 732 733
    [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
734 735
//    [KWMHttpUtil deleteCookie:@"cart"];
//    [[KWMShopCartData alloc] removeAllItems];
lee committed
736 737 738
    [self.userDao deleteCheckoutCache];
}

739

houweibin committed
740
@end