Skip to content

Instantly share code, notes, and snippets.

@stuffmc
Created March 2, 2010 17:06
Show Gist options
  • Save stuffmc/319684 to your computer and use it in GitHub Desktop.
Save stuffmc/319684 to your computer and use it in GitHub Desktop.
PayPal Express
::PAYPAL_OPTIONS = {
:user => "xxx",
:pwd => "xxx",
:signature => "xxx",
:version => '57.0',
}
::PAYPAL_API_URL = 'https://api-3t.paypal.com/nvp'
::PAYPAL_TOKEN_URL = 'https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='
def paypal_express
token = params[:token]
payer_id = params[:PayerID]
if !token.blank? && !payer_id.blank?
@order = # look up in my Order model for the record based on the token
::PAYPAL_OPTIONS.merge!({
:method => 'DoExpressCheckoutPayment',
:PAYMENTACTION => 'Sale',
:token => token,
:PAYERID => payer_id
})
response = RestClient.post ::PAYPAL_API_URL, ::PAYPAL_OPTIONS # yes, you need the RestClient Gem, get it on http://rubygems.org
success = (CGI.parse(response)["ACK"][0] == "Success")
# I Then do something with "success" of course, but it has nothing to do with PayPal anymore... One might just retry or reset the user to the "SetExpressCheckout"
else
order = # look up in my Order model for the record based on some ID in "param"
amount = # compute the amount - has to send it as "units" (aka USD or EUR) not as "cents", contrary to AM
tax_amount = # compute the tax, based on amount and the tax coefficient (VAT 19% in Germany for ex.)
shipping_amount = # got this from the databse
::PAYPAL_OPTIONS.merge!({
:method => "SetExpressCheckout",
:amt => "%.2f" % (amount + tax_amount + shipping_amount),
:L_NAME0 => "article name",
:L_AMT0 => "%.2f" % amount,
:L_QTY0 => 1,
:ITEMAMT => "%.2f" % amount,
:TAXAMT => "%.2f" % tax_amount,
:SHIPPINGAMT => "%.2f" % shipping_amount,
:CURRENCYCODE => "EUR", # I got this from the database in reality.
:returnurl => paypal_express_new_order_url,
:cancelurl => home_url,
:token => nil
})
response = RestClient.post ::PAYPAL_API_URL, ::PAYPAL_OPTIONS
@token = CGI.parse(response)["TOKEN"][0]
if @token.nil?
# Do whatever. I just display a message and redirect... Remember I'm doing this from an iPhone app so I can display an alert and refetch the page in background
else
order.update_attribute(:express_token, @token)
redirect_to ::PAYPAL_TOKEN_URL + @token
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment