只要 App 裡涉及虛擬物品交易,就繞不開 StoreKit 與 IAP。這篇從流程設計講到程式碼落地,把容易踩坑的環節都標出來。
IAP 有兩種常見架構:完全由 Apple 伺服器完成購買與驗證,或者自建後端參與驗證。
實務上幾乎都選第二種,原因有兩個:國內訪問 Apple 驗證介面延遲明顯,把驗證放在自己的伺服器可以異步化、可重試;更重要的是防偽造,憑證只存在用戶裝置上時,越獄環境下被改寫的風險很高。
「發貨」這一步務必放在後端確認之後,只依賴客戶端本地判斷等於把商品免費送出去。
登入 iTunes Connect 建立 App,此處的 Bundle ID 必須與專案 Info.plist 中的 Bundle Identifier 完全一致,否則後續所有測試都會失敗。
蘋果把虛擬物品分成五型:
第 2、3、5 型以 Apple ID 為粒度:同一個 Apple ID 在多台裝置上都可用。第 1、4 型通常是現買現用;需要更強的業務控制時,多數團隊會選第 4 型。
建立完成後,每個商品都會得到一組由字母與數字組成的 Product ID,App 正是靠它向 Apple 查詢商品資訊,命名一旦上線就不要再改。
這一步常被忽略:稅務、協議和收款資訊沒有填完,SKProductsRequest 一定拿不到商品資料,回傳的 products 會是空陣列。測試前請先確認相關狀態已就緒。
首先要在專案裡加入 StoreKit.framework。以下假設商品列表已從後端取得,且每個商品對應的 productIdentifier 存在 self.productIdent 中。
- (void)dealloc {
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView.mj_header beginRefreshing];
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
- (void)buyProduction:(UIButton *)sender {
if ([SKPaymentQueue canMakePayments]) {
[self getProductInfo:self.productIdent];
} else {
[self showMessage:@"使用者已禁止應用內付費購買"];
}
}
addTransactionObserver: 一定要在 viewDidLoad 註冊、dealloc 移除,否則交易狀態變化會收不到,而出現「錢扣了但沒發貨」的窘境。
- (void)getProductInfo:(NSString *)productIdentifier {
NSArray *product = @[productIdentifier];
NSSet *set = [NSSet setWithArray:product];
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
request.delegate = self;
[request start];
[self showMessageManualHide:@"正在購買,請稍後"];
}
// 查詢成功
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
[self hideHUD];
NSArray *myProduct = response.products;
if (myProduct.count == 0) {
[self showMessage:@"無法獲取產品資訊,請重試"];
return;
}
SKPayment *payment = [SKPayment paymentWithProduct:myProduct[0]];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
// 查詢失敗
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
[self hideHUD];
[self showMessage:[error localizedDescription]];
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
[self hideHUD];
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased: {
self.receipt = [GTMBase64 stringByEncodingData:
[NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]]];
[self checkReceiptIsValid]; // 送到後端驗證
[self completeTransaction:transaction];
break;
}
case SKPaymentTransactionStateFailed:
[self failedTransaction:transaction];
break;
case SKPaymentTransactionStateRestored:
[self showMessage:@"恢復購買成功"];
[self restoreTransaction:transaction];
break;
case SKPaymentTransactionStatePurchasing:
[self showMessage:@"正在請求付費資訊,請稍後"];
break;
default:
break;
}
}
}
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
if (transaction.error.code != SKErrorPaymentCancelled) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
message:@"購買失敗,請重試"
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"重試", nil];
[alertView show];
} else {
[self showMessage:@"使用者取消交易"];
}
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
切記:交易必須在處理完畢後呼叫 finishTransaction:,否則它會一直留在佇列裡被反覆回調。
- (void)checkReceiptIsValid {
[[AFHTTPSessionManager manager] GET:@"後台服務器地址"
parameters:@{@"receipt": self.receipt}
success:^(NSURLSessionDataTask *task, id responseObject) {
if (憑證有效) {
// 發放權益、更新本地狀態
} else {
// 提示使用者並記錄,等待人工或自動重試
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
message:@"購買失敗,請重試"
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"重試", nil];
[alertView show];
}];
}
網絡不穩是常態。憑證發送失敗時,必須把它落地保存,等下次啟動再重試,直到成功為止。
#define AppStoreInfoLocalFilePath [NSString stringWithFormat:@"%@/%@/", \
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], @"EACEF35FE363A75A"]
+ (NSString *)getUUIDString {
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef strRef = CFUUIDCreateString(kCFAllocatorDefault, uuidRef);
NSString *uuidString = [(__bridge NSString *)strRef stringByReplacingOccurrencesOfString:@"-" withString:@""];
CFRelease(strRef);
CFRelease(uuidRef);
return uuidString;
}
- (void)saveReceipt {
NSString *fileName = [AppUtils getUUIDString];
NSString *savedPath = [NSString stringWithFormat:@"%@%@.plist", AppStoreInfoLocalFilePath, fileName];
NSDictionary *dic = {
Request_transactionReceipt : self.receipt,
DATE : self.date,
USERID: self.userId
};
[dic writeToFile:savedPath atomically:YES];
}
檔名用 UUID 而非固定字串,是為了支援「同一用戶多筆未驗證交易」的情況;每筆記錄再附帶日期與用戶 ID,後端就能分辨歸屬。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:AppStoreInfoLocalFilePath]) {
[fileManager createDirectoryAtPath:AppStoreInfoLocalFilePath
withIntermediateDirectories:YES attributes:nil error:nil];
} else {
[self sendFailedIapFiles];
}
return YES;
}
- (void)sendFailedIapFiles {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *cacheFileNameArray = [fileManager contentsOfDirectoryAtPath:AppStoreInfoLocalFilePath error:&error];
if (error == nil) {
for (NSString *name in cacheFileNameArray) {
if ([name hasSuffix:@".plist"]) {
NSString *filePath = [NSString stringWithFormat:@"%@/%@", AppStoreInfoLocalFilePath, name];
[self sendAppStoreRequestBuyPlist:filePath];
}
}
} else {
DebugLog(@"AppStoreInfoLocalFilePath error:%@", [error domain]);
}
}
- (void)sendAppStoreRequestBuyPlist:(NSString *)plistPath {
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[dic objectForKey:USERID], USERID,
[dic objectForKey:DATE], DATE,
[dic objectForKey:Receipt], Receipt, nil];
[[AFHTTPSessionManager manager] GET:@"後台服務器地址"
parameters:params
success:^(NSURLSessionDataTask *task, id responseObject) {
if (憑證有效) {
[self removeReceipt];
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
// 保留檔案,等待下次啟動再試
}];
}
- (void)removeReceipt {
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:AppStoreInfoLocalFilePath]) {
[fileManager removeItemAtPath:AppStoreInfoLocalFilePath error:nil];
}
}