ios 支付

//

//  AppDelegate.m

//  Unity-iPhone

//

//  Created by wuruijian on 14-9-28.

//

//


#import "AppDelegate.h"

#import "U3DInterface.h"

#import "SYGPlatform.h"

#import <StoreKit/StoreKit.h>

#import "ReYunChannel.h"


#import <CommonCrypto/CommonDigest.h>

#import <AdSupport/AdSupport.h>



#import "sys/utsname.h"

#include <sys/sysctl.h>

#include <net/if.h>

#include <net/if_dl.h>

#include <stdlib.h>




IMPL_APP_CONTROLLER_SUBCLASS(AppDelegate)


NSString *uid;

AppDelegate *instance;


NSString *urlBackPHP;

NSInteger money;

NSString *myCustomInfo;

NSString *mySign;


#if defined(__cplusplus)

extern "C"{

#endif

    

    int GetPlatform()

    {

        return 10012;

    }


    void Init()

    {

        NSLog(@"------------ShouYouGu.Init");

        SDK_Init();

        [[GameUISDK shareInstance] initParamsWithAppId:@"17"

                                                AppKey:@"EC5D7BF66E0BAB20"

                                             channelId:@"2"

                                          subChannelId:@"1"];

        

        [instance SendIdfaToPhp];

        

    }

    

    void Login()

    {

        NSLog(@"------------ShouYouGu.Login");

        [[GameUISDK shareInstance] login];

    }

    

    void ShowCenter()

    {

        NSLog(@"------------ShouYouGu.ShowCenter");

        [ReYunChannel setEvent:@"打开用户中心"];

    }

    

    void Pay(int money, int time, const char* sign, const char* customInfo)

    {

        NSLog(@"手游谷-灵域戮仙AppStore.Pay");

        

        if(instance==nil) return;

        

        if([SKPaymentQueue canMakePayments]){

            

            myCustomInfo=[[NSString alloc] initWithFormat:@"%s",customInfo];

            mySign=[[NSString alloc] initWithFormat:@"%s",sign];


            NSString *productid=[[NSString alloc]initWithFormat:@"com.lylx.AppStore_%d",(money*10)];

            NSArray *product=[[NSArray alloc]initWithObjects:productid, nil];

            NSSet *set=[NSSet setWithArray:product];

            SKProductsRequest *request=[[SKProductsRequest alloc] initWithProductIdentifiers:set];

            request.delegate=instance;

            [request start];

            [product release];

            [ReYunChannel setEvent:@"开始充值"];

        }

        else

        {

            NSLog(@"请求支付失败,用户禁止应用内付费购买。");

            [instance showAlertView:@"确定" :@"请求支付失败,用户禁止应用内付费购买."];

        }

    }

    

    

#if defined(__cplusplus)

}

#endif



@implementation AppDelegate



-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    [super application:application didFinishLaunchingWithOptions:launchOptions];

    

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(onLoginSuc:)

                                                 name:LHYD_SDK_MSG_LOGIN_FIN

                                               object:nil];

    

    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];

    instance=self;

    [ReYunChannel initWithAppId:@"ac56c3339dbb7698f95ffe20eaa4891b"

                   withChannelId:@"_default_"];

    return YES;

}


-(void)onLoginSuc:(NSNotification *)info

{

    NSString *userid = [info object];

    uid =  [userid copy];

    NSString* param = [NSString stringWithFormat:@"r=appstore&userid=%@", uid];

    U3DSendMessage(ON_LGON, param);

    [ReYunChannel setLoginWithAccountID:uid];

}


-(void)UpdatePlayerInfo:(NSString *)info

{

   // NSArray *arrayEx=[info componentsSeparatedByString:@" "];

    [ReYunChannel setRegisterWithAccountID:uid];

    

}


-(void) GoAppStore

{

    NSLog(@"手游谷-灵域戮仙AppStore.跳转更新");

    NSString *iTunesLink =@"http://itunes.apple.com/us/app/id1079817121";

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];

    [ReYunChannel setEvent:@"跳转到appStore升级版本"];

}


- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window

{

    return UIInterfaceOrientationMaskAll;

}


//以上查询的回调函数

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{

    NSArray *myProduct=response.products;

    if(myProduct.count==0)

    {

        NSLog(@"无法获取产品信息,购买失败。");

        NSLog(@"无效的产品product ID = %@",response.invalidProductIdentifiers);

        return;

    }


    NSLog(@"Received products results...");

    SKPayment *payment=[SKPayment paymentWithProduct:myProduct[0]];

    [[SKPaymentQueue defaultQueue] addPayment:payment];

}

//获取交易状态

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {

    NSLog(@"paymentQueue");

    for (SKPaymentTransaction *transaction in transactions)

    {

        switch (transaction.transactionState)

        {

            case SKPaymentTransactionStatePurchased://交易完成

                NSLog(@"transactionIdentifier = %@", transaction.transactionIdentifier);

                [self completeTransaction:transaction];

                break;

            case SKPaymentTransactionStateFailed://交易失败

                NSLog(@"交易失败");

                [self failedTransaction:transaction];

                break;

            case SKPaymentTransactionStateRestored://已经购买过该商品

                NSLog(@"已经购买过该商品");

                [self restoreTransaction:transaction];

                break;

            case SKPaymentTransactionStatePurchasing:      //商品添加进列表

                NSLog(@"商品添加进列表");

                break;

            default:

                break;

        }

    }

}


- (NSString *)md5:(NSString *)str

{

    const char *cStr = [str UTF8String];

    unsigned char result[16];

    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call

    return [NSString stringWithFormat:

            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",

            result[0], result[1], result[2], result[3],

            result[4], result[5], result[6], result[7],

            result[8], result[9], result[10], result[11],

            result[12], result[13], result[14], result[15]

            ]; 

}



-(void) completeTransaction: (SKPaymentTransaction *)transaction{

    // Your application should implement these two methods.

    NSString *productId=transaction.payment.productIdentifier;

    NSString *receipt=[transaction.transactionReceipt base64Encoding];

    NSLog(@"支付成功:id=%@",productId);

    if([productId length]>0)

    {

        

        //向自己的服务器验证购买凭证

        NSArray *arrayEx=[productId componentsSeparatedByString:@"_"];

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

        [dateFormatter setDateFormat:@"yyyyMMddHHmmssSSS"];

        NSString *orderId = [dateFormatter stringFromDate:[NSDate date]];

        NSInteger money =[[arrayEx objectAtIndex:1] integerValue];

        NSString *sign=[ self md5:[NSString stringWithFormat:@"%@%@%@",myCustomInfo,orderId,@"4785831bc2a8b2dd348c568bf5692d6b"]];


        NSURL *url=[NSURL URLWithString:@"http://120.55.80.91/hhsy/api/pay_callback.php?r=appstore"];

        NSMutableURLRequest *request=[[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

        [request setHTTPMethod:@"POST"];

        NSString *str=[[NSString alloc] initWithFormat:@"&customInfo=%@&time=%@&sign=%@&money=%d&certificate=%@",myCustomInfo,orderId,sign,money/10,receipt];

        NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];

        [request setHTTPBody:data];

        NSLog(@"------------Custom=%@-url=%@",myCustomInfo,request);

        NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

        

        /*

        urlBackPHP =[[NSString alloc] initWithFormat:@"http://120.55.80.91/hhsy/api/pay_callback.php?r=appstore&customInfo=%@&time=%@&sign=%@&money=%d&certificate=%@",myCustomInfo,orderId,sign,money/10,receipt];

        NSLog(@"urlBackPHP=%@",urlBackPHP);

        urlBackPHP=[urlBackPHP stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        

        

        //异步get

        //1.创建url

        NSURL *url = [NSURL URLWithString:urlBackPHP];

        //2.创建请求

        NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

        //3.连接服务器

        NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

        */

        //热云数据上报

        [ReYunChannel setPayment:orderId paymentType:@"apple" currentType:@"CNY" currencyAmount:[[NSString stringWithFormat:@"%d",money/10] floatValue]];

    }

    // Remove the transaction from the payment queue.

    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

}


- (void)failedTransaction:(SKPaymentTransaction *)transaction {

    if(transaction.error.code != SKErrorPaymentCancelled) {

        NSLog(@"购买失败");

    } else {

        NSLog(@"用户取消交易");

    }

    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

}


- (void)restoreTransaction:(SKPaymentTransaction *)transaction {

    // 对于已购商品,处理恢复购买的逻辑

    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

}



// 返回数据

- (void)connection:(NSURLConnection *) connection didReceiveData:(NSData *)data {

    NSString *dataString =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"------------didReceiveData:%@", dataString);

}



///



-(void)SendIdfaToPhp

{

    

    NSString *proName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"My Bundle Identifier"];

    NSLog(@"Bundle identifier ==== %@",proName);

    

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyyMMddHHmmssSSS"];

    NSString *time = [dateFormatter stringFromDate:[NSDate date]];

    

    

    

    NSString *newTime=[NSString stringWithFormat:@"%@%@",time,@"4785831bc2a8b2dd348c568bf5692d6b"];

    NSString *md5Time=[self md5:newTime];

    

    NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];

    

    NSLog(@"idfa   %@",idfa);


    

    //NSString *ex=[NSString stringWithFormat:@"http://120.55.80.91/hhsy/center/api.php?r=regstat/idfa&idfa=%@&channel=%@&package=%@&sign=%@&time=%@",idfa,[self getchannel],[self getMarket],md5Time,time];

    

      NSString *ex=[NSString stringWithFormat:@"http://120.55.80.91/hhsy/center/api.php?r=regstat/idfa&idfa=%@&channel=%@&package=%@&sign=%@&time=%@&model=%@&version=%@&mac=%@&network=%@",idfa,[self getchannel],[self getMarket],md5Time,time,[self GetPlatform],[self GetVersion], [self GetMac],[self GetNetWork] ];

    

    

    

    NSLog(@"ex=%@",ex);

    ex=[ex stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    

    

    //异步get

    //1.创建url

    NSURL *url = [NSURL URLWithString:ex];

    //2.创建请求

    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    //3.连接服务器

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

}


-(NSString *)getchannel

{

    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"sdkInfo" ofType:@"plist"];

    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];

    NSString *channel = [[dictionary objectForKey:@"sdkInfo"] objectForKey:@"channel"];

    return channel;

}

-(NSString *)getMarket

{

    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"sdkInfo" ofType:@"plist"];

    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];

    NSInteger market = [[[dictionary objectForKey:@"sdkInfo"] objectForKey:@"market"] intValue];

    NSString *stringMarket=    [NSString stringWithFormat: @"%ld", (long)market];

    return stringMarket;

    

}




-(NSString *)GetNetWork

{

    NSString *network=  [hostReach GetNetState];

    NSLog(@"network   %@",network);

    return network;

}

-(NSString *)GetVersion

{

    NSString* version = [[UIDevice currentDevice] systemVersion];

    NSLog(@"version   %@",version);

    return version;

}

-(NSString *)GetPlatform

{

    struct utsname systemInfo;

    uname(&systemInfo);

    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];

    NSLog(@"platform  %@",platform);

    return platform;

}

-(NSString*) GetMac

{

    

    int                 mib[6];

    size_t              len;

    char                *buf;

    unsigned char       *ptr;

    struct if_msghdr    *ifm;

    struct sockaddr_dl  *sdl;

    

    mib[0] = CTL_NET;

    mib[1] = AF_ROUTE;

    mib[2] = 0;

    mib[3] = AF_LINK;

    mib[4] = NET_RT_IFLIST;

    

    if ((mib[5] = if_nametoindex("en0")) == 0) {

        printf("Error: if_nametoindex error/n");

        return NULL;

    }

    

    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {

        printf("Error: sysctl, take 1/n");

        return NULL;

    }

    

    if ((buf = (char *)malloc(len)) == NULL) {

        printf("Could not allocate memory. error!/n");

        return NULL;

    }

    

    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {

        printf("Error: sysctl, take 2");

        return NULL;

    }

    

    ifm = (struct if_msghdr *)buf;

    sdl = (struct sockaddr_dl *)(ifm + 1);

    ptr = (unsigned char *)LLADDR(sdl);

    NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];

    

    //    NSString *outstring = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];

    

    NSLog(@"outString:%@", outstring);

    

    free(buf);

    

    return [outstring uppercaseString];

}









@end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值