Skip to content

Instantly share code, notes, and snippets.

@lucassus
Created February 3, 2013 12:03
Show Gist options
  • Save lucassus/4701523 to your computer and use it in GitHub Desktop.
Save lucassus/4701523 to your computer and use it in GitHub Desktop.
Paypal ipn listener
class ListenersController < ApplicationController
def paypal_ipn
raw_post = request.raw_post
notification = ActiveMerchant::Billing::Integrations::Paypal::Notification.new(raw_post)
@ipn_log = PaypalIpnLog.new(:raw_post => raw_post)
if development? || notification.acknowledge
recurring_payment_id = notification.params['recurring_payment_id']
@ipn_log.recurring_payment_id = recurring_payment_id
@domain = Domain.find_by_billing_profile_id(recurring_payment_id)
@ipn_log.domain = @domain
handler = :"handle_#{notification.type}"
if respond_to?(handler)
send(handler, notification)
else
@ipn_log.message = "Unsupported operation (#{notification.inspect})"
end
else
@ipn_log.message = "Invalid IPN response (#{notification.inspect})"
end
@ipn_log.save
render :nothing => true
end
protected
def handle_recurring_payment(notification)
begin
payment_amount = notification.params['amount'].to_f
tax_amount = notification.params['tax'].to_f
# create payment
payment = Payment.new(
:domain => @domain,
:customer => @domain.customer,
:plan => @domain.plan,
:amount => payment_amount + tax_amount,
:from_date => Date.today,
:to_date => Date.today + 1.month)
if notification.complete? && @domain.plan.price == payment_amount
payment.status = Payment::STATUSES[:paid]
@ipn_log.success = true
# TODO generate invoice
else
payment.status = Payment::STATUSES[:unpaid]
@ipn_log.message = "Transaction is not completed or invalid payment amount (#{notification.inspect})"
end
payment.save!
@ipn_log.payment = payment
rescue => error
@ipn_log.message = error.to_s
end
end
def development?
Rails.env == 'development'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment