Skip to content

Instantly share code, notes, and snippets.

@Fivell
Created July 6, 2015 18:50
Show Gist options
  • Select an option

  • Save Fivell/9ee07a35e0aa9eaa4a56 to your computer and use it in GitHub Desktop.

Select an option

Save Fivell/9ee07a35e0aa9eaa4a56 to your computer and use it in GitHub Desktop.
paypal ipn
#Original code from ActiveMerchant::PayPalNotification
#Modified by me to account for multiple items and custom flag
#Also bypassed the acknowledge if environment is "test"
require 'net/http'
class PayPalNotification
class Error < StandardError
end
attr_accessor :params, :raw
def initialize(raw)
@params = Hash.new
@raw = ""
parse(raw)
end
def received_at
Time.parse @params['payment_date']
end
def custom
@params['custom']
end
def status
@params['payment_status']
end
# Id of this transaction (paypal number)
def transaction_id
@params['txn_id']
end
# What type of transaction are we dealing with?
# "cart" "send_money" "web_accept" are possible here.
def type
@params['txn_type']
end
#unique item identifier
def item_number
@params['item_number']
end
# the money amount we received in X.2 decimal.
def gross
@params['mc_gross'].to_s.to_f
end
# the markup paypal charges for the transaction
def fee
@params['mc_fee'].to_s.to_f
end
# What currency have we been dealing with
def currency
@params['mc_currency']
end
# This is the invoice which you passed to paypal
def invoice
@params['invoice']
end
def first_name
@params['first_name']
end
def last_name
@params['last_name']
end
def payer_email
@params['payer_email']
end
def account
@params['business'] || @params['receiver_email']
end
# Was the transaction complete?
def completed?
status == "Completed"
end
def failed?
status == "Failed"
end
def denied?
status == "Denied"
end
def valid?
acknowledge && completed?
end
def acknowledge
# use the POSTed information to create a call back URL to PayPal
query = 'cmd=_notify-validate'
@params.each_pair do |key, value|
query = query + '&' + key + '=' + value unless key == 'register/pay_pal_ipn.html/pay_pal_ipn'
end
# Verify all this with paypal
http = Net::HTTP.start(paypal_url, 80)
response = http.post('/cgi-bin/webscr', query).body.chomp
http.finish
raise Error.new("Faulty paypal result: #{response}") unless ["VERIFIED", "INVALID"].include?(response)
response == "VERIFIED"
end
protected
def paypal_url
production? ? 'www.paypal.com' : 'www.sandbox.paypal.com'
end
def production?
Rails.env.production?
end
private
# Take the posted data and move the relevant data into a hash
def parse(post)
@raw = post
for line in post.split('&')
key, value = *line.scan( %r{^(\w+)\=(.*)$} ).flatten
params[key] = CGI.unescape(value)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment