CNLivePayCostNetwork.m 41.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 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 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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 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 215 216 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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 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 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 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 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 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 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 607 608 609 610 611 612 613 614 615 616 617 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 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
//
//  CNLivePayCostNetwork.m
//  CNLivePayCostModule
//
//  Created by open on 2022/5/13.
//

#import "CNLivePayCostNetwork.h"
#import <CNLiveBaseTools/CNLiveTimeTools.h>
#import "CNLivePayCostModel.h"

static NSString *const CNLiveWillBecomeActivePaycostForOrderNotification = @"CNLiveWillBecomeActivePaycostForOrderNotification";
static NSString *const CNLiveWillBecomeActivePaycostForGroupNotification = @"CNLiveWillBecomeActivePaycostForGroupNotification";
static NSString *const CNLiveWillBecomeActivePaycostForTickeNotification = @"CNLiveWillBecomeActivePaycostForTickeNotification";
static NSString *const CNLiveWillBecomeActivePaycostForScanNotification = @"CNLiveWillBecomeActivePaycostForScanNotification";
static NSString *const CNLiveWillBecomeActivePaycostForSHShopNotification = @"CNLiveWillBecomeActivePaycostForSHShopNotification";

#define CNUMSPayWithPrePayApiContentURL   (@"https://apiumspay.cnlive.com/app/prePay")
#define CNUMSPayWithBalancePayApiContentURL   (@"https://apiumspay.cnlive.com/app/balancePay")

@implementation CNLivePayCostNetwork

+(instancetype)sharePayCostNetWork
{
    static CNLivePayCostNetwork * payCostNetWork;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        payCostNetWork = [[CNLivePayCostNetwork alloc] init];
    });
    return payCostNetWork;
}

#pragma mark = 生成预支付订单

/// 调用维金支付之前的预支付订单
/// @param orderId 订单id
/// @param body 订单信息
/// @param price 价格
/// @param coupon_fee 优惠券金额
/// @param balance_fee 余额金额
/// @param notify_url 服务端回调地址
/// @param type 支付方式 3:支付宝,4:余额,9:云闪付
/// @param threeType 支付类型
/// @param frmId 渠道id
/// @param completerBlock 返回
+(void)requestWithUMSPayForPrePayWithOrderId:(NSString *)orderId
                                        Body:(NSString *)body
                                       Price:(NSString *)price
                                   CouponFee:(NSString *)coupon_fee
                                  BalanceFee:(NSString *)balance_fee
                                   NotifyUrl:(NSString *)notify_url
                                        Type:(CNLivePayCostPayType)type
                                ThreePayType:(CNLivePayCostThreePayType)threeType
                                       FrmId:(NSString *)frmId
                                    PassWord:(NSString *)password
                              CompleterBlcok:(void(^)(NSInteger statue))completerBlock
{
    NSString * notifyUrls = threeType == CNLivePayCostThreePayTypeTicke ? CNJSFYNotifyUrl: cn_API_Host(@"/Daren/pay/newNotifyPay.action");

//    (type == CNLivePayCostPayTypeWeChatPay ? CNWeChatPayUrl : type == CNLivePayCostPayTypeAliPay ? CNAliPayUrl : CNUnionPayUrl);
    
    //上海电商 & 电商 需要特殊的回调地址
    if (!CNLiveStringIsEmpty(notify_url)
        && (threeType == CNLivePayCostThreePayTypeSHSop || threeType == CNLivePayCostThreePayTypeShop)) notifyUrls = notify_url;
    
    if (type == CNLivePayCostPayTypeWeChatPay) {
        
        NSString * path = [NSString stringWithFormat:@"pages/pays/pay/pay?appId=%@&body=%@&out_trade_no=%@&user_id=%@&total_fee=%@&notify_url=%@&type=1&&frmId=ios&&page_url=%@&&coupon_fee=%@&&balance_fee=%@",AppId,body,orderId,CNUserShareModel.uid?CNUserShareModel.uid:@"",price,notifyUrls,notify_url,coupon_fee,balance_fee];
        WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
        launchMiniProgramReq.userName = @"gh_061b347b32c1";  //拉起的小程序的username
        launchMiniProgramReq.path = path;
        launchMiniProgramReq.miniProgramType = [CNLiveEnvironmentManager manager].isTestEnvironment?WXMiniProgramTypePreview:WXMiniProgramTypeRelease;
        [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
            
        }];
    }else if (type == CNLivePayCostPayTypeWjjPay) {
        
        NSString * desc = threeType == CNLivePayCostThreePayTypeScren?@"扫码支付":body;
        
        NSDictionary * paramDict = @{
            @"appId":AppId,
            @"user_id":CNUserShareModel.uid?CNUserShareModel.uid:@"",
            @"out_trade_no":orderId,
            @"body":desc,
            @"coupon_fee":coupon_fee,
            @"balance_fee":price,
            @"notify_url":notifyUrls,
            @"page_url":@"",
            @"type":@"4",
            @"password":[NSString md5String:password],
            @"frmId":@"ios"
        };
        [CNLiveNetworking setAllowRequestDefaultArgument:YES];
        [CNLiveNetworking setupShowDataResult:YES];
        [CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:CNUMSPayWithBalancePayApiContentURL Param:paramDict CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
            [QMUITips hideAllToastInView:AppKeyWindow animated:YES];
            long errorCode = [responseObject longValueForKey:@"errorCode" default:100];
            NSString * errorMessage = [responseObject stringValueForKey:@"errorMessage" default:@""];
            if (errorCode == 0) {
                if (completerBlock) completerBlock(0);
            }else{
                [QMUITips showError:[errorMessage isNotBlank]?errorMessage:@"支付失败" inView:AppKeyWindow hideAfterDelay:1.5];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (completerBlock) {
                        if (errorCode == 100011) completerBlock(2);
                        if (errorCode == 100010) completerBlock(1);
                        if (errorCode != 100010 && errorCode != 100011) completerBlock(3);
                    }
                });
            }
        }];
        
    }else if (type == CNLivePayCostPayTypeAliPay) {
        
        NSString * desc = threeType == CNLivePayCostThreePayTypeScren?@"扫码支付":body;
        
        NSDictionary * paramDict = @{
                                     @"appId":AppId,
                                     @"user_id":CNUserShareModel.uid?CNUserShareModel.uid:@"",
                                     @"out_trade_no":orderId,
                                     @"body":desc,
                                     @"total_fee":price,
                                     @"coupon_fee":coupon_fee,
                                     @"balance_fee":balance_fee,
                                     @"notify_url":notifyUrls,
                                     @"page_url":@"",
                                     @"type":@"3",
                                     @"frmId":frmId
                                     };
        [CNLiveNetworking setupShowResult:YES];
        [CNLiveNetworking setupShowDataResult:NO];
        [CNLiveNetworking setAllowRequestDefaultArgument:YES];
        [CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:CNUMSPayWithPrePayApiContentURL Param:paramDict CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
            [CNLivePayCostNetwork payCost_chooseRequestWithResponseObject:responseObject Error:error isData:YES CompleterBlock:^(id responseObject, NSInteger errorCode) {
                if (responseObject) {
                    NSString *payDataJsonStr = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
                    [UMSPPPayUnifyPayPlugin payWithPayChannel:CHANNEL_ALIMINIPAY payData:payDataJsonStr callbackBlock:^(NSString *resultCode, NSString *resultInfo) {
                        if (completerBlock) {
                            if ([resultCode isEqualToString:@"0000"]) completerBlock(0);
                            if ([resultCode isEqualToString:@"1000"]) completerBlock(3);//余额支付取消支付 code1000
                        }
                        
                    }];
                }
            }];
        }];
    }else if (type == CNLivePayCostPayTypeUnionPay) {
        NSString * desc = threeType == CNLivePayCostThreePayTypeScren?@"扫码支付":body;
        
        NSDictionary * paramDict = @{
                                     @"appId":AppId,
                                     @"user_id":CNUserShareModel.uid?CNUserShareModel.uid:@"",
                                     @"out_trade_no":orderId,
                                     @"body":desc,
                                     @"total_fee":price,
                                     @"coupon_fee":coupon_fee,
                                     @"balance_fee":balance_fee,
                                     @"notify_url":notifyUrls,
                                     @"page_url":@"",
                                     @"type":@"9",
                                     @"frmId":frmId
                                     };
        [CNLiveNetworking setupShowResult:YES];
        [CNLiveNetworking setupShowDataResult:NO];
        [CNLiveNetworking setAllowRequestDefaultArgument:YES];
        [CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:CNUMSPayWithPrePayApiContentURL Param:paramDict CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
            [CNLivePayCostNetwork payCost_chooseRequestWithResponseObject:responseObject Error:error isData:YES CompleterBlock:^(id responseObject, NSInteger errorCode) {
                if (responseObject) {
                    NSString *payDataJsonStr = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
                    [UMSPPPayUnifyPayPlugin cloudPayWithURLSchemes:TestEnvironment?@"CNLiveNetAddTestUnionPaySchems":@"CNLiveNetAddUnionPaySchems" payData:payDataJsonStr viewController:[CNLivePayCostNetwork paycost_navigationViewController] callbackBlock:^(NSString *resultCode, NSString *resultInfo) {
                        if (completerBlock) {
                            if ([resultCode isEqualToString:@"0000"]) completerBlock(0);
                            if ([resultCode isEqualToString:@"1000"]) completerBlock(3);//余额支付取消支付 code1000
                        }
                    }];
                }
            }];
        }];
    }
}


#pragma mark = 以下为老接口

/**
 拉起支付接口,调起支付动作

 @param groupId 群组 id
 @param price  价钱
 @param fundsId 活动 ID
 @param completerBlock  返回
 */
-(void)requestActiveGroupPayInfoWithGroupId:(NSString *)groupId
                   CNLiveActiveGroupPayType:(CNLivePayCostPayType)payType
              CNLiveActiveGroupThreePayType:(CNLivePayCostThreePayType)threeType
                                       Type:(CNLivePayCostType)type
                                    PriceId:(NSString *)price
                                       Desc:(NSString *)desc
                                     Expand:(NSString *)expand
                                  NotifyUrl:(NSString *)notifyUrl
                                       jsfy:(BOOL)jsfy
                                   PassWord:(NSString *)password
                                    FundsId:(NSString *)fundsId
                                     Attach:(NSDictionary *)attach
                                     FormVC:(UIViewController *)formVC
                             CompleterBlcok:(void(^)(NSInteger statue))completerBlock
{
    

    
    if ((threeType == CNLivePayCostThreePayTypeTicke //门票
         || threeType == CNLivePayCostThreePayTypeScren
         || threeType == CNLivePayCostThreePayTypeOrder
         || threeType == CNLivePayCostThreePayTypeSHSop
         ) && payType != CNLivePayCostPayTypeWjjPay) {
        
        self.orderId = groupId;
        CNLivePayType type = payType == CNLivePayCostPayTypeWeChatPay ? CNLivePayCostPayTypeWeChatPay : payType == CNLivePayCostPayTypeAliPay ? CNLivePayCostPayTypeAliPay : CNLivePayCostPayTypeUnionPay;
        
        NSString * accountString = payType == CNLivePayCostPayTypeWeChatPay ? WXAccount : payType == CNLivePayCostPayTypeAliPay ? @"ztsx" : @"ztyl";
    
        
        if ([[CNLivePayCostModel sharePayCostModel].protocol pushActivePaymentNewPaycostWayWithModthod] && type != CNLivePayCostTypeHtml) {
            
            NSString * p = [NSString stringWithFormat:@"%d",(NSInteger)([price floatValue]*100)];
            
            [CNLivePayCostNetwork requestWithUMSPayForPrePayWithOrderId:groupId Body:desc Price:p CouponFee:@"0" BalanceFee:@"0" NotifyUrl:notifyUrl Type:payType ThreePayType:threeType FrmId:@"ios" PassWord:@"" CompleterBlcok:^(NSInteger statue) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (completerBlock) completerBlock(statue);
                });
            }];
        }else{
            float pri = [price floatValue]*100;
            
            NSString * notifyUrls = jsfy==YES ? CNJSFYNotifyUrl: (payType == CNLivePayCostPayTypeWeChatPay ? CNWeChatPayUrl : payType == CNLivePayCostPayTypeAliPay ? CNAliPayUrl : CNUnionPayUrl);
    
            //上海电商需要特殊的回调地址
            if (!CNLiveStringIsEmpty(notifyUrl)
                && threeType == CNLivePayCostThreePayTypeSHSop) notifyUrls = notifyUrl;
            
            [self requestPayFromWXAndAliPay:type OrderId:groupId Account:accountString PriceId:pri Desc:desc Attach:attach CNLiveActiveGroupThreePayType:threeType NotifyUrl:notifyUrls NetAddUrlSchems:payType == CNLivePayCostPayTypeWeChatPay ? nil : payType == CNLivePayCostPayTypeAliPay ? CNLiveNetAddUrlSchems : CNLiveNetAddUnionPaySchems FormVC:formVC CompleterBlock:^{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (completerBlock) completerBlock(0);
                });
            }];
        }
    }else{
        
        if ([[CNLivePayCostModel sharePayCostModel].protocol pushActivePaymentNewPaycostWayWithModthod] && type != CNLivePayCostTypeHtml) {
            
            NSString * p = [NSString stringWithFormat:@"%d",(NSInteger)([price floatValue]*100)];
            
            NSDictionary * paramDict = @{
                                         @"appId":AppId,
                                         @"user_id":CNUserShareModel.uid?CNUserShareModel.uid:@"",
                                         @"out_trade_no":groupId,
                                         @"body":desc,
                                         @"coupon_fee":@"",
                                         @"balance_fee":p,
                                         @"notify_url":notifyUrl,
                                         @"page_url":@"",
                                         @"type":@"4",
                                         @"password":password,
                                         @"frmId":@"ios"
                                         };
            [CNLiveNetworking setAllowRequestDefaultArgument:YES];
            [CNLiveNetworking setupShowDataResult:YES];
            [CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:CNUMSPayWithBalancePayApiContentURL Param:paramDict CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
                [CNLivePayCostNetwork payCost_chooseRequestWithResponseObject:responseObject Error:error isData:YES CompleterBlock:^(id responseObject, NSInteger errorCode) {
                    if (responseObject) {
                        if (completerBlock) completerBlock(0);
                    }else{
                        if (completerBlock) completerBlock(1);
                    }
                }];
            }];
            
        } else {
            __weak typeof(self) weakSelf = self;
            NSDictionary * paramDict = @{
                                         @"groupId":groupId,
                                         @"sid":CNUserShareModel.uid,
                                         @"price":price,
                                         @"fundsId":fundsId
                                         };
            [CNLiveNetworking setAllowRequestDefaultArgument:YES];
            [CNLiveNetworking setupShowDataResult:YES];
            [CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:CNPayByGroupMembersUrl Param:paramDict CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
    
                if (error == nil && [[responseObject allKeys] containsObject:@"payId"] && responseObject[@"payId"] != nil && ![responseObject[@"payId"] isKindOfClass:[NSNull class]]) {
                    
                    if (payType == CNLivePayCostPayTypeWjjPay) {
                        
                        NSString * toid = threeType == CNLivePayCostTypeOrder ? fundsId : groupId;
                        [self requestActiveGroupWjjPayMentWithFromId:CNUserShareModel.uid Toid:toid Price:[price floatValue] Expand:expand SourceId:[responseObject objectForKey:@"payId"] PayId:responseObject[@"payId"] Desc:desc NotifyUrl:notifyUrl PassWord:password ThreePayType:threeType CompleterBlock:^(NSInteger statue) {
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                if (completerBlock) completerBlock(statue);
                            });
                        }];
                    }else{
                        CNLivePayType type = payType == CNLivePayCostPayTypeWeChatPay ? CNLivePayTypeWeChatPay : payType == CNLivePayCostPayTypeAliPay ? CNLivePayTypeAliPay : CNLivePayTypeUnionpay;
                        
                        NSString * accountString = payType == CNLivePayCostPayTypeWeChatPay ? WXAccount : payType == CNLivePayCostPayTypeAliPay ? @"ztsx" : @"ztyl";
                        
                        float price = [responseObject[@"price"] floatValue]*100;
                        NSString * notifyUrls = jsfy == YES ? CNJSFYNotifyUrl : (payType == CNLivePayCostPayTypeWeChatPay ? CNWeChatPayUrl : payType == CNLivePayCostPayTypeAliPay ? CNAliPayUrl : CNUnionPayUrl);
                        
                        if (!CNLiveStringIsEmpty(notifyUrl)) notifyUrls = notifyUrl;
                        
                        weakSelf.payId = responseObject[@"payId"];
                        
                        [weakSelf requestPayFromWXAndAliPay:type OrderId:responseObject[@"payId"] Account:accountString PriceId:price Desc:desc Attach:@{} CNLiveActiveGroupThreePayType:threeType NotifyUrl:notifyUrls NetAddUrlSchems:payType == CNLivePayCostPayTypeWeChatPay ? nil : payType == CNLivePayCostPayTypeAliPay ? CNLiveNetAddUrlSchems : CNLiveNetAddUnionPaySchems FormVC:formVC CompleterBlock:^{
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                if (completerBlock) completerBlock(0);
                            });
                        }];
                    }
                }else{
                    [QMUITips hideAllToastInView:AppKeyWindow animated:YES];
                    [QMUITips showError:@"预支付失败" inView:AppKeyWindow hideAfterDelay:1.5];
                }
                
                if (error) [QMUITips showError:[error.userInfo objectForKey:NSLocalizedDescriptionKey] inView:AppKeyWindow hideAfterDelay:1.5];
            }];
        }
    }
}
#pragma mark - 网加加余额支付&连带生成预订单

/**
 使用网加加支付调用支付接口

 @param fromId 支付人 ID
 @param toId 受让人 ID
 @param price 价格
 @param expand 扩展字段
 @param sourceId 资源 ID
 @param payId 支付 ID
 @param password 支付密码
 @param completerBlock 支付结果返回
 */
-(void)requestActiveGroupWjjPayMentWithFromId:(NSString *)fromId
                                         Toid:(NSString *)toId
                                        Price:(float)price
                                       Expand:(NSString *)expand
                                     SourceId:(NSString *)sourceId
                                        PayId:(NSString *)payId
                                         Desc:(NSString *)desc
                                    NotifyUrl:(NSString *)notifyUrl
                                     PassWord:(NSString *)password
                                 ThreePayType:(CNLivePayCostThreePayType)threeType
                               CompleterBlock:(void (^)(NSInteger))completerBlock
{
    
    if ([[CNLivePayCostModel sharePayCostModel].protocol pushActivePaymentNewPaycostWayWithModthod]) {
        
        NSString * p = [NSString stringWithFormat:@"%d",(NSInteger)(price*100)];
        
        [CNLivePayCostNetwork requestWithUMSPayForPrePayWithOrderId:payId Body:desc Price:p CouponFee:@"0" BalanceFee:@"0" NotifyUrl:notifyUrl Type:CNLivePayCostPayTypeWjjPay ThreePayType:threeType FrmId:@"ios" PassWord:password CompleterBlcok:^(NSInteger statue) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(statue);
            });
        }];
        
    } else {
        
        [self requestActiveForPrivateKeyWithCompleterBlock:^(NSDictionary * dict) {
            
            NSDictionary * signDict = @{
                @"userId":CNUserShareModel.uid,
                @"platFormId":[[NSBundle mainBundle] bundleIdentifier],
                @"timestamp":[NSString stringWithFormat:@"%ld",(long)[CNLiveTimeTools getNow10NumTimestamp]],
                @"fromId":fromId,
                @"toId":toId,
                @"price":[NSString stringWithFormat:@"%.2f",price],
                @"expand":expand,
                @"sourceId":sourceId
            };
            
            NSMutableDictionary * param =  [[CNLiveEncryptManager manager] validationEncryptWithParams:signDict preValiDic:dict].mutableCopy;
            
            [param addEntriesFromDictionary:@{@"appId":AppId}];
            
            [CNLiveNetworking setupShowDataResult:NO];
            [CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:CNGroupWjjPayWjjPrePaySourceUrl Param:param CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
                
                if (error) {
                    [QMUITips hideAllToastInView:AppKeyWindow animated:YES];
                    if(error.code != 406) [QMUITips showError:[error.userInfo objectForKey:NSLocalizedDescriptionKey] inView:AppKeyWindow hideAfterDelay:2];
                    if (error.code == 406) completerBlock(1);
                    return;;
                }
                
                [CNLivePayCostNetwork payCost_chooseRequestWithResponseObject:responseObject Error:error isData:YES CompleterBlock:^(id responseObject, NSInteger errorCode) {
                    
                    if (responseObject) {
                        NSDictionary * subParamDic = @{
                            @"userId":CNUserShareModel.uid,
                            @"platFormId":[[NSBundle mainBundle] bundleIdentifier],
                            @"timestamp":[NSString stringWithFormat:@"%ld",(long)[CNLiveTimeTools getNow10NumTimestamp]],
                            @"preId":[responseObject objectForKey:@"preId"],
                            @"password":[NSString md5String:password],
                        };
                        
                        NSMutableDictionary * subParam =  [[CNLiveEncryptManager manager] validationEncryptWithParams:subParamDic preValiDic:dict].mutableCopy;
                        
                        [subParam addEntriesFromDictionary:@{@"appId":AppId}];
                        
                        [CNLiveNetworking setupShowResult:YES];
                        [CNLiveNetworking setupShowDataResult:YES];
                        [CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:CNGroupWjjPayWjjSourceUrl Param:subParam CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
                            
                            [QMUITips hideAllToastInView:AppKeyWindow animated:YES];
                            
                            if (error == nil) {
                                
                                completerBlock(0);
                                
                            }else{
                                if (error.code != 414) [QMUITips showError:[error.userInfo objectForKey:NSLocalizedDescriptionKey] inView:AppKeyWindow hideAfterDelay:1.5];
                                if (error.code == 414) completerBlock(2);
                            }
                        }];
                    }else{
                        [QMUITips hideAllTipsInView:AppKeyWindow];
                    }
                }];
            }];
        }];
    }
}

#pragma mark - 获取相关的公钥及随机秘钥
-(void)requestActiveForPrivateKeyWithCompleterBlock:(void (^)(NSDictionary *))completerBlock
{
    NSDictionary * paramDict = @{
                                 @"userId":CNUserShareModel.uid,
                                 @"platFormId":[[NSBundle mainBundle] bundleIdentifier],
                                 @"timestamp":[NSString stringWithFormat:@"%ld",(long)[CNLiveTimeTools getNow10NumTimestamp]]
                                 };
    NSMutableDictionary * param =  [[CNLiveEncryptManager manager] preValidationEncryptWithParams:paramDict].mutableCopy;
    
    [param addEntriesFromDictionary:@{@"appId":AppId}];
    
    [CNLiveNetworking setupShowDataResult:YES];
    [CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:CNGroupReturnEncryptKeyUrl Param:param CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
        
        NSString * publicKey = [responseObject objectForKey:@"publicKey"];
        NSString * randomAesKey = [responseObject objectForKey:@"randomAesKey"];

        if (error == nil) {
            if (publicKey.length != 0 && randomAesKey.length != 0 ) {
                if (completerBlock) completerBlock(responseObject);
            }else{
                [QMUITips hideAllToastInView:AppKeyWindow animated:YES];
                NSString * errorMessage = [responseObject stringValueForKey:@"errorMessage" default:@""];
                [QMUITips showError:[errorMessage isNotBlank]?errorMessage:@"请求失败" inView:AppKeyWindow hideAfterDelay:2];
            }
        }else{
            [QMUITips hideAllToastInView:AppKeyWindow animated:YES];
            [QMUITips showError:[error.userInfo objectForKey:NSLocalizedDescriptionKey] inView:AppKeyWindow hideAfterDelay:2];
        }
    }];
}

#pragma mark - 判断是否有支付密码

/// 判断是否有支付密码
/// @param amount 价格
/// @param completerBlock 查询回调
-(void)requestActiveForPasswordWithLocalAmount:(float)amount
                                CompleterBlock:(void(^)(NSInteger isPassword))completerBlock
{
    NSString *PasswordIsExistingKey = [@"CNPayPasswordIsExisting_" stringByAppendingString:CNUserShareModel.uid];
    
    NSDictionary * paramDict = @{
                                 @"appId":AppId,
                                 @"userId":CNUserShareModel.uid?CNUserShareModel.uid:@""
                                 };
    [CNLiveNetworking setupShowDataResult:YES];
    [CNLiveNetworking requestNetworkWithMethod:CNLiveRequestMethodPOST URLString:CNPasswordIsExistingUrl Param:paramDict CacheType:CNLiveNetworkCacheTypeNetworkOnly CompletionBlock:^(NSURLSessionTask *requestTask, id responseObject, NSError *error) {
        if (error == nil) {
            
            [[NSUserDefaults standardUserDefaults] setObject:@"Existing" forKey:PasswordIsExistingKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            float balance = [[responseObject objectForKey:@"balance"] floatValue];
            if (balance<amount) {
               if (completerBlock) completerBlock(1);
            }else{
                if (completerBlock) completerBlock(2);
            }
            return;
        }
        if (error.code == -1009) {
            [QMUITips hideAllToastInView:AppKeyWindow animated:YES];
            [QMUITips showError:error.userInfo[NSLocalizedDescriptionKey] inView:AppKeyWindow hideAfterDelay:2];
            return;
        }
        if (error.code == 402) {
            [[NSUserDefaults standardUserDefaults] setObject:@"NotExisting" forKey:PasswordIsExistingKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            if (completerBlock) completerBlock(0);
        }
    }];
}

/**
 调起客户端进行支付

 @param type 支付类型
 @param orderId 订单编号
 @param account 授权
 @param price 交钱
 @param desc 描述
 @param notifyUrl 授权回调
 @param netAddUrlSchems 回调
 */
-(void)requestPayFromWXAndAliPay:(CNLivePayType)type
                         OrderId:(NSString *)orderId
                         Account:(NSString *)account
                         PriceId:(int)price
                            Desc:(NSString *)desc
                          Attach:(NSDictionary *)attach
   CNLiveActiveGroupThreePayType:(CNLivePayCostThreePayType)threeType
                       NotifyUrl:(NSString *)notifyUrl
                 NetAddUrlSchems:(NSString *)netAddUrlSchems
                          FormVC:(UIViewController *)formVC
                  CompleterBlock:(void(^)(void))completerBlock;
{
    __weak __typeof(self)weakSelf = self;
    NSString * localKey = @"";
    if (threeType == CNLivePayCostThreePayTypeTicke) localKey = CNLiveWillBecomeActivePaycostForTickeNotification;
    if (threeType == CNLivePayCostThreePayTypeOrder) localKey = CNLiveWillBecomeActivePaycostForOrderNotification;
    if (threeType == CNLivePayCostThreePayTypeScren) localKey =
        CNLiveWillBecomeActivePaycostForScanNotification;
    if (threeType == CNLivePayCostThreePayTypePayment) localKey =CNLiveWillBecomeActivePaycostForGroupNotification;
    if (threeType == CNLivePayCostThreePayTypeSHSop) localKey = CNLiveWillBecomeActivePaycostForSHShopNotification;
    
    BOOL isInstalled = [[CNLivePaySDK sharedCNLivePayManager] isPaymentAppInstalled];
    
    [[NSUserDefaults standardUserDefaults] setObject:(type == CNLivePayTypeUnionpay && !isInstalled) ? @(NO) : @(YES) forKey:localKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    CNLivePayArg *arg = [[CNLivePayArg alloc] init];
    arg.account = account;
    arg.type = type;
    arg.out_trade_no = orderId;
    arg.total_fee = price;
    arg.notify_url = notifyUrl;
    arg.user_id = CNUserShareModel.uid;
    arg.attach = attach != nil ? attach : @{@"plat":@"i"};
    arg.body = desc;

    UITabBarController * vc = (UITabBarController *)AppKeyWindow.rootViewController;
    UINavigationController * cVC = vc.selectedViewController;
    [[CNLivePaySDK sharedCNLivePayManager] pay:arg appScheme:netAddUrlSchems viewController:formVC == nil ? cVC.topViewController : formVC completion:^(CNLivePayResult *cnlivePayResult) {
        [QMUITips hideAllToastInView:AppKeyWindow animated:YES];
        //支付结果回调Block
        if (cnlivePayResult.explain == CNLive_CODE_SUCCESS)
        {//支付成功
            [MobClick event:@"pay_state_success"];
            if (type == CNLivePayTypeUnionpay) {
                if (cnlivePayResult.isPaymentAppInstalled) {
                    NSLog(@"已安装银联App");
                } else {
                    NSLog(@"未安装银联App");
                    if (completerBlock) completerBlock();
                }
            }
        }else if(cnlivePayResult.explain == CNLive_CODE_FAIL_CANCEL)
        {//用户取消
            [MobClick event:@"pay_state_failed"];
            [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:localKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }else if (cnlivePayResult.explain == CNLive_CODE_Failure)
        {//支付失败
            [MobClick event:@"pay_state_failed"];
            [QMUITips showError:@"支付失败" inView:AppKeyWindow hideAfterDelay:1.5];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"CNThirdPayBack"];
            [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:localKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            for (UIViewController *vc in  [[UIApplication sharedApplication] keyWindow].rootViewController.navigationController.viewControllers) {
                if ([vc isKindOfClass:NSClassFromString(@"CNChatViewController")]) {
                    [[CNLivePayCostNetwork paycost_navigationViewController] popToViewController:vc animated:YES];
                    [[NSNotificationCenter defaultCenter] removeObserver:weakSelf];
                    break;
                }
            }
        }else{
            //其他错误
            [MobClick event:@"pay_state_failed"];
            [QMUITips hideAllToastInView:AppKeyWindow animated:YES];
            [QMUITips showError:cnlivePayResult.backDescription inView:AppKeyWindow hideAfterDelay:2];
            [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:localKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }];
}

#pragma mark =========== 对网络返回的结果进行提醒判断 ===========

/// 对放回的结果进行提醒判断
/// @param responseObject 返回数据
/// @param error 错误
/// @param isData 是否取data
/// @param completerBlock 成功
+(void)payCost_chooseRequestWithResponseObject:(id)responseObject Error:(NSError *)error isData:(BOOL)isData CompleterBlock:(void(^)(id responseObject,NSInteger errorCode))completerBlock
{
    if (error) {
        if (error.code == -1009) {
            [QMUITips showError:error.userInfo[@"NSLocalizedDescription"] inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,error.code);
            });
        }else if (error.code == -1004) {
            [QMUITips showError:@"未能连接到服务器" inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,error.code);
            });
        }else if (error.code == 8) {
            [QMUITips showError:error.userInfo[@"NSLocalizedDescription"] inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,error.code);
            });
        }else if (error.code == 500 || error.code == 404
                  || error.code == 503 || error.code == 403) {
            [QMUITips showError:@"服务器异常" inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,error.code);
            });
        }else if (error.code == 400) {
            [QMUITips showError:@"参数错误" inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,error.code);
            });
        }else if (error.code == -1001) {
            [QMUITips showError:@"请求超时" inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,error.code);
            });
        }else if (error.code == 3840) {
            [QMUITips showError:@"返回数据异常" inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,3840);
            });
        }else{
            [QMUITips showError:@"请求失败" inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,-500);
            });
        }
    }else{
        if (responseObject == nil) {
            [QMUITips showError:@"请求失败" inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,-500);
            });
        }else if ([responseObject isKindOfClass:[NSDictionary class]]
                  && ((NSDictionary *)responseObject).allKeys.count == 0) {
            [QMUITips showError:@"请求失败" inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,-500);
            });
        }else if ([responseObject[@"errorMessage"] isKindOfClass:[NSNull class]]) {
            [QMUITips showError:@"请求失败" inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,-500);
            });
        }else if ([responseObject isKindOfClass:[NSDictionary class]]
                  && ((NSDictionary *)responseObject).allKeys.count > 0
                  && [responseObject[@"errorCode"] integerValue] != 0) {
            [QMUITips showError:responseObject[@"errorMessage"] inView:AppKeyWindow hideAfterDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (completerBlock) completerBlock(nil,[responseObject[@"errorCode"] integerValue]);
            });
        }else{
            if (isData) {
                if (responseObject[@"data"] != nil
                    && responseObject[@"data"] != NULL
                    && ![responseObject[@"data"] isKindOfClass:[NSNull class]]
                    && [responseObject[@"data"] isKindOfClass:[NSDictionary class]]
                    && ((NSDictionary *)responseObject[@"data"]).allValues.count > 0) {
                    if (completerBlock) completerBlock(responseObject[@"data"],0);
                }else{
                    NSString * errorMessage = [responseObject stringValueForKey:@"errorMessage" default:@""];
                    if ([errorMessage length] > 0) {
                        [QMUITips showError:errorMessage inView:AppKeyWindow hideAfterDelay:1.5];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            if (completerBlock) completerBlock(nil,-500);
                        });
                    }else{
                        [QMUITips showError:@"请求失败" inView:AppKeyWindow hideAfterDelay:1.5];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            if (completerBlock) completerBlock(nil,-500);
                        });
                    }
                }
            }else{
                if (completerBlock) completerBlock(responseObject,0);
            }
        }
    }
}

// 获取当前活动的navigationcontroller
+ (UINavigationController *)paycost_navigationViewController
{
    if ([[[UIApplication sharedApplication] keyWindow].rootViewController isKindOfClass:[UINavigationController class]])
    {
        return (UINavigationController *)[[UIApplication sharedApplication] keyWindow].rootViewController;
    }
    else if ([[[UIApplication sharedApplication] keyWindow].rootViewController isKindOfClass:[UITabBarController class]])
    {
        UIViewController *selectVc = [((UITabBarController *)[[UIApplication sharedApplication] keyWindow].rootViewController) selectedViewController];
        if ([selectVc isKindOfClass:[UINavigationController class]])
        {
            return (UINavigationController *)selectVc;
        }
    }
    return nil;
}

/// 获取图片
/// @param imageName 图片名称
+(UIImage *)payCost_setImageWithName:(NSString *)imageName
{
    return [CNLivePayCostNetwork cnlive_payCostCommuntGetImageName:imageName bundle:@"CNLivePayCostModule.bundle/CNLivePayCostModule" targetClass:[CNLivePayCostNetwork class]];
}
+ (UIImage *)cnlive_payCostCommuntGetImageName:(NSString *)imageName bundle:(NSString *)bundlePath targetClass:(Class)targetClass {
    NSBundle *bundle = [NSBundle bundleForClass:targetClass];
    NSURL *url = [bundle URLForResource:bundlePath withExtension:@"bundle"];
    if (!url) {
        return [UIImage new];
    }
    NSBundle *targetBundle = [NSBundle bundleWithURL:url];
    if (!targetBundle) {
        return [UIImage new];
    }
    UIImage *image = [UIImage imageNamed:imageName inBundle:targetBundle compatibleWithTraitCollection:nil];
    if (image) {
        return image;
    }else {
        if ([UIImage imageNamed:imageName inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil]) {
            return [UIImage imageNamed:imageName inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
        }else{
            return [UIImage new];
        }
    }
}
@end