Last active
September 13, 2017 22:06
-
-
Save cagatayk/c23e1e8ae92f3a811cad90784777dff7 to your computer and use it in GitHub Desktop.
Simple Receipt Validation Code With the App Store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)getReceiptDataWithCompletionBlock:(void(^)(NSError *error))completionBlock { | |
NSURL *recieptURL = [[NSBundle mainBundle] appStoreReceiptURL]; | |
NSData *recieptData = [NSData dataWithContentsOfURL:recieptURL]; | |
NSMutableDictionary *payLoad; | |
if (recieptData){ | |
payLoad = [NSMutableDictionary dictionaryWithObject:[recieptData base64EncodedStringWithOptions:0] forKey:@"receipt-data"]; | |
} | |
else { | |
payLoad = [NSMutableDictionary dictionary]; | |
} | |
NSError *requestError; | |
NSData *requestData = [NSJSONSerialization dataWithJSONObject:payLoad options:0 error:&requestError]; | |
NSURL *sandboxURL = [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"]; | |
NSURL *liveURL = [NSURL URLWithString:@"https://buy.itunes.apple.com/verifyReceipt"]; | |
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:sandboxURL]; // Use sandboxURL or liveURL according to environment you try | |
[request setHTTPMethod:@"POST"]; | |
[request setHTTPBody:requestData]; | |
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; | |
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { | |
dispatch_async(dispatch_get_main_queue(), ^{ | |
if(!error){ | |
NSError *responseError; | |
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&responseError]; | |
// Handle receipt data here | |
completionBlock(nil); | |
} | |
else { | |
completionBlock(error); | |
} | |
}); | |
}] resume]; | |
[session finishTasksAndInvalidate]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment