Validating receipts from Apple iPhone store in Ruby

Recently, I had to write a service on Ruby-on-Rails project to validate an in-store purchase for iPhone application. Though, it was fairly straight forward, but I am posting the code in case someone else needs it:

  1 require 'net/http'                                                                                                                                                                                                                                                            

  2 require 'net/https'
  3 require 'uri'
  4
  5 class AppleReceiptVerifier 

  6   #
  7   ### Verifies Apple receipt submitted by iPhone 
  8   ### See http://developer.apple.com/iphone/library/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Overview%20of%20the%20Store%20Kit%20API/OverviewoftheStoreKitAPI.html#//apple_ref/doc/uid/TP40008267-CH100-SW14

  9   #
 10   def self.verify(b64_receipt)
 11     url = URI.parse(APPLE_RECEIPT_VERIFY_URL)

 12     http = Net::HTTP.new(url.host, url.port)
 13     http.use_ssl = true
 14     http.verify_mode = OpenSSL::SSL::VERIFY_NONE

 15     valid = false
 16     json_request = {'receipt-data' => b64_receipt}.to_json
 17     resp, resp_body = http.post(url.path, json_request.to_s, {'Content-Type' => 'application/x-www-form-urlencoded'})

 18     if resp.code == '200'
 19       json_resp = JSON.parse(resp_body)
 20       if json_resp['status'] == 0

 21         valid = true
 22       end
 23     end
 24     valid
 25   end 

 26 end
 27
 28
 

Note that the receipt returned by iPhone APIs is not base 64 encoded so you will need to encode it before calling the service. Also, for testing, APPLE_RECEIPT_VERIFY_URL will point to the sandbox environment, i.e., https://sandbox.itunes.apple.com/verifyReceipt and for real purchase it will point to https://buy.itunes.apple.com/verifyReceipt. Finally, you can learn more from the Apple documentation on purchase model and on validating receipts.


contact me using:

"bhatti AT plexobject DOT com". or tweet me at "http://twitter.com/bhatti_shahzad".