应用内购买有一个请求队列。如果您的请求未完成,它将保留在队列中,并且当您的应用重新启动时将尝试继续请求。通过调用适当的方法来完成请求是开发人员的责任。
请记住:Apple 的沙盒服务可能很慢,实时服务器应该快得多。
就在今天,我将应用内购买集成到一个应用程序中,我将在下面发布代码以用于教育目的。我选择将所有代码放入单例中。可能不是最好的解决方案(也许是,也许不是),但就我的目的而言,效果很好。我的商店目前只处理 1 种产品,在销售更多产品时代码可能有点不切实际,但我会尽量记住这一点。
PS:请注意下面的代码是一个正在进行的工作。不过,它似乎对我来说很好,所以它可能会帮助你解决你的问题。
产品商店.h
@interface FSProductStore : NSObject
+ (FSProductStore *)defaultStore;
// AppDelegate should call this on app start (appDidFinishLoading) ...
- (void)registerObserver;
// handling product requests ...
- (void)startProductRequestWithIdentifier:(NSString *)productIdentifier
completionHandler:(void (^)(BOOL success, NSError *error))completionHandler;
- (void)cancelProductRequest;
@end
FSProductStore.m
#import "FSProductStore.h"
#import <StoreKit/StoreKit.h>
#import "NSData+Base64.h"
#import "AFNetworking.h"
#import "FSTransaction.h"
@interface FSProductStore () <SKProductsRequestDelegate, SKPaymentTransactionObserver>
- (void)startTransaction:(SKPaymentTransaction *)transaction;
- (void)completeTransaction:(SKPaymentTransaction *)transaction;
- (void)failedTransaction:(SKPaymentTransaction *)transaction;
- (void)restoreTransaction:(SKPaymentTransaction *)transaction;
- (void)validateReceipt:(NSData *)receiptData withCompletionHandler:(void (^)(BOOL success, NSError *error))completionHandler;
- (void)purchaseSuccess:(NSString *)productIdentifier;
- (void)purchaseFailedWithError:(NSError *)error;
@property (nonatomic, strong) SKProductsRequest *currentProductRequest;
@property (nonatomic, copy) void (^completionHandler)(BOOL success, NSError *error);
@end
@implementation FSProductStore
+ (FSProductStore *)defaultStore
{
static FSProductStore *store;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (!store)
{
store = [[FSProductStore alloc] init];
}
});
return store;
}
- (void)registerObserver
{
DLog(@"registering observer ...");
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
#pragma mark - Products request delegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
if (!response.products || response.products.count == 0)
{
NSError *error = [NSError errorWithDomain:FSMyAppErrorDomain code:FSNoProductsAvailableError];
[self purchaseFailedWithError:error];
}
else
{
SKProduct *product = response.products[0];
SKPayment *payment = [SKPayment paymentWithProduct:product];
if ([SKPaymentQueue canMakePayments])
{
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
else
{
NSError *error = [NSError errorWithDomain:FSMyAppErrorDomain code:FSInAppPurchaseDisabledError];
[self purchaseFailedWithError:error];
}
DLog(@"%@", response.products);
}
}
#pragma mark - Payment transaction observer
// Sent when the transaction array has changed (additions or state changes). Client should check state of transactions and finish as appropriate.
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
DLog(@"%@", transactions);
for (SKPaymentTransaction *transaction in transactions)
{
DLog(@"%@", transaction);
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchasing: [self startTransaction:transaction]; break;
case SKPaymentTransactionStateFailed: [self failedTransaction:transaction]; break;
case SKPaymentTransactionStatePurchased: [self completeTransaction:transaction]; break;
case SKPaymentTransactionStateRestored: [self restoreTransaction:transaction]; break;
default: break;
}
}
}
// Sent when an error is encountered while adding transactions from the user's purchase history back to the queue.
- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error
{
DLog(@"%@", error);
[self purchaseFailedWithError:error];
}
// Sent when transactions are removed from the queue (via finishTransaction:).
- (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray *)transactions
{
DLog(@"%@", transactions);
}
// Sent when all transactions from the user's purchase history have successfully been added back to the queue.
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
{
DLog(@"%@", queue);
}
// Sent when the download state has changed.
- (void)paymentQueue:(SKPaymentQueue *)queue updatedDownloads:(NSArray *)downloads
{
DLog(@"%@", downloads);
}
#pragma mark - Public methods
- (void)startProductRequestWithIdentifier:(NSString *)productIdentifier
completionHandler:(void (^)(BOOL success, NSError *error))completionHandler
{
if ([productIdentifier isEqualToString:FS_PRODUCT_DISABLE_ADS] == NO)
{
DLog(@"ERROR: invalid product identifier!");
NSError *error = [NSError errorWithDomain:FSMyAppErrorDomain code:FSInvalidProductIdentifier];
if (completionHandler)
{
completionHandler(NO, error);
}
return;
}
// cancel any existing product request (if exists) ...
[self cancelProductRequest];
// start new request ...
self.completionHandler = completionHandler;
NSSet *productIdentifiers = [NSSet setWithObject:productIdentifier];
self.currentProductRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
_currentProductRequest.delegate = self;
[_currentProductRequest start];
}
- (void)cancelProductRequest
{
if (_currentProductRequest)
{
DLog(@"cancelling existing request ...");
[_currentProductRequest setDelegate:nil];
[_currentProductRequest cancel];
}
}
#pragma mark - Private methods
- (void)startTransaction:(SKPaymentTransaction *)transaction
{
DLog(@"starting transaction: %@", transaction);
}
- (void)completeTransaction: (SKPaymentTransaction *)transaction
{
[self validateReceipt:transaction.transactionReceipt withCompletionHandler:^ (BOOL success, NSError *error) {
if (success)
{
// Your application should implement these two methods.
[self recordTransaction:transaction];
[self purchaseSuccess:transaction.payment.productIdentifier];
}
else
{
// deal with error ...
[self purchaseFailedWithError:error];
}
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}];
}
- (void)failedTransaction: (SKPaymentTransaction *)transaction
{
if (transaction.error.code != SKErrorPaymentCancelled) {
[self purchaseFailedWithError:transaction.error];
}
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)restoreTransaction: (SKPaymentTransaction *)transaction
{
[self recordTransaction:transaction];
[self purchaseSuccess:transaction.originalTransaction.payment.productIdentifier];
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)recordTransaction:(SKPaymentTransaction *)transaction
{
DLog(@"recording transaction: %@", transaction);
// TODO: store for audit trail - perhaps on remote server?
FSTransaction *transactionToRecord = [FSTransaction transactionWithIdentifier:transaction.transactionIdentifier receipt:transaction.transactionReceipt];
[transactionToRecord store];
}
- (void)purchaseSuccess:(NSString *)productIdentifier
{
// TODO: make purchase available to user - perhaps call completion block?
DLog(@"transaction success for product: %@", productIdentifier);
self.currentProductRequest = nil;
if (_completionHandler)
{
_completionHandler(YES, nil);
}
}
- (void)purchaseFailedWithError:(NSError *)error
{
DLog(@"%@", error);
self.currentProductRequest = nil;
if (_completionHandler)
{
_completionHandler(NO, error);
}
}
- (void)validateReceipt:(NSData *)receiptData withCompletionHandler:(void (^)(BOOL success, NSError *error))completionHandler
{
DLog(@"validating receipt with Apple ...");
NSString *body = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", [receiptData base64EncodedString]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:FS_URL_APPLE_VERIFY_RECEIPT];
request.HTTPMethod = @"POST";
request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^ (NSURLRequest *request, NSURLResponse *response, id JSON) {
DLog(@"%@", JSON);
NSNumber *number = [JSON objectForKey:@"status"];
BOOL success = number && (number.integerValue == 0);
NSError *error = success ? nil : [NSError errorWithDomain:FSMyAppErrorDomain code:FSInvalidProductReceipt];
if (completionHandler)
{
completionHandler(success, error);
}
} failure:^ (NSURLRequest *request, NSURLResponse *response, NSError *error, id JSON) {
if (completionHandler)
{
completionHandler(NO, error);
}
}];
[operation start];
}
@end
这个类的设计的好处是它有点像一个用于应用内购买的黑盒子。使用该类相当容易,例如以下代码用于购买“禁用广告”产品:
- (void)disableAds
{
[self showLoadingIndicator:YES forView:self.tableView];
[[FSProductStore defaultStore] startProductRequestWithIdentifier:FS_PRODUCT_DISABLE_ADS completionHandler:^ (BOOL success, NSError *error) {
[self showLoadingIndicator:NO forView:self.tableView];
DLog(@"%d %@", success, error);
if (success)
{
NSNumber *object = [NSNumber numberWithBool:YES];
[[NSNotificationCenter defaultCenter] postNotificationName:FSShouldDisableAdsNotification object:object];
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
if (indexPath)
{
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}
else
{
[UIAlertView showAlertViewWithError:error delegate:self];
}
}];
}
PS:以下宏用于收据验证 URL。我有 3 个方案:调试(开发)、发布(测试)和分发(AppStore):
// In-App purchase: we'll use the Sandbox environment for test versions ...
#if (DEBUG || RELEASE)
#define FS_URL_APPLE_VERIFY_RECEIPT [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"]
#else // DISTRIBUTION
#define FS_URL_APPLE_VERIFY_RECEIPT [NSURL URLWithString:@"https://buy.itunes.apple.com/verifyReceipt"]
#endif // (DEBUG || RELEASE)