KWMBeforePayVC.m 25.5 KB
Newer Older
houweibin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//
//  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"
#import "KWMPaySuccessVC.h"
#import "KWMShopCartModel.h"
#import "KWMStringUtil.h"
#import "KWMCheckoutWebViewVC.h"
#import "KWMPaySuccessVC.h"
#import "KWMStringUtil.h"
#import "UIColor+SAMAdditions.h"
lee committed
19
#import <RegexKitLite/RegexKitLite.h>
lee committed
20
#import "KWMHttpUtil.h"
lee committed
21
#import "KWMValidateUtil.h"
22
#import "KWMPayUtil.h"
houweibin committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

@interface KWMBeforePayVC ()
@property (nonatomic) BUYCustomer *customer;

@end

@implementation KWMBeforePayVC

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

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

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
houweibin committed
43
    [self validateOrderPayResult];
houweibin committed
44 45 46 47 48 49
    [self initDefaultData];
}

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

-(void)dealloc{
    //注销支付成功广播接收者
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self
                                  name:KWMPaySuccess
                                object:nil];
}

-(void)setPayType:(KWMPayType)payType{
    _payType = payType;
houweibin committed
67 68 69 70 71 72 73
    //web支付,隐藏选择支付栏
    if(payType == TypeWebpay){
        self.heightPayType.constant = 0;
        self.vPayType.hidden = YES;
    }else{
        self.lbPayType.text = [KWMPayUtil payTypeString:payType];
    }
houweibin committed
74 75 76 77 78 79 80 81 82 83 84
}

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

lee committed
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
- (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
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
//因为没有地址后进入的地址页面
-(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];
}

159 160 161 162
-(void)kwm_onSelectPayType:(KWMPayType)payType{
    self.payType = payType;
}

houweibin committed
163 164 165 166 167 168 169 170 171 172 173 174 175
- (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;
176
        if(address.province){ //省份有可能为空
houweibin committed
177
            //城市 省份
178
            _lbAddress.text = [NSString stringWithFormat:@"%@, %@, %@",address.city,address.province,address.country];
houweibin committed
179 180
        }else{
            //具体地址 补充
181
            _lbAddress.text = [NSString stringWithFormat:@"%@, %@",address.city,address.country];
houweibin committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        }
        _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
215 216
//        self.lbTotalPrice.text =  [NSString stringWithFormat:@"¥%@",[KWMStringUtil getEUR2CNYstring:self.checkout.totalPrice]];
        self.lbTotalPrice.text = self.checkout.totalPrice.priceValueFormatted;
houweibin committed
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    }
}

- (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
288 289
//    直接使用session cart所以不需要init了之后可以做代码清除
//    [self initBuyCart];
houweibin committed
290
    //如果已登录
lee committed
291 292
//    if(self.cart && self.customer){
    if(self.customer){
houweibin committed
293
        
lee committed
294 295 296 297 298 299 300 301 302 303 304 305
//        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
306
        NSDictionary *checkoutCache = [self.userDao checkOutCache];
lee committed
307
        BUYCheckout *checkout = nil;
lee committed
308
        if (!checkoutCache || self.cartCookie) {
lee committed
309
            checkout = [[BUYCheckout alloc] initWithModelManager:self.client.modelManager JSONDictionary:nil];
houweibin committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
        }
        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;
//        self.client.urlScheme = @"CemaroseApp://";
lee committed
330 331 332 333 334 335 336 337 338
        // 走session的情况下应该不存在update 只是update cart自动会update到checkout
//        if(checkoutCache){
            // 更新订单
//            [self requestUpdateCheckout:checkout isCacheCheckout:YES];
//        }else{
            // 申请将session cart转成checkout
        [self requestCreateCheckout:checkout];
//            
//        }
houweibin committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    }
}



- (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"];
367
    typeVC.delegate = self;
houweibin committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    [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];
}

//选择配送方式页面
-(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;
    }
424 425 426 427
    if(self.payType == TypeNone){
        [self showToast:@"请选择一种付款方式"];
        return;
    }
houweibin committed
428 429 430 431 432 433 434 435
    if(self.checkout.shippingRate == nil){
        [self showToast:@"请先选择配送方式"];
        return;
    }
    if(self.checkout.webCheckoutURL == nil){
        [self showToast:@"未成功创建支付链接"];
        return;
    }
436 437
    //不同的支付方式
    switch (self.payType) {
houweibin committed
438
        case TypeWebpay:
439 440 441 442 443 444 445 446 447 448 449
            [self goToWebPay];
            break;
        case TypeAlipay:
            [self requestAliPay];
            break;
        case TypeWechatPay:
            [self requestWeChatPay];
            break;
        default:
            break;
    }
houweibin committed
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
}

//设置配送费到订单
-(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
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    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
488 489 490 491 492 493
}


-(void)requestCreateCheckout:(BUYCheckout *)checkout{
    [self showLoading];
    //[self showToast:@"创建订单中"];
lee committed
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
//    __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
516 517
    if (self.cartCookie) {
        [manager.requestSerializer setHTTPShouldHandleCookies:NO];
lee committed
518 519 520 521 522 523
        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
524 525
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
lee committed
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    [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
542
        if (checkout || this.cartCookie) {
lee committed
543 544 545 546 547 548 549 550 551 552 553 554
            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
555
        if(this.checkout.shippingAddress && !this.checkout.shippingRate) {
lee committed
556
            [this requestShippingData];
houweibin committed
557
        }
lee committed
558
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
lee committed
559
        [this hideLoading];
lee committed
560
        [this showError:error];
houweibin committed
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
    }];
}

-(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
607 608 609 610
-(void)validateOrderPayResult{
    //微信支付,用户支付后,当用户没有点击完成按钮,而是直接使用home键,或者点击状态栏左上角返回APP订单页面时,微信的回调不会调用,而很容易出现订单结果丢失的情况,所以需要再确认一次订单是否完成。
    //支付宝暂时没有这种问题。
    if(self.beforePayData && self.beforePayData.wechatPayData){
houweibin committed
611 612 613 614 615
        self.beforePayData.wechatPayData = nil;
        __weak KWMBeforePayVC *weakSelf = self;
        [self.client getCompletionStatusOfCheckoutWithToken:self.checkout.token completion:^(BUYStatus status, NSError * _Nullable error) {
            if (!error && status) {
                [weakSelf paySuccess];
houweibin committed
616
            }
houweibin committed
617
        }];
houweibin committed
618 619 620
    }
}

621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
//支付宝支付
-(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){
            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{
    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
669
            weakSelf.beforePayData.wechatPayData = data;
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
        }
    };
    [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{
    KWMPaySuccessVC *successVC = (KWMPaySuccessVC *)[KWMBaseVC findControllerBy:[KWMPaySuccessVC kwmTag] fromStoryboard:@"ShopCart"];
    [self.navigationController pushViewController:successVC animated:YES];
}


houweibin committed
688 689 690 691 692
//判断订单是否支付
-(void)requestCheckPay:(BUYCheckout *)checkout{
    [self showLoading];

}
houweibin committed
693 694 695


@end