Cocos2d-Lua 接IOS支付记录

Cocos2d-Lua 接IOS支付记录,第1张

概述网上可以找到Cocos2d-X或者Cocos2d-Js接IOS支付的参考,但是没有Lua的,所以就暂且提供一个我的版本。 没有折腾Lua和C++之间的交互,暂且用着Cocos2d框架提供的LuaObjcBridge,非常简单。一些类名取自IAP Js版本作者。 第一个文件:IAPDelegates.h #import <Foundation/Foundation.h>#import <Store

网上可以找到Cocos2d-X或者Cocos2d-Js接IOS支付的参考,但是没有Lua的,所以就暂且提供一个我的版本。
没有折腾Lua和C++之间的交互,暂且用着Cocos2d框架提供的LuaObjcBrIDge,非常简单。一些类名取自IAP Js版本作者。

第一个文件:IAPDelegates.h

#import <Foundation/Foundation.h>#import <StoreKit/StoreKit.h>@class AppController;@interface iAPProductsRequestDelegate : NSObject<SKProductsRequestDelegate>@property (nonatomic,assign) AppController *iosiap;@end@interface iAPTransactionObserver : NSObject<SKPaymentTransactionObserver>@property (nonatomic,assign) AppController *iosiap;@end

第二个文件:IAPDelegates.m

#import <Foundation/Foundation.h>#import "IAPDelegates.h"#import "AppController.h"@implementation iAPProductsRequestDelegate- (voID)productsRequest:(SKProductsRequest *)request     dIDReceiveResponse:(SKProductsResponse *)response{    if (_iosiap.skProducts) {        [(NSArray *)(_iosiap.skProducts) release];    }    _iosiap.skProducts = [response.products retain];}- (voID)requestDIDFinish:(SKRequest *)request{    [request.delegate release];    [request release];}- (voID)request:(SKRequest *)request dIDFailWithError:(NSError *)error{    NSLog(@"%@",error);}@end@implementation iAPTransactionObserver- (voID)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{    for (SKPaymentTransaction *transaction in transactions) {        if(transaction.transactionState == SKPaymentTransactionStatePurchased){            [_iosiap onPaymentEvent:transaction.payment.productIDentifIEr andQuantity:transaction.payment.quantity];        }        if (transaction.transactionState != SKPaymentTransactionStatePurchasing) {            [[SKPaymentQueue defaultQueue] finishTransaction: transaction];        }    }}- (voID)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray *)transactions{}@end

主文件,也就是Cocos2d提供的AppController.mm:

#import <UIKit/UIKit.h>#import "cocos2d.h"#import "platform/ios/ccluaObjcBrIDge.h"#import "AppController.h"#import "AppDelegate.h"#import "RootVIEwController.h"#import "platform/ios/CCEAGLVIEw-ios.h"#import "IAPDelegates.h"@implementation AppController{    iAPTransactionObserver* skTransactionObserver;    int nLuaFunctionMemoryWarningCallback;    int nLuaFunctionPaySuccessCallback;    NSMutableDictionary* dictOfPayInfo;    BOol bTriggerAd;}#pragma mark -#pragma mark Application lifecycle// cocos2d application instancestatic AppDelegate s_sharedApplication;static AppController* s_sharedAppController;+ (voID)InitIAp:(NSDictionary *) dict{    [s_sharedAppController applicationInitiAP:dict];}+ (voID)Charge:(NSDictionary *) dict{    [s_sharedAppController applicationPayRequest:dict];}+ (voID)ListenMemoryWarning:(NSDictionary *) dict{    s_sharedAppController->nLuaFunctionMemoryWarningCallback = [[dict objectForKey:@"callback"] intValue];}- (BOol)application:(UIApplication *)application dIDFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    cocos2d::Application *app = cocos2d::Application::getInstance();    app->initGLContextAttrs();    cocos2d::GLVIEwImpl::convertAttrs();    // OverrIDe point for customization after application launch.    // Add the vIEw controller's vIEw to the window and display.    window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];    CCEAGLVIEw *eaglVIEw = [CCEAGLVIEw vIEwWithFrame: [window bounds]                                     pixelFormat: (Nsstring*)cocos2d::GLVIEwImpl::_pixelFormat                                     depthFormat: cocos2d::GLVIEwImpl::_depthFormat                              preserveBackbuffer: NO                                      sharegroup: nil                                   multiSampling: NO                                 numberOfSamples: 0 ];    [eaglVIEw setMultipletouchEnabled:YES];    // Use RootVIEwController manage CCEAGLVIEw    vIEwController = [[RootVIEwController alloc] initWithNibname:nil bundle:nil];    vIEwController.wantsFullScreenLayout = YES;    vIEwController.vIEw = eaglVIEw;    // Set RootVIEwController to window    if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)    {        // warning: addSubVIEw doesn't work on iOS6        [window addSubvIEw: vIEwController.vIEw];    }    else    {        // use this method on ios6        [window setRootVIEwController:vIEwController];    }    [window makeKeyAndVisible];    [[UIApplication sharedApplication] setStatusbarHIDden: YES];    // important: Setting the GLVIEw should be done after creating the RootVIEwController    cocos2d::GLVIEw *glvIEw = cocos2d::GLVIEwImpl::createWithEAGLVIEw(eaglVIEw);    cocos2d::Director::getInstance()->setopenGLVIEw(glvIEw);    s_sharedAppController = self;    app->run();    return YES;}//初始化IAP- (voID)applicationInitiAP:(NSDictionary *) dict{    // Initialize iAp Observer    skTransactionObserver = [[iAPTransactionObserver alloc] init];    ((iAPTransactionObserver *)skTransactionObserver).iosiap = self;    [[SKPaymentQueue defaultQueue] addTransactionObserver:(iAPTransactionObserver *)skTransactionObserver];    int productID = 1;    NSMutableSet *set = [NSMutableSet setWithCapacity:4];//MagicNumber,but doesn't matter.    Nsstring *productname = nil;    while ((productname = [dict objectForKey:[Nsstring stringWithFormat:@"productID_%d",productID]]) != nil) {        productID++;        [set addobject:productname];    }    SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIDentifIErs:set];    iAPProductsRequestDelegate *delegate = [[iAPProductsRequestDelegate alloc] init];    delegate.iosiap = self;    productsRequest.delegate = delegate;    [productsRequest start];}//调用IAP支付, dict中含有{"productID":"xxx","quantity":1,"callback":xx}- (voID)applicationPayRequest:(NSDictionary *) dict{    Nsstring *productID = [dict objectForKey:@"productID"];    for(int i = 0; i < [self.skProducts count]; i++){        SKProduct *skProduct = [self.skProducts objectAtIndex:i];        if([skProduct.productIDentifIEr isEqualToString:productID]){            SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:skProduct];            payment.quantity = [[dict objectForKey:@"quantity"] intValue];            [[SKPaymentQueue defaultQueue] addPayment:payment];            self->nLuaFunctionPaySuccessCallback = [[dict objectForKey:@"callback"] intValue];            break;        }    }}- (voID)applicationWillResignActive:(UIApplication *)application {    /* Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the Transition to the background state. Use this method to pause ongoing tasks,disable timers,and throttle down OpenGL ES frame rates. Games should use this method to pause the game. */    cocos2d::Director::getInstance()->pause();}- (voID)applicationDIDBecomeActive:(UIApplication *)application {    /* Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was prevIoUsly in the background,optionally refresh the user interface. */    cocos2d::Director::getInstance()->resume();}- (voID)applicationDIDEnterBackground:(UIApplication *)application {    /* Use this method to release shared resources,save user data,invalIDate timers,and store enough application state information to restore your application to its current state in case it is terminated later. If your application supports background execution,called instead of applicationWillTerminate: when the user quits. */    cocos2d::Application::getInstance()->applicationDIDEnterBackground();}- (voID)applicationWillEnterForeground:(UIApplication *)application {    /* Called as part of Transition from the background to the inactive state: here you can undo many of the changes made on entering the background. */    cocos2d::Application::getInstance()->applicationWillEnterForeground();}- (voID)applicationWillTerminate:(UIApplication *)application {    /* Called when the application is about to terminate. See also applicationDIDEnterBackground:. */}//支付成功的回调- (voID) onPaymentEvent:(Nsstring *)productID andQuantity:(NSInteger)count{    cocos2d::LuaObjcBrIDge::pushLuaFunctionByID(self->nLuaFunctionPaySuccessCallback);    cocos2d::LuaObjcBrIDge::getStack()->pushLuaValue(cocos2d::LuaValue::stringValue([productID UTF8String]));    cocos2d::LuaObjcBrIDge::getStack()->executeFunction(1);    cocos2d::LuaObjcBrIDge::releaseLuaFunctionByID(self->nLuaFunctionPaySuccessCallback);}#pragma mark -#pragma mark Memory management- (voID)applicationDIDReceiveMemoryWarning:(UIApplication *)application {    /* Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. */     cocos2d::Director::getInstance()->purgeCachedData();    cocos2d::LuaObjcBrIDge::pushLuaFunctionByID(self->nLuaFunctionMemoryWarningCallback);    cocos2d::LuaObjcBrIDge::getStack()->executeFunction(0);    //cocos2d::LuaObjcBrIDge::releaseLuaFunctionByID(self->nLuaFunctionMemoryWarningCallback);}- (voID)dealloc {    [super dealloc];}@end

最后贴一下lua代码中调用的片段:

function IsIOS()    --Lua的区分了iPad和iPhone,估计是历史包袱。    return (cc.Application:getInstance():getTargetPlatform() == cc.PLATFORM_OS_IPHONE) or (cc.Application:getInstance():getTargetPlatform() == cc.PLATFORM_OS_IPAD)end--下面的是函数里的片段if IsIOS() then    local ok,ret = LuaObjcBrIDge.callStaticmethod("AppController","Charge",{            ["productID"]=InfoAboutSDKPay[ID],["quantity"]=1,["callback"]=PaySuccess        })    if(not ok) then        print("AppController.Charge() err",ret)    endend
总结

以上是内存溢出为你收集整理的Cocos2d-Lua 接IOS支付记录全部内容,希望文章能够帮你解决Cocos2d-Lua 接IOS支付记录所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1077107.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存