我們在內購開發(fā)中亦鳞,購買成功后。要把這次交易的憑證發(fā)送給服務器棒坏。讓服務器去驗證這次交易是否真實。
拿到憑證的代碼:
NSURL* receiptURL = [[NSBundle mainBundle]appStoreReceiptURL];
//這里直接轉成base64是因為要發(fā)生給服務器遭笋。
NSString* receipt = [[NSData dataWithContentsOfURL:receiptURL]base64EncodedStringWithOptions:0];
但是發(fā)生過去后坝冕,發(fā)送一直憑證錯誤。導致浪費了瓦呼,三個小時時間在找問題上喂窟。后來测暗,對比發(fā)送前和發(fā)送后的憑證。發(fā)現(xiàn)磨澡!+變成了“ ”(空格)
研究后碗啄,這個特殊字符發(fā)送過去后,會發(fā)生改變稳摄。查資料后稚字,解決辦法如下:
NSURL* receiptURL = [[NSBundle mainBundle]appStoreReceiptURL];
NSString* receipt = [[NSData dataWithContentsOfURL:receiptURL]base64EncodedStringWithOptions:0];
receipt = [receipt stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%<>[\\]^`{|}\"]+"].invertedSet];
加一行代碼就??OK!
實際開發(fā)中厦酬,我們還可以自己去官網上先驗證一下憑證,然后再發(fā)生給服務器:
這里有個有趣現(xiàn)象胆描,就是不加上面那段代碼,發(fā)送給蘋果也是正常的仗阅,估計蘋果那里做了處理昌讲。把空格替換為+號了。
NSURL* receiptURL = [[NSBundle mainBundle]appStoreReceiptURL];
//這里直接轉成base64是因為要發(fā)生給服務器减噪。
NSString* receipt = [[NSData dataWithContentsOfURL:receiptURL]base64EncodedStringWithOptions:0];
~~~//======這里有個有趣現(xiàn)象短绸,就是不加上面那段代碼,發(fā)送給蘋果也是正常的筹裕,估計蘋果那里做了處理醋闭。把空格替換為+號了。======
.....................................
.....................................
NSError *error;
NSDictionary *requestContents = @{
@"receipt-data": receipt
};
NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents
options:0
error:&error];
if (!requestData) { /* ... Handle error ... */ }
// Create a POST request with the receipt data.
//正式環(huán)境請?zhí)鎿Q下面的地址為https://buy.itunes.apple.com/verifyReceipt
NSURL *storeURL = [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"];
NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:storeURL];
[storeRequest setHTTPMethod:@"POST"];
[storeRequest setHTTPBody:requestData];
// Make a connection to the iTunes Store on a background queue.
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:storeRequest queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
/* ... Handle error ... */
} else {
NSError *error;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
if (!jsonResponse) { /* ... Handle error ...*/ }
/* ... Send a response back to the device ... */
}
}];