我正在使用以下方法获取收据数据:
// Use this method instead of accessing transaction.transactionReceipt directly!
- (NSData *)appStoreReceiptForPaymentTransaction:(SKPaymentTransaction *)transaction {
NSData *receiptData = nil;
// This is just a quick/dummy implementation!
if (kiOS7) {
NSURL *receiptFileURL = [[NSBundle mainBundle] appStoreReceiptURL];
receiptData = [NSData dataWithContentsOfURL:receiptFileURL]; // Returns valid NSData object
} else {
receiptData = transaction.transactionReceipt; // Returns valid NSData object
}
return receiptData;
}
我正在使用以下代码来读取 JSON 收据:
NSData *receipt = [self appStoreReceiptForPaymentTransaction:transaction];
NSError *error = nil;
NSDictionary *receiptDict = [receipt dictionaryFromPlistData:&error];
NSString *transactionPurchaseInfo = [receiptDict objectForKey:@"purchase-info"];
NSString *decodedPurchaseInfo = [NSString stringWithUTF8String:[[NSData dataFromBase64String:transactionPurchaseInfo] bytes]];
NSDictionary *purchaseInfoDict = [[decodedPurchaseInfo dataUsingEncoding:NSUTF8StringEncoding] dictionaryFromPlistData:&error];
NSString *transactionID = [purchaseInfoDict objectForKey:@"transaction-id"];
NSString *purchaseDateString = [purchaseInfoDict objectForKey:@"purchase-date"];
NSString *signature = [receiptDict objectForKey:@"signature"];
NSString *signatureDecoded = [NSString stringWithUTF8String:[[NSData dataFromBase64String:signature] bytes]];
// Convert the string into a date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
NSDate *purchaseDate = [dateFormat dateFromString:[purchaseDateString stringByReplacingOccurrencesOfString:@"Etc/" withString:@""]];
NSLog(@"Raw receipt content: \n%@", [NSString stringWithUTF8String:[receipt bytes]]);
NSLog(@"Purchase Info: %@", purchaseInfoDict);
NSLog(@"Transaction ID: %@", transactionID);
NSLog(@"Purchase Date: %@", purchaseDate);
NSLog(@"Signature: %@", signatureDecoded);
该dictionaryFromPlistData:
方法为返回的数据返回正确的NSDictionary
对象transactionReceipt
,但它使用使用返回的nil
数据返回appStoreReceiptURL
- 因此我没有得到有效的收据!
- (NSDictionary *)dictionaryFromPlistData:(NSError **)outError {
NSError *error;
NSDictionary *dictionaryParsed = [NSPropertyListSerialization propertyListWithData:self
options:NSPropertyListImmutable
format:nil
error:&error];
if (!dictionaryParsed) {
if (error) {
*outError = error;
}
return nil;
}
return dictionaryParsed;
}
为什么上面的代码在 iOS 7 中不起作用?
重申一下,dictionaryFromPlistData:
正确转换NSData
返回的transaction.transactionReceipt
.