现在手机游戏免费模式+道具购买成为主流,所以iOS开发的游戏需要集成苹果的IAP功能。
IAP的流程
当用户点击商店时,App会向App Store发送商品列表请求,并获得所有商品的信息。其实这一步不需要,只需要在本地保存所有商品信息并显示。当用户选择某一具体的商品并点击购买时,App会向App store发送购买请求(payment request)包含商品id(product id)信息。App strore处理完购买请求,并返回一个tranction。App根据tranction信息像用户显示购买完成信息。
测试
1.添加测试App
我们可以创建测试程序来对IAP进行测试。首先打开iTune connect,并添加一个测试App。需要注意的是,因为我们要使用IAP功能,我们的app bundle identifier不能用*的方式,必须使用唯一的bundle identifier。
2. 添加商品
商品拥有唯一的id,我添加了4个测试商品,其中商品one有唯一的id: com.chupeng.one。
3.写测试程序
请求产品信息
-(void)RequestProductData
{
CCLOG(@"---------请求对应的产品信息------------");
NSArray *product = [[NSArray alloc] initWithObjects:@"com.chupeng.one",nil];
NSSet *nsset = [NSSet setWithArray:product];
SKProductsRequest *request=[[SKProductsRequest alloc] initWithProductIdentifiers: nsset];
request.delegate=self;
[request start];
[product release];
}
- (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);
}
}
发送购买payment请求
SKPayment *payment = [SKPayment paymentWithProductIdentifier:@"com.chupeng.one"]; ;
CCLOG(@"---------发送购买请求------------");
[[SKPaymentQueue defaultQueue] addPayment:payment];
[request autorelease];
处理tranction
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions//交易结果
{
CCLOG(@"-----paymentQueue--------");
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased://交易完成
[self completeTransaction:transaction];
CCLOG(@"-----交易完成 --------");
CCLOG(@"不允许程序内付费购买");
UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"购买成功" delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
[alerView show];
[alerView release];
break;
case SKPaymentTransactionStateFailed://交易失败
[self failedTransaction:transaction];
CCLOG(@"-----交易失败 --------");
UIAlertView *alerView2 = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"购买失败" delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
[alerView2 show];
[alerView2 release];
break;
case SKPaymentTransactionStateRestored://已经购买过该商品
[self restoreTransaction:transaction];
CCLOG(@"-----已经购买过该商品 --------");
case SKPaymentTransactionStatePurchasing: //商品添加进列表
CCLOG(@"-----商品添加进列表 --------");
break;
default:
break;
}
}
}