SDKInterface.m 12.7 KB
//
//  UnionInterface.m
//  PoolSdk
//
//  Created by winFan on 11/23/15.
//  Copyright (c) 2015 winFan. All rights reserved.
//
#include "SDKInterface.h"
#import <UIKit/UIKit.h>
#import <SXSDK/SXSDK.h>

@interface SDKInterface()
{
    UIViewController* _gameViewController;
    
    UIInterfaceOrientationMask _interfaceOrientationMask;
    int userOpType ;//0为正常登录 1为切换账号
    NSString *loginToken;
}
@end

@implementation SDKInterface : Interface

/**
 初始化SDK
*/
- (void)SDKinit:(UIViewController *) control
{
    //必须继承
    [super SDKinit:control];
    
    [PoolConfig getInstance];
    
    _gameViewController = control;
    
    
    NSString *ori = [[PoolConfig getInstance]getValueByKey:@"screenOrientation"];
    if ([@"1" isEqualToString:ori]) {//1为竖屏 2为横屏
        _interfaceOrientationMask = UIInterfaceOrientationMaskPortrait;
    }else{
        _interfaceOrientationMask = UIInterfaceOrientationMaskLandscape;
    }
    
    NSString * appID = [[PoolConfig getInstance]getValueByKey:@"sdkAppID"];
    NSString * key = [[PoolConfig getInstance]getValueByKey:@"sdkKey"];
    NSString * gameVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString * gameID = [[PoolConfig getInstance]getValueByKey:@"sdkAppID"];
    NSString * trackingKey = [[PoolConfig getInstance]getValueByKey:@"sdkTrackingKey"];
    
    [[SXSDK shareInstance] initWithApplication:appID key:key version:gameVersion game:gameID trackingKey:trackingKey];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeOrientations:) name:@"shouldChangeOrientations" object:nil];
    
    [[PoolChecker getInstance]setPoolSdkDelegate:self];
    [[PoolChecker getInstance] sendNotice:PoolSDKNotificationInitSDK notiName:@"InitSuccess" statusCode:POOLSDK_NO_ERROR description:@"initSuccess" extendData:nil];
    
    
    [[SXSDK shareInstance] setBlock:^{
        userOpType = 0;
        [[PoolChecker getInstance] sendNotice:PoolSDKNotificationLogout notiName:@"logoutSuccess" statusCode:POOLSDK_NO_ERROR description:@"logoutSuccess" extendData:nil];
    } failCallback:^{
        NSLog(@"callback blcok fail");
    }];
    
}

-(void)changeOrientations:(NSNotification*)noti{
    
    NSDictionary *dict = [NSDictionary dictionary];
    dict = noti.userInfo;
    _interfaceOrientationMask = [dict[@"interfaceOrientationMask"] integerValue];
}

- (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    return _interfaceOrientationMask;
}


- (NSString *)encodeParameter:(NSString *)originalPara {
    CFStringRef encodeParaCf = CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)originalPara, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8);
    NSString *encodePara = (__bridge NSString *)(encodeParaCf);
    CFRelease(encodeParaCf);
    return encodePara;
}

/**
 *
 **/
- (NSString*)urlEncode:(NSString*)data
{
    NSCharacterSet *encodeUrlSet = [NSCharacterSet URLQueryAllowedCharacterSet];
    NSString *encodeUrl = [data stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet];
    NSLog(@"encodeURL:%@",encodeUrl);
    return encodeUrl;
}


/**
 登录SDK
 */
- (void)SDKloginSDK
{
    NSLog(@"调用了LoginSDK");
    userOpType = 0;
    [[SXSDK shareInstance] loginWithController:_gameViewController succCallback:^(NSDictionary *result) {
        NSLog(@"[ 登录成功 ]   %@", result);
        
        //NSString *gameid = [result objectForKey:@"gameID"];
        loginToken = [result objectForKey:@"data"];
       
        //[self encodeParameter:data];
        PoolLoginInfo* loginInfo = [[PoolLoginInfo alloc] init];
        loginInfo.timestamp = [self getCurrentTimestamp];
        [loginInfo setOpenId:[self encodeParameter:loginToken]];
        [loginInfo setSign:[self encodeParameter:loginToken]];
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            if (userOpType == 0) {
                [[PoolChecker getInstance] startCheck:loginInfo];
            }else{
                [[PoolChecker getInstance ]startCheckDelegate:loginInfo type:PoolSDKNotificationSwitchAccount];
            }
            
        });
        
    } failCallback:^(NSString *message) {
        NSLog(@"[ 登录失败 ]   %@", message);
    } exitCallback:^{
        NSLog(@"[ 登录退出 ]");
    }];
}

- (void)SDKreport:(PoolReportInfo *)reportInfo
{
    NSLog(@"reportInfo");
    if ([REPORT_CREATEROLE isEqualToString:[reportInfo reportType]]) {
        //0
        NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
                              [reportInfo openId], @"uid",
                              [reportInfo playerId], @"roleID",
                              [reportInfo playerName], @"roleName",
                              [[PoolConfig getInstance]getValueByKey:@"sdkGameID"], @"gameID",
                              [reportInfo serverId], @"serverID",
                              [reportInfo serverName], @"serverName",
                              [reportInfo playerLevel], @"roleLevel",
                              [self getSDKTimestamp], @"timestamp",
                              @"0", @"dataType",
                              nil];
        
        [[SXSDK shareInstance] achievement:data succCallback:^(NSDictionary *result) {
            NSLog(@"[提交信息成功] %@", result);
        } failCallback:^(NSDictionary *message) {
            NSLog(@"[提交信息失败] %@", [message objectForKey:@"msg"]);
            
        }];
        
    }else if ([[reportInfo reportType] isEqualToString:REPORT_ENTER]) {
        //1
        NSDictionary *data = [[NSDictionary alloc]initWithObjectsAndKeys:
                              [reportInfo openId], @"uid",
                              [reportInfo playerId], @"roleID",
                              [reportInfo playerName], @"roleName",
                              [[PoolConfig getInstance]getValueByKey:@"sdkGameID"], @"gameID",
                              [reportInfo serverId], @"serverID",
                              [reportInfo serverName], @"serverName",
                              [reportInfo playerLevel], @"roleLevel",
                              [self getSDKTimestamp], @"timestamp",
                              @"1", @"dataType",
                              nil];
        
        [[SXSDK shareInstance] achievement:data succCallback:^(NSDictionary *result) {
            NSLog(@"[提交信息成功] %@", result);
        } failCallback:^(NSDictionary *message) {
            NSLog(@"[提交信息失败] %@", [message objectForKey:@"msg"]);
            
        }];
        
    }else if([[reportInfo reportType] isEqualToString:REPORT_ROLEUPGRADE]) {
        //2
        NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
                              [reportInfo openId], @"uid",
                              [reportInfo playerId], @"roleID",
                              [reportInfo playerName], @"roleName",
                              [[PoolConfig getInstance]getValueByKey:@"sdkGameID"], @"gameID",
                              [reportInfo serverId], @"serverID",
                              [reportInfo serverName], @"serverName",
                              [reportInfo playerLevel], @"roleLevel",
                              [self getSDKTimestamp], @"timestamp",
                              @"2", @"dataType",
                              nil];
        
        [[SXSDK shareInstance] achievement:data succCallback:^(NSDictionary *result) {
            NSLog(@"[提交信息成功] %@", result);
        } failCallback:^(NSDictionary *message) {
            NSLog(@"[提交信息失败] %@", [message objectForKey:@"msg"]);
            
        }];
    }
}

-(BOOL)hasSwitchAccount
{
    return YES;
}

- (void)switchAccount
{
    NSLog(@"切换账号");
    
    //退出,切换?
    [[SXSDK shareInstance] switchAccount:^{
        NSLog(@"switch account callback");
        userOpType = 1;
    }];
}

- (void)receivePayMessage : (NSNotification *)notification;
{
    NSString *order_id = [notification object];
    NSLog(@"订单ID:%@", order_id);
}

/**
 @return 商品名称
 */
- (NSString*)getProductNameByAmount:(NSString*)products amount:(NSString*)amount
{
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:products options:NSJSONWritingPrettyPrinted error:nil];
    if(jsonData){
        NSDictionary* productList = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
        if(productList){
            NSEnumerator* keysList = [productList keyEnumerator];
            id keyValue;
            while (keyValue = [keysList nextObject])
            {
                NSString* appleAmount = [[productList objectForKey:keyValue] objectForKey:@"amount"];
                if(appleAmount.intValue == amount.intValue){
                     NSString* productName = [[productList objectForKey:keyValue] objectForKey:@"name"];
                    return productName;
                }
            }
        }
    }
    NSLog(@"get product name error amount:%@",amount);
    return @"元宝";
}

/**
 @return 商品ID
 */
- (NSString*)getProductIdByAmount:(NSString*)products amount:(NSString*)amount
{
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:products options:NSJSONWritingPrettyPrinted error:nil];
    if(jsonData){
        NSDictionary* productList = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
        if(productList){
            NSEnumerator* keysList = [productList keyEnumerator];
            id keyValue;
            while (keyValue = [keysList nextObject])
            {
                NSLog(@"i found %@",keyValue);
                NSString* appleAmount = [[productList objectForKey:keyValue] objectForKey:@"amount"];
                NSLog(@"appleAmount:%@ amount:%@",appleAmount,amount);
                if(appleAmount.intValue == amount.intValue){
                    return keyValue;
                }
            }
        }
    }
    return @"unknow";
}


- (void)SDKpayWithPaymentInfo:(PoolCreateOrderInfo *)payInfo
{
    NSString *notifyUrl = [PoolUtils createPayUrl];
    
    NSLog(@"loginToken:%@",loginToken);
    
    NSDictionary *payParameDic = [[NSDictionary alloc]initWithObjectsAndKeys:[self encodeParameter:loginToken],@"accessToken",notifyUrl,@"noticeUrl",[payInfo serverName],@"serverName",[payInfo playerName],@"roleName",[[PoolChecker getInstance]userId],@"openUID",[payInfo serverId],@"serverID", nil];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:payParameDic options:0 error:NULL];
    NSString * otherInfo = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    otherInfo = [otherInfo stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    
    [payInfo setOtherInfo:otherInfo];
    [super SDKpayWithPaymentInfo:payInfo];
}


- (void)receiveCreateOrder:(NSNotification *)notification
{
    NSLog(@"创建订单成功");
    PoolPayInfo *payInfo = [notification object];
    [[SXSDK shareInstance] pay:[payInfo other]
                  succCallback:^(NSDictionary *result) {
                      //NSLog(@"[ 支付成功 ]    %@", result);
                  }
                  failCallback:^(NSDictionary *message) {
                       //NSLog(@"[ 购买异常 ]    %@", message);
                  }];
}

-(NSString*)getCurrentTimestamp{
    // 时间戳转时间
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString* timeStr = [[NSString alloc]initWithFormat:@"%.f",interval];
    return timeStr;
}

-(NSString *)getSDKTimestamp {
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSInteger t = a;
    NSString *timeString = [NSString stringWithFormat:@"%ld", (long)t];
    
    return timeString;
}



-(void)PoolSdkLoginSuccess:(PoolLoginInfo*)loginInfo{
    [[PoolChecker getInstance] sendNotice:PoolSDKNotificationLogin notiName:@"LoginSuccess" statusCode:POOLSDK_NO_ERROR description:@"LoginSucecess" extendData:loginInfo];
}

-(void)PoolSdkLoginFail:(NSString*)msg
{
    [[PoolChecker getInstance] sendNotice:PoolSDKNotificationLogin notiName:@"LoginFail" statusCode:POOLSDK_ERROR_LOGIN_FAILED description:@"LoginFail" extendData:msg];
}

-(void)PoolSdkSwitchAccountSuccess:(PoolLoginInfo*)loginInfo
{
    NSLog(@"switch success");
    [[PoolChecker getInstance] sendNotice:PoolSDKNotificationSwitchAccount notiName:@"SwitchSuccess" statusCode:POOLSDK_NO_ERROR description:@"SwitchSucecess" extendData:loginInfo];
}

-(void)PoolSdkSwitchAccountFail:(NSString*)msg
{
    [[PoolChecker getInstance] sendNotice:PoolSDKNotificationSwitchAccount notiName:@"SwitchFail" statusCode:POOLSDK_ERROR_SWICHT_ACCOUNT_FAILED description:@"SwitchFail" extendData:msg];
}


@end