Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a PayPal IPN code sample for Ruby on Rails?

Tags:

There are official code samples for several languages but couldn't find one for Rails.

like image 506
joscas Avatar asked Jan 14 '13 10:01

joscas


1 Answers

I post here my working code sample for a Rails controller. It does verification. I hope it will be useful.

class PaymentNotificationsController < ApplicationController   protect_from_forgery :except => [:create] #Otherwise the request from PayPal wouldn't make it to the controller   def create     response = validate_IPN_notification(request.raw_post)     case response     when "VERIFIED"       # check that paymentStatus=Completed       # check that txnId has not been previously processed       # check that receiverEmail is your Primary PayPal email       # check that paymentAmount/paymentCurrency are correct       # process payment     when "INVALID"       # log for investigation     else       # error     end     render :nothing => true   end    protected    def validate_IPN_notification(raw)     live = 'https://ipnpb.paypal.com/cgi-bin'     sandbox = 'https://ipnpb.sandbox.paypal.com/cgi-bin'     uri = URI.parse(sandbox + '/webscr?cmd=_notify-validate')     http = Net::HTTP.new(uri.host, uri.port)     http.open_timeout = 60     http.read_timeout = 60     http.verify_mode = OpenSSL::SSL::VERIFY_PEER     http.use_ssl = true     response = http.post(uri.request_uri, raw,                          'Content-Length' => "#{raw.size}",                          'User-Agent' => "My custom user agent"                        ).body   end end 

Code is inspired by Railscast 142 and this post by Tanel Suurhans

like image 69
joscas Avatar answered Oct 05 '22 13:10

joscas