在IAP中,首先,我遵循了链接中的指令:http://troybrant.net/blog/2010/01/in-app-purchases-a-full-walkthrough/
幸运而迅速的是,我弹出了IAP对话框(售价0.99美元购买XXX )。一切似乎都正常!然后我开始处理收据验证的问题。
一两天后,我得到了无效的产品ID。我几乎在任何地方都添加了断点,最后,我发现
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
方法根本没有被调用。然后它花了我大约2周谷歌所有东西,我没有任何进展。然后我删除了我的startPayment方法
- (void)startPayment
{
SKPayment *payment = [SKPayment paymentWithProduct: myProduct];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
并在行中添加了一个断点。
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
好的,我发现方法在等待3-5秒后被调用,并且没有无效的Product 问题。
因此,我在startPayment方法中调用了productsRequest didReceiveResponse方法。是的,无效的产品ID问题消失了,但我遇到了另一个问题。
我的应用程序在等待2-3秒后崩溃(返回到iPhone的主菜单),然后IAP对话框在1-2秒后弹出。看起来,对话框直接弹出在iPhone的主菜单上。当我再次点击应用程序的图标时,对话框消失了,应用程序从一开始就开始加载。
有人能告诉我到底怎么回事吗?非常感谢!
发布于 2012-12-31 03:58:00
应用程序内的采购有一个请求队列。如果您的请求尚未完成,它将保留在队列中,当您的应用程序重新启动时,将尝试继续执行该请求。开发人员有责任通过调用适当的方法来完成请求。
记住:苹果的沙箱服务可能是缓慢的,实时服务器应该更快。
就在今天,我将应用程序购买集成到一个应用程序中,我将把下面的代码用于教育目的。我选择把所有的代码都放到一个Singleton中。也许不是最好的解决方案(也许是,也许不是),但就我而言,它的效果很好。我的商店目前只处理一个产品,在销售更多的产品时,代码可能有点不切实际,尽管我确实试图记住这一点。
P.S:,请注意下面的代码正在进行中。虽然这对我来说似乎很好,所以它可能会帮助你解决你的问题。
ProductStore.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];
}
}];
}
P.S.:以下宏用于接收验证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)
https://stackoverflow.com/questions/14093013
复制相似问题