首先,您应该真正返回并查看 Apple 提供的应用内购买文档- 他们详细概述了这一点,了解他们正在做的事情很有用。
您缺少的是 SKPaymentTransactionObserver - 您有责任实现这个观察者,您将其添加为 SKPaymentTransactionQueue 的观察者。Apple 建议您将应用程序启动时的观察者添加到默认队列,以便它能够观察您的应用程序运行时发生的所有事务。
本质上,您需要编写自己的类来实现 SKPaymentTransactionObserver 协议。这个类的作用是观察在 iTunes 商店处理付款时从付款队列中捕获回调,并让您捕获成功和失败事件。
这是支付观察者的框架:
PaymentObserver.h
#import <StoreKit/StoreKit.h>
@interface PaymentObserver : NSObject <SKPaymentTransactionObserver> {
}
- (void) completeTransaction: (SKPaymentTransaction *)transaction;
- (void) restoreTransaction: (SKPaymentTransaction *)transaction;
- (void) failedTransaction: (SKPaymentTransaction *)transaction;
@end
PaymentObserver.m
#import "PaymentObserver.h"
@implementation PaymentObserver
- (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray *)transactions
{
// handle payment cancellation
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
// handle the payment transaction actions for each state
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased:
[self completeTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
[self failedTransaction:transaction];
break;
case SKPaymentTransactionStateRestored:
[self restoreTransaction:transaction];
default:
break;
}
}
}
- (void) completeTransaction: (SKPaymentTransaction *)transaction;
{
// Record the transaction
//...
// Do whatever you need to do to provide the service/subscription purchased
//...
// Remove the transaction from the payment queue.
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- (void) restoreTransaction: (SKPaymentTransaction *)transaction
{
// Record the transaction
//...
// Do whatever you need to do to provide the service/subscription purchased
//...
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
if (transaction.error.code != SKErrorPaymentCancelled)
{
// Optionally, display an error here.
}
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
@end
实现 PaymentObserver 后,您需要将一个实例添加到默认支付队列中作为事务观察者。
// Done at app launch...
PaymentObserver *paymentObserver = [[PaymentObserver alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:paymentObserver];