#import <StoreKit/StoreKit.h>
<SKProductsRequestDelegate,SKPaymentTransactionObserver>
1、根据商品id,请求商品列表
NSArray *product = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ProductList" ofType:@"plist"]]; NSSet *nsset = [NSSet setWithArray:product]; SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset]; request.delegate = self; [request start];
2、请求结果
//收到产品返回信息- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{ //商品信息 NSArray *product = response.products;}//请求失败- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{}//请求结束- (void)requestDidFinish:(SKRequest *)request{}
3、发起支付请求
SKPayment *payment = [SKPayment paymentWithProduct:product];[[SKPaymentQueue defaultQueue] addPayment:payment];
4、监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction{ for(SKPaymentTransaction *tran in transaction){ switch (tran.transactionState) { case SKPaymentTransactionStatePurchased:{ NSLog(@"交易完成"); // 发送到苹果服务器验证凭证 [self verifyPurchaseWithPaymentTransaction]; [[SKPaymentQueue defaultQueue] finishTransaction:tran]; } break; case SKPaymentTransactionStatePurchasing: NSLog(@"商品添加进列表"); break; case SKPaymentTransactionStateRestored:{ NSLog(@"已经购买过商品"); [[SKPaymentQueue defaultQueue] finishTransaction:tran]; } break; case SKPaymentTransactionStateFailed:{ NSLog(@"交易失败"); [[SKPaymentQueue defaultQueue] finishTransaction:tran]; [SVProgressHUD showErrorWithStatus:@"购买失败"]; } break; default: break; } }}
5、验证购买结果
-(void)verifyPurchaseWithPaymentTransaction{ //从沙盒中获取交易凭证并且拼接成请求体数据 NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL]; NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl]; //转化为base64字符串 NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]; //拼接请求数据 NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString]; NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; //创建请求到苹果官方进行购买验证 NSURL *url=[NSURL URLWithString:AppStore]; NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url]; requestM.HTTPBody=bodyData; requestM.HTTPMethod=@"POST"; //创建连接并发送同步请求 NSError *error=nil; NSData *responseData=[NSURLConnection sendSynchronousRequest:requestM returningResponse:nil error:&error]; if (error) { NSLog(@"验证购买过程中发生错误,错误信息:%@",error.localizedDescription); return; } NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@",dic); if([dic[@"status"] intValue]==0){ NSLog(@"购买成功!"); }else{ NSLog(@"购买失败,未通过验证!"); }}
6、交易结束
//交易结束- (void)completeTransaction:(SKPaymentTransaction *)transaction{ NSLog(@"交易结束"); [[SKPaymentQueue defaultQueue] finishTransaction:transaction];}