Last active
December 15, 2015 21:29
-
-
Save joshtwist/5326614 to your computer and use it in GitHub Desktop.
Simple sample of In-App purchase receipt verification and storage in Mobile Services DB
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
// This server script 'swizzles' the data. It takes an item that will NOT be inserted to the database. | |
// Instead the item.receipt property is forwarded to the App Store to verify the receipt is valid. If so, | |
// Apple will return a full receipt with many properties including the purchase time, product Id etc. | |
// Instead then, we insert this data to the database along with the userId so we know who made the purchase. | |
var req = require('request'); | |
var table = tables.getTable('receipts'); | |
function insert(item, user, request) { | |
req.post({ | |
// change this to buy.itunes.apple.com for production | |
url: 'https://sandbox.itunes.apple.com/verifyReceipt', | |
body: JSON.stringify({ "receipt-data" : new Buffer(item.receipt).toString('base64') }) | |
}, function(e, r, body) { | |
if (r.statusCode !== 200) { | |
console.error(r); | |
request.respond(400, "Failed to verify receipt"); | |
} | |
else { | |
var data = JSON.parse(body); | |
if (data.status === 0) { | |
// we're good. Insert the receipt to the DB | |
data.receipt.userId = user.userId; | |
table.insert(data.receipt, { | |
success: function() { | |
request.respond(200, data.receipt); | |
} | |
}) | |
} | |
else { | |
console.error(r); | |
request.respond(500, { status: data.status, error: "receipt validation failed" }); | |
} | |
} | |
}); | |
} |
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
// this is from the client code - simply pass the transactionReceipt property of the SKPaymentTransaction | |
// as the receipt parameter to the method below. This will POST the data to the mobile service which will, | |
// in turn, invoke the insert function on the server shown in this gist | |
- (void)insertReceipt:(NSData *)receipt completion:(CompletionBlock)completion | |
{ | |
NSString *string = [[NSString alloc] initWithData:receipt encoding:NSUTF8StringEncoding]; | |
[self.receipts insert:@{ @"receipt" : string } completion:^(NSDictionary *item, NSError *error) { | |
completion(); | |
}]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment