If you have In App Purchases in your iOS app, apple recommends to validate the purchase. There are to ways: first connecting the apple app store directly within your app, and second send a so called receipt to your own server and having your server perform the validation with the App Store server. I want to digg deeper in the latter one and show you my ruby solution. I was inspired by this gist and this little plugin.
When the iOS App sends you a receipt, first of all you have to encode the data using base64 encoding, i did it in an extra method:
def encode_receipt receipt Base64.encode64(receipt) end
After that, put encoded data in a json object with receipt-data as the key and data as the value and send it via a HTTP POST request to apple.
def json_response_from_verifying_data data parameters = {'receipt-data' => data} uri = URI("https://sandbox.itunes.apple.com/verifyReceipt") # for production use "https://buy.itunes.apple.com/verifyReceipt" http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri) request['Accept'] = "application/json" request['Content-Type'] = "application/json" request.body = parameters.to_json response = http.request(request) JSON.parse(response.body) end
Apple responses with a json object including two keys, status and receipt. If status is 0, the receipt is valid otherwise not. The receipt contains further informations, you can read about it here on apple.
To put it all together, i use a verify method to call the two methods above and return either true if the receipt is valid or false if not.
def verify receipt encoded_receipt = encode_receipt(receipt) json = json_response_from_verifying_data(encoded_receipt) status, receipt_attributes = json['status'].to_i, json['receipt'] if status == 0 # save receipt return true else return false end end
Greate Work really, this post is very very useful for me.
Thank you So much,
keep it up.