quick-cocos2dx中 lua 和oc的通信中,游戏的逻辑是用lua代码,系统是ios系统,主要是oc代码。那么,如果要调用支付代码,该如何调用呢?
这里两者沟通的桥梁主要是使用luaoc这个模块。废话不多说,下面是lua端的例子。代码如下:
local function buySuccess(receipt)
print(" buySuccess! "..receipt)
print(" 调用lua代码向服务器请求验证receipt的正确性")
end
local products = {
productIndex = 1,
}
luaoc.callStaticMethod("MyObserver","buyProduct",products)
luaoc.callStaticMethod("MyObserver","registerScriptHandler",{listener = buySuccess})
可以明确的看出, products是参数,buySuccess是回调函数,buyProduct是MyObserver的一个类。
下面给出oc代码的例子:
--MyObserver.h
#import <UIKit/UIKit.h>
#import <StoreKit/StoreKit.h>
enum
{
IAP60DM = 0,
IAP130DM,
IAP370DM,
IAP720DM,
IAP1650DM,
IAPWUJIN,
}buyDiamondTag;
@interface MyObserver : NSObject<SKProductsRequestDelegate,SKPaymentTransactionObserver>
{
int buyType;
}
+(MyObserver*) sharedInstance;
-(void)requestProUpgradeProductData;
-(void)RequestProductData;
-(bool)CanMakePay;
-(void)buy:(int)type;
-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions;
-(void) PurchasedTransaction: (SKPaymentTransaction *)transaction;
-(void) completeTransaction: (SKPaymentTransaction *)transaction;
-(void) FailedTransaction: (SKPaymentTransaction *)transaction;
-(void) paymentQueueRestoreCompletedTransactionsFinished: (SKPaymentTransaction *)transaction;
-(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error;
-(void) restoreTransaction: (SKPaymentTransaction *)transaction;
-(void)provideContent:(NSString *)product;
-(void)recordTransaction:(NSString *)product;
+(void)buyProduct:(NSDictionary*)info;
+(void)registerScriptHandler:(NSDictionary*)info;
@end
--MyObserver.mm
#import "MyObserver.h"
#import "cocos2d.h"
#include "CCLuaEngine.h"
#include "CCLuaBridge.h"
#define ProductID_IAP60DM @"xinshoudalibao" //6
#define ProductID_IAP130DM @"com.blueBox.130DM" //12
#define ProductID_IAP370DM @"com.blueBox.370DM" //30
#define ProductID_IAP720DM @"com.blueBox.720DM" //50
#define ProductID_IAP1650DM @"com.blueBox.1650DM" //98
#define ProductID_WUJIN @"com.blueBox.WUJIN"
@implementation MyObserver
static MyObserver* _sharedInstance = nil;
static int functionId = 0;
static int buyItemdId = -1;
static NSString * receipt = @"";
static int buySuccess = 1;
+(MyObserver*)sharedInstance
{
@synchronized([MyObserver class])
{
if (!_sharedInstance)
[[self alloc] init];
functionId = 0;
[[SKPaymentQueue defaultQueue] addTransactionObserver:_sharedInstance];
return _sharedInstance;
}
return nil;
}
+(id)alloc
{
@synchronized([MyObserver class])
{
NSAssert(_sharedInstance == nil,@"Attempted to allocate a second instance of a singleton.\n");
_sharedInstance = [super alloc];
return _sharedInstance;
}
return nil;
}
+(void)buyProduct:(NSDictionary*)info
{
int productIndex = 0;
if ([info objectForKey:@"productIndex"])
{
productIndex = [[info objectForKey:@"prodectIndex"] intValue];
}
[[MyObserver sharedInstance] buy:productIndex];
}
+ (void) registerScriptHandler:(NSDictionary*)dict
{
NSLog(@"%s: %@",__func__,dict);
// functionId 是 Lua function 的引用 ID,参考 LuaJavaBridge 文章中的描述
functionId = [[dict objectForKey:@"listener"] intValue]; //保存回调函数
// NSLog(@" functionId %d",functionId);
// // 1. 将引用 ID 对应的 Lua function 放入 Lua stack
// cocos2d::LuaBridge::pushLuaFunctionById(functionId);
//
// // 2. 将需要传递给 Lua function 的参数放入 Lua stack
// cocos2d::LuaBridge::getStack()->pushString("SDK_LEAVE_PLATFORM");
//
// // 3. 执行 Lua function
// cocos2d::LuaBridge::getStack()->executeFunction(1);
// auto director = cocos2d::Director::getInstance();
// director->getScheduler()->schedule([=](float dt)
// {
//// if (buySuccess!=1) {
// NSString *a = @"a";
// NSLog(@" buyItemId %d",buyItemdId);
// cocos2d::LuaBridge::pushLuaFunctionById(functionId);
// cocos2d::LuaBridge::getStack()->pushString([a UTF8String]);
// cocos2d::LuaBridge::getStack()->executeFunction(1);
// // 4. 释放引用 ID
//// cocos2d::LuaBridge::releaseLuaFunctionById(functionId);
//// }
//// NSLog(@" buySuccess %d",buySuccess);
// },self,1.0f,10,0.0f,false,"SHOW_WINDOW_CALLBACK");
}
-(id)init {
self = [super init];
if (self != nil) {
// initialize stuff here
}
return self;
}
-(void)buy:(int)type
{
buyType = type;
buyItemdId = type;
if ([SKPaymentQueue canMakePayments]) {
//[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
[self RequestProductData];
NSLog(@"允许程序内付费购买");
}
else
{
NSLog(@"不允许程序内付费购买");
UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"Alert"
message:@" You can‘t purchase in app store "
delegate:nil cancelButtonTitle:NSLocalizedString(@"Close(关闭)",nil) otherButtonTitles:nil];
[alerView show];
[alerView release];
}
}
-(bool)CanMakePay
{
return [SKPaymentQueue canMakePayments];
}
-(void)RequestProductData
{
NSLog(@"---------请求对应的产品信息------------");
NSArray *product = nil;
switch (buyType) {
case IAP60DM:
product=[[NSArray alloc] initWithObjects:ProductID_IAP60DM,nil];
break;
case IAP130DM:
product=[[NSArray alloc] initWithObjects:ProductID_IAP130DM,nil];
break;
case IAP370DM:
product=[[NSArray alloc] initWithObjects:ProductID_IAP370DM,nil];
break;
case IAP720DM:
product=[[NSArray alloc] initWithObjects:ProductID_IAP720DM,nil];
break;
case IAP1650DM:
product=[[NSArray alloc] initWithObjects:ProductID_IAP1650DM,nil];
break;
case IAPWUJIN:
product = [[NSArray alloc] initWithObjects:ProductID_WUJIN,nil];
default:
break;
}
NSSet *nsset = [NSSet setWithArray:product];
SKProductsRequest *request=[[SKProductsRequest alloc] initWithProductIdentifiers: nsset];
request.delegate=self;
[request start];
[product release];
}
//<SKProductsRequestDelegate> 请求协议
//收到的产品信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
NSLog(@"-----------收到产品反馈信息--------------");
NSArray *myProduct = response.products;
NSLog(@"产品Product ID:%@",response.invalidProductIdentifiers);
NSLog(@"产品付费数量: %d",[myProduct count]);
// populate UI
for(SKProduct *product in myProduct){
NSLog(@"product info");
NSLog(@"SKProduct 描述信息%@",[product description]);
NSLog(@"产品标题 %@",product.localizedTitle);
NSLog(@"产品描述信息: %@",product.localizedDescription);
NSLog(@"价格: %@",product.price);
NSLog(@"Product id: %@",product.productIdentifier);
}
SKPayment *payment = nil;
switch (buyType) {
case IAP60DM:
NSLog(@" xinshoudalibao ");
payment = [SKPayment paymentWithProductIdentifier:ProductID_IAP60DM]; //支付$0.99
break;
case IAP130DM:
payment = [SKPayment paymentWithProductIdentifier:ProductID_IAP130DM]; //支付$1.99
break;
case IAP370DM:
payment = [SKPayment paymentWithProductIdentifier:ProductID_IAP370DM]; //支付$9.99
break;
case IAP720DM:
payment = [SKPayment paymentWithProductIdentifier:ProductID_IAP720DM]; //支付$19.99
break;
case IAP1650DM:
payment = [SKPayment paymentWithProductIdentifier:ProductID_IAP1650DM]; //支付$29.99
break;
case IAPWUJIN:
payment = [SKPayment paymentWithProductIdentifier:ProductID_WUJIN];
break;
default:
break;
}
NSLog(@"---------发送购买请求------------");
[[SKPaymentQueue defaultQueue] addPayment:payment];
[request autorelease];
}
- (void)requestProUpgradeProductData
{
NSLog(@"------请求升级数据---------");
NSSet *productIdentifiers = [NSSet setWithObject:@"com.productid"];
SKProductsRequest* productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
productsRequest.delegate = self;
[productsRequest start];
}
//弹出错误信息
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
NSLog(@"-------弹出错误信息----------");
UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",NULL) message:[error localizedDescription]
delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
[alerView show];
[alerView release];
}
-(void) requestDidFinish:(SKRequest *)request
{
NSLog(@"----------反馈信息结束--------------");
}
-(void) PurchasedTransaction: (SKPaymentTransaction *)transaction{
NSLog(@"-----PurchasedTransaction----");
NSArray *transactions =[[NSArray alloc] initWithObjects:transaction,nil];
[self paymentQueue:[SKPaymentQueue defaultQueue] updatedTransactions:transactions];
[transactions release];
}
//<SKPaymentTransactionObserver> 千万不要忘记绑定,代码如下:
//----监听购买结果
//[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions//交易结果
{
NSLog(@"-----paymentQueue--------");
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased://交易完成
{
[self completeTransaction:transaction];
NSLog(@"-----交易完成 --------");
// cocos2d::LuaEngine::defaultEngine()->executeGlobalFunction("paySuccess");
}
break;
case SKPaymentTransactionStateFailed://交易失败
{
[self FailedTransaction:transaction];
cocos2d::LuaEngine::getInstance()->executeGlobalFunction("payFailure");
NSLog(@"-----交易失败 --------");
}
break;
case SKPaymentTransactionStateRestored://已经购买过该商品
{
[self restoreTransaction:transaction];
NSLog(@"-----已经购买过该商品 --------");
}
break;
case SKPaymentTransactionStatePurchasing: //商品添加进列表
NSLog(@"-----商品添加进列表 --------");
break;
default:
break;
}
}
}
- (void) completeTransaction: (SKPaymentTransaction *)transaction
{
NSLog(@"-----completeTransaction--------");
// Your application should implement these two methods.
// NSString *product = transaction.payment.productIdentifier;
// if ([product length] > 0) {
//
// NSArray *tt = [product componentsSeparatedByString:@"."];
// NSString *bookid = [tt lastObject];
// if ([bookid length] > 0) {
// [self recordTransaction:bookid];
// [self provideContent:bookid];
// }
// }
// Your application should implement these two methods.
NSString * productIdentifier = transaction.payment.productIdentifier;
receipt = [transaction.transactionReceipt base64Encoding];
// NSData *working = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
// // Tried 64 or 76 chars/line and LF or CR line endings
// NSString *receipt = [working base64EncodedStringWithOptions:kNilOptions];
// [transaction.transactionReceipt base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
// NSLog(@"%@ ",receipt);
if ([productIdentifier length] > 0) {
// 向自己的服务器验证购买凭证
cocos2d::LuaBridge::pushLuaFunctionById(functionId);
cocos2d::LuaBridge::getStack()->pushString([receipt UTF8String]);
cocos2d::LuaBridge::getStack()->executeFunction(1);
}
// Remove the transaction from the payment queue.
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
//记录交易
-(void)recordTransaction:(NSString *)product{
NSLog(@"-----记录交易--------");
}
//处理下载内容
-(void)provideContent:(NSString *)product{
NSLog(@"-----下载--------");
}
- (void) FailedTransaction: (SKPaymentTransaction *)transaction{
NSLog(@"失败");
if (transaction.error.code != SKErrorPaymentCancelled)
{
}
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
-(void) paymentQueueRestoreCompletedTransactionsFinished: (SKPaymentTransaction *)transaction{
}
- (void) restoreTransaction: (SKPaymentTransaction *)transaction
{
NSLog(@" 交易恢复处理");
}
-(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error{
NSLog(@"-------paymentQueue----");
}
#pragma mark connection delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"%@",[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@" didReceiveResponse! ");
switch([(NSHTTPURLResponse *)response statusCode]) {
case 200:
case 206:
break;
case 304:
break;
case 400:
break;
case 404:
break;
case 416:
break;
case 403:
break;
case 401:
case 500:
break;
default:
break;
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"test");
}
-(void)dealloc
{
[super dealloc];
}
@end
代码都有,主要是写了一个buyProduct的函数。这个函数在lua中调用,在oc中实现,实现其中的功能。写了一个mm文件。
这样就能够沟通了。
原文链接:https://www.f2er.com/cocos2dx/340217.html