这里面存了内购的收据,我们应该没次启动app的时候,都对这个data进行检查,如果没有对这个data,进行过充值操作,则应先对齐进行充值操作。建议:调用这个之前,先[[[SKReceiptRefreshRequest alloc] initWithReceiptProperties:@{}]]
来刷新下凭证
此处添加监听,当app重新启动的时候,系统会对上次未完成的交易,自动发送相关通知。
这个方法要慎重调用,只有我们确认交易完成后(我们后台验证,充值之后),才能调用这个方法。 如果我们不调用这个方法,下次用户打开app后,还是会收到相关的交易通知。 如果不调用这个方法,当用户下次购买同一商品的时候,将不会扣除用户的钱,直接返回成功,返回上次的收据。
if ([SKPaymentQueue canMakePayments]) {
// 执行下面提到的第5步:
[self getProductInfo];
} else {
NSLog(@"失败,用户禁止应用内付费购买.");
}
// 下面的ProductId应该是事先在itunesConnect中添加好的,已存在的付费项目。否则查询会失败。
- (void)getProductInfo {
NSSet * set = [NSSet setWithArray:@[@"ProductId"]];
SKProductsRequest * request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
request.delegate = self;
[request start];
}
// 以上查询的回调函数
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSArray *myProduct = response.products;
if (myProduct.count == 0) {
NSLog(@"无法获取产品信息,购买失败。");
return;
}
SKPayment * payment = [SKPayment paymentWithProduct:myProduct[0]];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
- (void)viewDidLoad {
[super viewDidLoad];
// 监听购买结果
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
- (void)viewDidUnload {
[super viewDidUnload];
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased://交易完成
NSLog(@"transactionIdentifier = %@", transaction.transactionIdentifier);
[self completeTransaction:transaction];
break;
case SKPaymentTransactionStateFailed://交易失败
[self failedTransaction:transaction];
break;
case SKPaymentTransactionStateRestored://已经购买过该商品
[self restoreTransaction:transaction];
break;
case SKPaymentTransactionStatePurchasing: //商品添加进列表
NSLog(@"商品添加进列表");
break;
default:
break;
}
}
}
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
// Your application should implement these two methods.
NSString * productIdentifier = transaction.payment.productIdentifier;
NSString * receipt = [transaction.transactionReceipt base64EncodedString];
if ([productIdentifier length] > 0) {
// 向自己的服务器验证购买凭证
}
// 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];
}