Online Payment Solution for RoR Application: PayPal - IPN




... continued from PayPal Integration Basics


If you want to do some operations after getting payment confirmation i.e. Instant Payment Notification(IPN) which would sent by PayPal after every transaction (either completed or not), then you can follow next steps:
  1. First of all you need to enable IPN in your paypal account. Login to merchant account -> Profile -> Instant Payment Notification Preferences -> Enter notification url and select radio button "Receive IPN messages" -> Save
Note: You cannot get IPN on your rails local server, as you cannot set local address of your application while enable IPN from your paypal account.
  1. After getting IPN, you can make any operation according to your application's need. In my app, I am going to make operations on my new model after getting IPN. For this, generate a new model and migrate it to database:
$ rails generate model order product_id:integer quantity:integer amount:decimal status:string

$ rake db:migrate
  1. Now time to make associations,
  • In app/models/product.rb, add
has_many :orders
  • In app/models/order.rb, add
belongs_to :product
  1. Open config/route.rb, replace
resources :products

with
resources :products do
collection do
post 'notification'
end
end
  1. Add new method in app/controllers/products_controller.rb, for handelling IPN
def notification
#handle for old deals.
if params[:item_number1] && !params[:item_number1].empty?
#paypal sends an IPN even when the transaction is voided.
if params[:payment_status] != 'Voided'
@product = Product.find(params[:item_number1].to_i) rescue nil @product.orders.build(:quantity => 1, :amount => params[:mc_gross_1], :status => params[:payment_status]).save unless @product.nil?
end
end
render :nothing => true
end

In app/views/products/index.html.erb,

replace
product.paypal_url(products_url)

with
product.paypal_url(products_url, notification_products_url)

and add a new line after
:return => return_url

in paypal_url method (in app/models/product.rb), for supporting notify_url:
:notify_url => notify_url

also change signature of this method to accept notify_url parameter, it will look like:

def paypal_url(return_url,notify_url)

Done with IPN implementation, you can cross check for your IPN:

Login to merchant account -> History -> IPN History


The fully implemented application is uploaded on heroku: PayPal Integration.
You can checkout application's code here.

Go Back to PayPal Basics
Must read about Security while Payments


Comments

  1. There are many reasons why one might need to Accept Payments Online . Maybe you sell two or three items, yet insufficient to invest the energy and money important to set up.

    ReplyDelete

Post a Comment