KWMAPIManager.m 42.5 KB
Newer Older
houweibin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
//
//  KWMAPIManager.m
//  iXiaoWeiOA
//
//  Created by kevin on 3/14/15.
//  Copyright (c) 2015 kollway. All rights reserved.
//

#import "KWMAPIManager.h"
#import "KWMStringUtil.h"
#import "KWMRequestListResult.h"
#import "KWMBaseModel.h"
#import "KWMUser.h"
#import "NSString+SAMAdditions.h"
#import "KWMAPIManager.h"
#import <UIImageView+WebCache.h>
#import "KWMUserDao.h"
#import "KWMCustomer.h"
#import "KWMCustomerResult.h"
#import "KWMBrandsTypeResult.h"
#import "KWMBrandsTypeModel.h"
lee committed
22 23 24 25
#import "KWMDictionaryResult.h"
#import <RegexKitLite/RegexKitLite.h>
#import <SAMKeychain/SAMKeychain.h>
#import "KWMUserModel.h"
lee committed
26
#import "KWMHttpUtil.h"
lee committed
27 28
#import "KWMHomeDataResult.h"
#import <PPNetworkHelper/PPNetworkHelper.h>
houweibin committed
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



typedef NS_ENUM(NSInteger, KWMHTTPMethod) {
    KWMHTTPMethodGET = 0,
    KWMHTTPMethodPOST,
    KWMHTTPMethodPUT,
    KWMHTTPMethodDELETE
};

@implementation KWMAPIManager

+ (KWMAPIManager *)sharedManager {
    static KWMAPIManager *_sharedManager = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedManager = [[self alloc] init];
    });
    return _sharedManager;
}

- (NSString *)toAbsoluteUrl:(NSString *)relativeUrl {
    if([KWMStringUtil isEmpty:relativeUrl]){
        return self.baseUrl;
    }
    if([relativeUrl rangeOfString:@"http"].location == 0){
        return relativeUrl;
    }
    return [[NSString alloc] initWithFormat:@"%@%@", self.baseUrl, relativeUrl];
}

- (NSString *)baseUrl {
    if(! _baseUrl){
        if (API_HOST_PORT != 8088) {
            _baseUrl = [[NSString alloc] initWithFormat:@"https://%@:%d", API_HOST, API_HOST_PORT];
        }else{
            _baseUrl = [[NSString alloc] initWithFormat:@"https://%@", API_HOST];
        }
    }
    return _baseUrl;
}

/**
 * 根据API返回类型,模型类型创建成功callback
 */
- (void(^)(NSURLSessionDataTask *, id ))buildSuccessCallbackWithResultClass:(Class)requestResultClass
                                                                 modelClass:(Class)modelClass
                                                                    success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                                                                    failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure{
    void(^successCallback)(NSURLSessionDataTask *, id ) =
    ^(NSURLSessionDataTask *task, id jsonDict){
        NSError *error;
        id result = nil;
        @try {
            //#ifdef DEBUG
lee committed
84 85 86
//            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
//            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//            NSLog(@"%@", jsonString);
houweibin committed
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
            //#endif
            result = [[requestResultClass alloc] initWithDictionary:jsonDict modelClass:modelClass error:&error];
        }
        @catch (NSException *e){
            NSLog(@"%@", [e description]);
        }
        @finally{
            [self checkRequestResult:result];
            if(error){
                failure(task, error);
            }else{
                success(task, result);
            }
        }
    };
    return successCallback;
}

/**
 * 检测API返回错误号
 */
- (void)checkRequestResult:(id)requestResult {
    if(! requestResult) {
        return;
    }
    
    NSString *message = nil;
    NSInteger responseCode = 0;
    if([requestResult isKindOfClass:[KWMRequestResult class]]){
        responseCode = ((KWMRequestResult *)requestResult).code;
        message = ((KWMRequestResult *)requestResult).message;
    }else if([requestResult isKindOfClass:[KWMRequestListResult class]]){
        responseCode = ((KWMRequestListResult *)requestResult).code;
        message = ((KWMRequestListResult *)requestResult).message;
    }else{
        return;
    }
    
    switch (responseCode){
        case 1: {
            [[NSNotificationCenter defaultCenter] postNotificationName:KWMReceiverNoLogin object:nil userInfo: nil];
            break;
        }
        default:break;
    }
}

/**
 * 处理列表API的请求参数
 */
- (NSDictionary *)processListAPIParameters:(NSDictionary *)parameters {
    static NSString *KEY_PAGE = @"page";
    static NSString *KEY_PAGE_SIZE = @"pagesize";
    NSMutableDictionary *mutableParameters = [[NSMutableDictionary alloc] initWithDictionary:parameters];
    
    NSAssert((mutableParameters && mutableParameters[KEY_PAGE]), @"required parameter: page");
    
    if(!mutableParameters[KEY_PAGE_SIZE]){
        mutableParameters[KEY_PAGE_SIZE] = @(KWM_PAGE_SIZE).stringValue;
    }
    
    return [[NSDictionary alloc] initWithDictionary:mutableParameters];
}

//账号 密码
//正式
static NSString *const userName = @"868f335328bf6ea61fc94448ed314ace";
static NSString *const password = @"ae6dc70d26e9315f370ebade3e86d21b";

//测试
static NSString *const userNameTest = @"55275437287d63252b80dc5a784b3b8f";
static NSString *const passwordTest = @"9e84aae218c57cdf0762763c4cf5a651";

- (AFHTTPSessionManager *)buildSessionManager{
    
    return [self buildSessionManager:NO];
}

- (AFHTTPSessionManager *)buildSessionManager:(BOOL)isJsonParameter{
    
    NSURL *url = [NSURL URLWithString:self.baseUrl];
    AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:url];
    
    //设置超时时间为10秒
    [sessionManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionManager.requestSerializer.timeoutInterval = 10.f;
    [sessionManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    
    if (isJsonParameter) {
        sessionManager.requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:0];
    }
    
lee committed
180 181
    // 使用系统cookie管理 2017年5月18日  因为改动cart需要使用cookie
//    [[KWMUserDao shareDao] checkSession];
houweibin committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    sessionManager.requestSerializer.HTTPShouldHandleCookies = YES;
    
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
    //测试
    if([TestModel isEqualToString:@"YES"]){
        [sessionManager.requestSerializer setAuthorizationHeaderFieldWithUsername:userNameTest password:passwordTest];
    }
    //正式
    else{
        [sessionManager.requestSerializer setAuthorizationHeaderFieldWithUsername:userName password:password];
    }
    return sessionManager;
}


lee committed
197

houweibin committed
198 199 200 201 202 203 204 205 206 207 208 209 210
- (NSURLSessionDataTask *)startSessionTask:(KWMHTTPMethod)httpMethod
                                   apiPath:(NSString *)apiPath
                                parameters:(NSDictionary *)parameters
                                 filePaths:(NSDictionary *)filePaths
                                    images:(NSArray *)images
                             jsonParameter:(BOOL)isJsonParameter
                                    result:(Class)result
                                     model:(Class)model
                                   success:(void (^)(NSURLSessionDataTask *task, id result))success
                                   failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure{
    
    
    NSAssert((result == [KWMRequestResult class] || result == [KWMRequestListResult class]
211
              || result == [KWMCheckoutPayResult class] 
houweibin committed
212 213 214 215 216 217 218 219 220 221 222
              || result == [KWMCemaroseResult class] || [result isSubclassOfClass:[KWMCemaroseResult class]]),
             @"result class must either be KWMRequestResult or KWMRequestListResult!");
    NSAssert((!model || (model && [model isSubclassOfClass:[JSONModel class]])),
             @"model class must be sub class of JSONModel");
    
    void(^successCallback)(NSURLSessionDataTask *, id ) = [self buildSuccessCallbackWithResultClass:result
                                                                                         modelClass:model
                                                                                            success:success
                                                                                            failure:failure];
    AFHTTPSessionManager *sessionManager = [self buildSessionManager:isJsonParameter];
    //app version code
lee committed
223 224
//    static NSString *KEY_VERSION_CODE = @"version_code";
//    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
houweibin committed
225 226 227 228
    NSMutableDictionary *mutableParameters = [[NSMutableDictionary alloc] initWithDictionary:parameters];
//    mutableParameters[KEY_VERSION_CODE] = build;
    
    //os_version统一添加
lee committed
229
//    static NSString *KEY_OS_VERSION = @"os_version";
houweibin committed
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
//    mutableParameters[KEY_OS_VERSION] = [NSString stringWithFormat:@"ios%@", [UIDevice currentDevice].systemVersion];
    //    NSLog(@"os_version:%@=====", mutableParameters[KEY_OS_VERSION]);
    
    
    if (filePaths != nil && filePaths.count > 0) {
        return [sessionManager POST:apiPath parameters:mutableParameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSEnumerator *e = [filePaths keyEnumerator];
            for (NSString *key in e) {
                NSString *filePath = filePaths[key];
                
                if (![KWMStringUtil isEmpty:filePath]) {
                    if ([fileManager fileExistsAtPath:filePath]) {
                        [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath]
                                                   name:key
                                                  error:nil];
                    }else if([filePath sam_containsString:@"http"]){//网络图片
                        NSURL *url = [[NSURL alloc] initWithString:filePath];
                        [formData appendPartWithFileURL:url
                                                   name:key
                                                  error:nil];
                    }
                    
                }
            }
        } success:successCallback failure:failure];
    }
    
    if (images != nil && images.count > 0) {
        return [sessionManager POST:apiPath parameters:mutableParameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            for (NSInteger i = 0; i < images.count; i++) {
                NSString *filePath = images[i];
                
                if (![KWMStringUtil isEmpty:filePath]
                    && [fileManager fileExistsAtPath:filePath]) {
                    
                    if (images.count == 1) {
                        [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath]
                                                   name:@"image"
                                                  error:nil];
                    }else{
                        [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath]
                                                   name:[NSString stringWithFormat:@"image%@", @(i+1)]
                                                  error:nil];
                    }
                }
            }
        } success:successCallback failure:failure];
    }
    
    if(parameters.allKeys==nil || parameters.allKeys.count==0){
        parameters = nil;
    }
    
    switch (httpMethod) {
        case KWMHTTPMethodGET:{
            return [sessionManager GET:apiPath parameters:parameters success:successCallback failure:failure];
        }
        case KWMHTTPMethodPOST:{
            return [sessionManager POST:apiPath parameters:parameters success:successCallback failure:failure];
        }
        case KWMHTTPMethodPUT:{
            return [sessionManager PUT:apiPath parameters:parameters success:successCallback failure:failure];
        }
        case KWMHTTPMethodDELETE:{
            return [sessionManager DELETE:apiPath parameters:parameters success:successCallback failure:failure];
        }
        default:{
            NSString *reason = [[NSString alloc] initWithFormat:@"Don't use this way to build your NSURLSessionDataTask!"];
            NSAssert(NO, reason);
            return nil;
        }
    }
    
    
    
}

lee committed
311

houweibin committed
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
- (NSURLSessionDataTask *)startSessionTask:(KWMHTTPMethod)httpMethod
                                   apiPath:(NSString *)apiPath
                                parameters:(NSDictionary *)parameters
                                 filePaths:(NSDictionary *)filePaths
                             jsonParameter:(BOOL)isJsonParameter
                                    result:(Class)result
                                     model:(Class)model
                                   success:(void (^)(NSURLSessionDataTask *task, id result))success
                                   failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    
    return [self startSessionTask:httpMethod
                          apiPath:apiPath
                       parameters:parameters
                        filePaths:filePaths
                           images:nil
                    jsonParameter:isJsonParameter
                           result:result
                            model:model
                          success:success
                          failure:failure];
}

u  
lee committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
- (NSURLSessionDataTask *)makeSessionTask:(KWMHTTPMethod)httpMethod
                                   apiPath:(NSString *)apiPath
                                parameters:(NSDictionary *)parameters
                                    result:(Class)result
                                     model:(Class)model
                                   success:(void (^)(NSURLSessionDataTask *task, id result))success
                                   failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    
    void(^successCallback)(NSURLSessionDataTask *, id ) = [self buildSuccessCallbackWithResultClass:result
                                                                                         modelClass:model
                                                                                            success:success
                                                                                            failure:failure];
    AFHTTPSessionManager *sessionManager = [self buildSessionManager:NO];
    NSString *method = httpMethod == KWMHTTPMethodPOST ? @"POST" : @"GET";
    NSURLRequest *request = [sessionManager.requestSerializer requestWithMethod:method URLString:apiPath parameters:parameters error:nil];
    __block id task = [sessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            failure(task,error);
        }else{
            successCallback(task,responseObject);
        }
    }];
    return task;
}
houweibin committed
358

lee committed
359

houweibin committed
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
- (NSURLSessionDataTask *)startSessionTask:(KWMHTTPMethod)httpMethod
                                   apiPath:(NSString *)apiPath
                                parameters:(NSDictionary *)parameters
                                    result:(Class)result
                                     model:(Class)model
                                   success:(void (^)(NSURLSessionDataTask *task, id result))success
                                   failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    return [self startSessionTask:httpMethod
                          apiPath:apiPath
                       parameters:parameters
                        filePaths:nil
                    jsonParameter:NO
                           result:result
                            model:model
                          success:success failure:failure];
}

- (NSString *)toIds:(NSArray<__kindof NSString *> *)idsArray {
    NSMutableString *tmp = [NSMutableString new];
    for (NSString *s in idsArray) {
        [tmp appendFormat:@"%@,", s];
    }
    
    if (tmp.length > 0) {
        return [tmp substringToIndex:tmp.length - 1];
    }else{
        return @"";
    }
}

lee committed
390 391 392 393 394 395 396 397 398 399 400
- (void)loginWebSuccess:(void (^)())success failure:(void (^)(NSError *))failure {
    KWMUserModel *user= [KWMUserModel shareUser];
    NSString *account = user.email;
    NSString *password = user.password;
    if (!password) {
        password = [SAMKeychain passwordForService:@"cemarose.account" account:account];
    }
    // 没登陆过不做处理
    if (!password) {
        return;
    }
u  
lee committed
401
    NSLog(@"loginTask username:%@,password:%@",account,password);
lee committed
402 403 404 405 406 407
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
    [manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
        NSString *url = request.URL.absoluteString;
        if ([url isEqualToString:[NSString stringWithFormat:@"https://%@/account",Shopify_SHOP_DOMAIN]]) {
u  
lee committed
408
            if(success) success();
lee committed
409 410
        }else{
            NSError *error = [[NSError alloc] initWithDomain:url code:401 userInfo:@{NSLocalizedDescriptionKey:@"email & password is invalid !"}];
u  
lee committed
411
            if(failure) failure(error);
lee committed
412 413 414 415 416 417 418 419 420 421 422 423
        }
        return nil;
    }];
    NSString *loginUrl = [NSString stringWithFormat:@"https://%@/account/login",Shopify_SHOP_DOMAIN];
    id param = @{
                @"from_type":@"customer_login",
                @"utf8":@"✓",
                @"customer[email]":account,
                @"customer[password]":password,
                 };
    [manager POST:loginUrl parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
u  
lee committed
424
        if(failure) failure(error);
lee committed
425 426 427
    }];
    
}
houweibin committed
428 429 430

/**
 * 手机登录API
431 432
 * @param mobile 手机号
 * @param code 收到的短信验证码
houweibin committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
 */
- (NSURLSessionDataTask *) phoneLogin:(NSDictionary *)parameters
                                success:(void(^)(NSURLSessionDataTask *task,KWMCustomerResult *result))success
                                failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{

    NSString *apiPath = [NSString stringWithFormat:@"/shopifyapps/china_social_login/%@/api-check-code",Cemarose_KEY];
    
    return [self startSessionTask:KWMHTTPMethodPOST
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMCustomerResult class]
                            model:[KWMCustomer class]
                          success:success
                          failure:failure];
}

u  
lee committed
449 450
#pragma mark - 购物车接口

lee committed
451
- (NSURLSessionDataTask *)changeProductWithVariantId:(NSNumber *)variantId quantity:(NSInteger) quantity success:(void (^)(NSURLSessionDataTask *, KWMCartResult *))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
lee committed
452 453
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/cart/change/%@.js",Shopify_SHOP_DOMAIN,variantId];
    id params = @{ @"quantity": @(quantity) };
u  
lee committed
454
    return [self makeSessionTask:KWMHTTPMethodGET apiPath:apiPath parameters:params result:[KWMCartResult class] model:nil success:success failure:failure];
lee committed
455 456
}

lee committed
457 458 459 460 461 462
- (NSURLSessionDataTask *)updateProductWithVariantIds:(NSArray<NSNumber *> *)variantIds quantities:(NSArray<NSNumber *> *)quantities success:(void (^)(NSURLSessionDataTask *, KWMCartResult *))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/cart/update.js",Shopify_SHOP_DOMAIN];
    NSMutableDictionary *params = [NSMutableDictionary new];
    for (int i=0; i<quantities.count; i++) {
        [params setObject:quantities[i] forKey:[NSString stringWithFormat:@"updates[%@]",variantIds[i]]];
    }
u  
lee committed
463
    return [self makeSessionTask:KWMHTTPMethodPOST apiPath:apiPath parameters:params result:[KWMCartResult class] model:nil success:success failure:failure];
lee committed
464 465
}

lee committed
466 467 468 469 470 471
- (NSURLSessionDataTask *)addProductWithVariantId:(NSNumber *)variantId quantity:(NSInteger)quantity success:(void (^)(NSURLSessionDataTask *, KWMRequestResult *))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/cart/add.js",Shopify_SHOP_DOMAIN];
    id params = @{
                  @"id":variantId,
                  @"quantity":@(quantity),
                  };
u  
lee committed
472 473 474 475 476 477
    return [self makeSessionTask:KWMHTTPMethodPOST apiPath:apiPath parameters:params result:[KWMDictionaryResult class] model:nil success:success failure:failure];
}

-(NSURLSessionDataTask *)getCartSuccess:(void (^)(NSURLSessionDataTask *, KWMCartResult *))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/cart.js",Shopify_SHOP_DOMAIN];
    return [self makeSessionTask:KWMHTTPMethodGET apiPath:apiPath parameters:nil result:[KWMCartResult class] model:nil success:success failure:failure];
lee committed
478 479
}

lee committed
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
- (NSURLSessionDataTask *)tmpCartWithVariantId:(NSNumber *)variantId quantity:(NSInteger)quantity success:(void (^)(NSURLSessionDataTask *, NSString *))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/cart/add.js",Shopify_SHOP_DOMAIN];
    id params = @{
                @"id":variantId,
                @"quantity":@(quantity),
                };
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setHTTPShouldHandleCookies:NO];
    NSString *cookie = [[KWMHttpUtil buildRequestCookieString] stringByReplacingOccurrencesOfRegex:@"cart=.*?; ?" withString:@""];
    [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    return [manager POST:apiPath parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSString *cartCookie = [response.allHeaderFields[@"Set-Cookie"] stringByMatching:@"cart=(.*?);" capture:1];
        success(task,cartCookie);
    } failure:failure];
}

houweibin committed
497 498
/**
 * 手机登录-获取短信API
499
 * @param mobile 手机号
houweibin committed
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
 */
- (NSURLSessionDataTask *) phoneSms:(NSDictionary *)parameters
                              success:(void(^)(NSURLSessionDataTask *task,KWMCemaroseResult *result))success
                              failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    
    NSString *apiPath = [NSString stringWithFormat:@"/shopifyapps/china_social_login/%@/api-verify-code",Cemarose_KEY];
    
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMCemaroseResult class]
                            model:nil
                          success:success
                          failure:failure];
    
}


/**
 * 获取所有品牌
 */
- (NSURLSessionDataTask *) getAllBrand:(NSDictionary *)parameters
                            success:(void(^)(NSURLSessionDataTask *task,KWMBrandsResult *result))success
                            failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    
    NSString *apiPath = @"shopifyapps/product_search/cemarose/brands";
    
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMBrandsResult class]
                            model:nil
                          success:success
                          failure:failure];
}

/**
 * 搜索API
538
 * @param keyword 搜索内容
houweibin committed
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
 */
- (NSURLSessionDataTask *) searchProduct:(NSDictionary *)parameters
                                 success:(void(^)(NSURLSessionDataTask *task,KWMSearchResult *result))success
                                 failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    NSString *apiPath = @"shopifyapps/product_search/cemarose/search";
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                        parameters:parameters
                           result:[KWMSearchResult class]
                            model:nil
                          success:success
                          failure:failure];
}

/**
 * 博客API
 */
- (NSURLSessionDataTask *) getAllBlog:(NSDictionary *)parameters
                              success:(void(^)(NSURLSessionDataTask *task,KWMBlogResult *result))success
                              failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure;{
     NSString *apiPath = [[NSString alloc] initWithFormat:@"https://%@/admin/articles.json",Shopify_SHOP_DOMAIN];
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMBlogResult class]
                            model:nil
                          success:success
                          failure:failure];
}

/**
 * 商品——新品API
 */
- (NSURLSessionDataTask *) getNewProducts:(NSDictionary *)parameters
                                  success:(void(^)(NSURLSessionDataTask *task,KWMNewProducts *result))success
                                  failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    NSString *apiPath = @"https://ogbgohpla.qnssl.com/App.Home.New.json";

    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]/100;
    long long  time = interval;
    apiPath = [[NSString alloc] initWithFormat:@"%@?_=%llu", apiPath, time];
    
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMNewProducts class]
                            model:[KWMNewGoodsModel class]
                          success:success
                          failure:failure];
}

/**
 * 商品——打折API
 */
- (NSURLSessionDataTask *) getDiscountProducts:(NSDictionary *)parameters
                                  success:(void(^)(NSURLSessionDataTask *task,KWMNewProducts *result))success
                                  failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    NSString *apiPath = @"https://ogbgohpla.qnssl.com/App.Home.SALE.json";
    
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]/100;
    long long  time = interval;
    apiPath = [[NSString alloc] initWithFormat:@"%@?_=%llu", apiPath, time];
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMNewProducts class]
                            model:[KWMNewGoodsModel class]
                          success:success
                          failure:failure];
    }

/**
 * 获取商品分类API
 */
- (NSURLSessionDataTask *) getProductTypes:(NSDictionary *)parameters type:(NSInteger)type
                                   success:(void(^)(NSURLSessionDataTask *task,KWMProductTypeResult *result))success
                                   failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    
    NSString *apiPath = @"https://ogbgohpla.qnssl.com/Baby.Navigation.json";
    if(type == 0){
        apiPath = @"https://ogbgohpla.qnssl.com/Baby.Navigation.json";
    }else if(type == 1){
        apiPath = @"https://ogbgohpla.qnssl.com/Girls.Navigation.json";
    }else if(type == 2){
        apiPath = @"https://ogbgohpla.qnssl.com/Boys.Navigation.json";
    }else if(type == 3){
        apiPath = @"https://ogbgohpla.qnssl.com/Shoes.Navigation.json";
    }
    
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]/100;
    long long  time = interval;
    apiPath = [[NSString alloc] initWithFormat:@"%@?_=%llu", apiPath, time];
    
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMProductTypeResult class]
                            model:[KWMProductType class]
                          success:success
                          failure:failure];
}
    

/**
 * 品牌类型--API
 */
- (NSURLSessionDataTask *) getBrandsType:(NSDictionary *)parameters
                                       success:(void(^)(NSURLSessionDataTask *task,KWMBrandsTypeResult *result))success
                                       failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    NSString *apiPath = @"https://ogbgohpla.qnssl.com/Designers.json";
    
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]/100;
    long long  time = interval;
    apiPath = [[NSString alloc] initWithFormat:@"%@?_=%llu", apiPath, time];
    
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMBrandsTypeResult class]
                            model:[KWMBrandsTypeModel class]
                          success:success
                          failure:failure];
}


/**
 * 汇率--API
 */
- (NSURLSessionDataTask *) getExchangeRate:(NSDictionary *)parameters
                                 success:(void(^)(NSURLSessionDataTask *task,KWMExchangeRateResult *result))success
                                 failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
u  
lee committed
670
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/app/exchange/rate",Pay_API_DOMAIN];
lee committed
671 672 673 674
//    NSString *sign = [KWMStringUtil MD5:[KWMStringUtil BASE64:@"currency=EUR&key=bd3f58f5cd3d7a217ac8c8e655ab52f8"]];
//    NSLog(@"rate sign: %@",sign);
//    NSDictionary *params = @{@"currency":@"EUR",@"sign":sign};
    NSDictionary *params = @{@"currency":@"EUR",@"sign":@"665d9716511eb11f68a1a7a862ed2ddd"};
houweibin committed
675
    
lee committed
676
    return [self startSessionTask:KWMHTTPMethodPOST
houweibin committed
677
                          apiPath:apiPath
lee committed
678
                       parameters:params
houweibin committed
679 680 681 682 683 684
                           result:[KWMExchangeRateResult class]
                            model:nil
                          success:success
                          failure:failure];
}

lee committed
685 686 687 688 689
- (NSURLSessionDataTask *)getHomeDataWithSuccess:(void (^)(NSURLSessionDataTask *, KWMHomeDataResult *))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    NSString *apiPath = @"https://ogbgohpla.qnssl.com/App.Home.json?1";
    return [self startSessionTask:KWMHTTPMethodGET apiPath:apiPath parameters:nil result:[KWMHomeDataResult class] model:nil success:success failure:failure];
}

houweibin committed
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


/**
 * 获取相关图片api
 */
- (NSURLSessionDataTask *) getProductImages:(NSDictionary *)parameters productId:(NSNumber *)productId
                                    success:(void(^)(NSURLSessionDataTask *task,KWMImagesResult *result))success
                                    failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
   
    NSString *apiPath = [[NSString alloc] initWithFormat:@"https://%@/admin/products/%@/metafields.json",Shopify_SHOP_DOMAIN,productId.stringValue];
    
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMImagesResult class]
                            model:[KWMImage class]
                          success:success
                          failure:failure];
}

/**
 * 获取获取某个订单api
 */
- (NSURLSessionDataTask *) getAdminOrder:(NSDictionary *)parameters orderId:(NSNumber *)orderId
                                    success:(void(^)(NSURLSessionDataTask *task,KWMOrdersResult *result))success
                                    failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    
    NSString *apiPath = [[NSString alloc] initWithFormat:@"https://%@/admin/orders.json?ids=%@",Shopify_SHOP_DOMAIN,orderId.stringValue];
    
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMOrdersResult class]
                            model:[KWMOrder class]
                          success:success
                          failure:failure];
}

/**
 * 获取商品api,因為admin商品有剩余库存数量字段,所以商品詳細還需要請求此api。
 */
- (NSURLSessionDataTask *) getAdminProduct:(NSDictionary *)parameters productId:(NSNumber *)productId
                                    success:(void(^)(NSURLSessionDataTask *task,KWMProductResult *result))success
                                    failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    
    NSString *apiPath = [[NSString alloc] initWithFormat:@"https://%@/admin/products/%@.json",Shopify_SHOP_DOMAIN,productId.stringValue];
    
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMProductResult class]
                            model:[KWMProduct class]
                          success:success
                          failure:failure];
}

/**
 * 取消订单api
748 749 750 751 752
 * @param amount 退款金额 (default: false)(十进制:21.20)If set, Shopify will attempt to void/refund the payment depending on the status.
 * @param restock 是否将此订单商品重新包装会商店 (default: false)
 * @param reason 订单取消原因 (用户customer, 库存inventory, 假货fraud, 其他other)(default: other)
 * @param email 发送邮箱通知用户 (default: false)
 * @param refund 更复杂的退款方式 As specified in the Refund documentation. Required for some more complex refund situations.
houweibin committed
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
 */
- (NSURLSessionDataTask *) cancelOrder:(NSDictionary *)parameters orderId:(NSNumber *)orderId
                                   success:(void(^)(NSURLSessionDataTask *task,KWMProductResult *result))success
                                   failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    NSString *apiPath = [[NSString alloc] initWithFormat:@"https://%@/admin/orders/%@/cancel.json",Shopify_SHOP_DOMAIN,orderId.stringValue];
    
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMCemaroseResult class]
                            model:nil
                          success:success
                          failure:failure];
}


769 770
/**
 * 微信统一下单API
771 772 773 774 775
 * @param checkout_token shopify订单token
 * @param total_price 订单总金额
 * @param ip_address 手机IP
 * @param subject 订单描述
 * @param sign 签名验证
776 777 778 779 780 781 782
 * 签名规则
 * str_sign = "ip_address=127.0.0.1&checkout_token=5173547165345&subject=test&total_price=23423&key=bd3f58f5cd3d7a217ac8c8e655ab52f8";
 * sign = md5(base64_encode($str_sign));
 */
- (NSURLSessionDataTask *) wechatPayUnifiedOrder:(NSDictionary *)parameters
                                         success:(void(^)(NSURLSessionDataTask *task,KWMCheckoutPayResult *result))success
                                         failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
houweibin committed
783
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/wechatpay/app/unified_order",Pay_API_DOMAIN];
784 785 786 787 788 789 790 791 792 793 794
    return [self startSessionTask:KWMHTTPMethodPOST
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMCheckoutPayResult class]
                            model:[KWMWechatPayData class]
                          success:success
                          failure:failure];
}

/**
 * 支付宝统一下单API
795 796 797 798 799
 * @param checkout_token shopify订单token
 * @param total_price 订单总金额
 * @param subject 订单描述
 * @param sign 签名验证
 * 签名规则:
800 801 802 803 804 805
 * str_sign = checkout_token=5173547165345&subject=test&total_price=23423&key=bd3f58f5cd3d7a217ac8c8e655ab52f8";
 * sign = md5(base64_encode($str_sign));
 */
- (NSURLSessionDataTask *) aliPayUnifiedOrder:(NSDictionary *)parameters
                                      success:(void(^)(NSURLSessionDataTask *task,KWMCheckoutPayResult *result))success
                                      failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
houweibin committed
806
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/alipay/app/unified_order",Pay_API_DOMAIN];
807 808 809 810 811 812 813 814 815 816 817 818
    return [self startSessionTask:KWMHTTPMethodPOST
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMCheckoutPayResult class]
                            model:nil
                          success:success
                          failure:failure];
}

- (NSURLSessionDataTask *) wechatPayOrderQuery:(NSDictionary *)parameters
                                       success:(void(^)(NSURLSessionDataTask *task,KWMCheckoutPayResult *result))success
                                       failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
houweibin committed
819
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/wechatpay/order/query",Pay_API_DOMAIN];
houweibin committed
820

821 822 823 824 825 826 827 828 829 830 831 832
    return [self startSessionTask:KWMHTTPMethodPOST
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMCheckoutPayResult class]
                            model:nil
                          success:success
                          failure:failure];
}

- (NSURLSessionDataTask *) aliPayOrderQuery:(NSDictionary *)parameters
                                    success:(void(^)(NSURLSessionDataTask *task,KWMCheckoutPayResult *result))success
                                    failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
houweibin committed
833
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/alipay/order/query",Pay_API_DOMAIN];
houweibin committed
834

835 836 837 838 839 840 841 842 843
    return [self startSessionTask:KWMHTTPMethodPOST
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMCheckoutPayResult class]
                            model:nil
                          success:success
                          failure:failure];
}

houweibin committed
844 845
/**
 * 通过checkout_token查询shopify订单API
846 847 848
 * @param checkout_token shopify订单token
 * @param sign 签名验证
 * 签名规则:
houweibin committed
849 850 851 852 853 854
 * str_sign = checkout_token=5173547165345&key=bd3f58f5cd3d7a217ac8c8e655ab52f8";
 * sign = md5(base64_encode($str_sign));
 */
- (NSURLSessionDataTask *) appOrderQuery:(NSDictionary *)parameters
                                    success:(void(^)(NSURLSessionDataTask *task,KWMCheckoutPayResult *result))success
                                    failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
houweibin committed
855
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/app/order/query",Pay_API_DOMAIN];
houweibin committed
856 857 858 859 860 861 862 863 864
    return [self startSessionTask:KWMHTTPMethodPOST
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMCheckoutPayResult class]
                            model:[KWMOrderPaid class]
                          success:success
                          failure:failure];
}

865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
/**
 * 用户添加 wish API
 * @param customer_id 用户ID
 * @param customer_email 用户邮箱
 * @param customer_name 用户名
 * @param product_title 产品标题
 * @param prodcut_id 产品ID
 * @param variant_id 变体ID
 * @param variant_sku sku
 * @param variant_title 变体标题
 * @param product_handle 产品handle
 * @param shop 店铺名(cemarose-test.myshopify.com)
 */
- (NSURLSessionDataTask *) saveWish:(NSDictionary *)parameters
                                 success:(void(^)(NSURLSessionDataTask *task,KWMAdditionalListResult *result))success
                                 failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/app/wishlist-save",@"chris.tofnews.com"];
    return [self startSessionTask:KWMHTTPMethodPOST
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMAdditionalListResult class]
                            model:nil
                          success:success
                          failure:failure];
}
houweibin committed
890

891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
/**
 * 获取用户 wishlist API
 * @param customer_id 用户ID
 * @param customer_email 用户邮箱
 * @param variant_id 变体ID(用于获取单个愿望商品)
 * @param shop 店铺名(cemarose-test.myshopify.com)
 */
- (NSURLSessionDataTask *) getWishList:(NSDictionary *)parameters
                                success:(void(^)(NSURLSessionDataTask *task,KWMAdditionalListResult *result))success
                                failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/app/wishlist",@"chris.tofnews.com"];
    return [self startSessionTask:KWMHTTPMethodGET
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMAdditionalListResult class]
                            model:[KWMWish class]
                          success:success
                          failure:failure];
}

/**
 * 移除指定 wish API
 * @param customer_id 用户ID
 * @param customer_email 用户邮箱
 * @param variant_id 变体ID
 * @param shop 店铺名(cemarose-test.myshopify.com)
 */
- (NSURLSessionDataTask *) removeWish:(NSDictionary *)parameters
                               success:(void(^)(NSURLSessionDataTask *task,KWMAdditionalListResult *result))success
                               failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/app/wishlist-prune",@"chris.tofnews.com"];
    return [self startSessionTask:KWMHTTPMethodPOST
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMAdditionalListResult class]
                            model:[KWMWish class]
                          success:success
                          failure:failure];
}
houweibin committed
930

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
/**
 * 清空愿望单 API
 * @param customer_id 用户ID
 * @param customer_email 用户邮箱
 * @param shop 店铺名(cemarose-test.myshopify.com)
 */
- (NSURLSessionDataTask *) clearWishList:(NSDictionary *)parameters
                              success:(void(^)(NSURLSessionDataTask *task,KWMAdditionalListResult *result))success
                              failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure{
    NSString *apiPath = [NSString stringWithFormat:@"https://%@/app/wishlist-delete",@"chris.tofnews.com"];
    return [self startSessionTask:KWMHTTPMethodPOST
                          apiPath:apiPath
                       parameters:parameters
                           result:[KWMAdditionalListResult class]
                            model:[KWMWish class]
                          success:success
                          failure:failure];
}
houweibin committed
949 950 951



952

houweibin committed
953 954

@end