#144
Jan 12, 2009

Active Merchant Basics

Active Merchant is a great library for handling credit card transactions. In this episode I will show you the basics of using it to communicate with PayPal's gateway.
Download (15.6 MB, 10:10)
alternative download for iPod & Apple TV (12.7 MB, 10:10)

Resources

sudo gem install activemerchant
require "rubygems"
require "active_merchant"

ActiveMerchant::Billing::Base.mode = :test

gateway = ActiveMerchant::Billing::PaypalGateway.new(
  :login => "seller_1229899173_biz_api1.railscasts.com",
  :password => "FXWU58S7KXFC6HBE",
  :signature => "AGjv6SW.mTiKxtkm6L9DcSUCUgePAUDQ3L-kTdszkPG8mRfjaRZDYtSu"
)

credit_card = ActiveMerchant::Billing::CreditCard.new(
  :type               => "visa",
  :number             => "4024007148673576",
  :verification_value => "123",
  :month              => 1,
  :year               => Time.now.year+1,
  :first_name         => "Ryan",
  :last_name          => "Bates"
)

if credit_card.valid?
  # or gateway.purchase to do both authorize and capture
  response = gateway.authorize(1000, credit_card, :ip => "127.0.0.1")
  if response.success?
    gateway.capture(1000, response.authorization)
    puts "Purchase complete!"
  else
    puts "Error: #{response.message}"
  end
else
  puts "Error: credit card is not valid. #{credit_card.errors.full_messages.join('. ')}"
end

RSS Feed for Episode Comments 38 comments

1. David Trasbo Jan 12, 2009 at 00:02

Oh, finally a screencast on ActiveMerchant! Looking good, Ryan. Keep up the good work. (I was first, yay!) :)


2. Ben Jan 12, 2009 at 00:46

Very, nice! I cant wait for the recurrent billing episode :)
Good job!


3. Hubert Łępicki Jan 12, 2009 at 02:40

Is this screencast finally available because of sponsor changed? I know peepcode had screencast on AM and was sponsor of this site - so I guess it was a conflict :)


4. Josh Jan 12, 2009 at 04:40

Beautiful! Thanks, Ryan!


5. Marcello_BR Jan 12, 2009 at 05:03

Very interesting! Much simpler than the gateway I use now. Thanks Ryan!


6. Jeffrey Lee Jan 12, 2009 at 07:28

Does the credit function use PayPal's "refund" operation (where fees are also refunded) or is it seen as another transaction (another set of fees)?


7. Gustavo Scanferla Jan 12, 2009 at 07:37

When my project is ready,I will click the "PayPal Donate" here at RailsCasts =)


8. David Trasbo Jan 12, 2009 at 07:57

Gustavo Scanferla: Wow, I never even noticed that button. And I don't think I'm the only one. Maybe Ryan should mention it in one of his screencasts or upsize the button or something.


9. Carl Jan 12, 2009 at 08:29

Activemerchant is a nice library for abstracting away the differences between Gateways.

I second the Paypal donate button increase. I've been watching these for a long time and I never noticed it before.


10. Ken Jan 12, 2009 at 08:44

Great episode Ryan. One of your best!


11. Ryan Bates Jan 12, 2009 at 09:15

@Hubert, there wasn't a conflict with PeepCode sponsorship in the past, I just hadn't looked into Active Merchant enough back then to do an episode on it.

AFAIK PeepCode doesn't have a screencast on Active Merchant, but they do have a PDF book which I highly recommend. It's difficult to find adequate documentation on the subject.

@Jeffrey, that's a good question. I know Active Merchant itself provides two ways to handle credits. One is based on an existing transaction, and another is using a credit card number which will be treated as its own separate transaction (payment in reverse).

I'm assuming if you supply the authorization code when issuing the credit, it will treat it as a refund through PayPal but I have yet to test it.


12. StartBreakingFree.com Jan 12, 2009 at 10:43

Great stuff Ryan.

As for the donate button - have you ever thought about putting an Amazon wish list together? I think these are better than the donate button since it makes it more personal what people send you and can often result in higher dollar amounts. Just a thought!

I'm also looking forward to an episode on recurring billing!

It's amazing Active Merchant doesn't have a video like this on their homepage! Hope they link to it. Thanks Ryan.
Brian Armstrong


13. Bill DeVaul Jan 12, 2009 at 10:56

This is so useful to me. I have the Peepcode but seeing coding in action just works for me.

Many, many thanks for it.


14. Tole Jan 12, 2009 at 15:57

Another nice screencast. very useful again. Thanks Ryan


15. Ryan Bates Jan 12, 2009 at 16:01

@Brian, you can find my Amazon wish list here if you like. :)
http://www.amazon.com/gp/registry/wishlist/1MLM280E2D


16. Tommy Jan 12, 2009 at 16:03

Great stuff and great timing! When do you think the next episode will be up! Thank you thank you!


17. Walter Schreppers Jan 12, 2009 at 16:28

Hi, thanks for another great screencast! I only see one possible problem when using gateway.authorize&capture:

Say you checked on a valid authorize. A few days later you decide to ship the item and do a gateway.capture(...) and during those days between you did the authorize and the capture the shopping client maxed out his credit. What happens then?

Or in other words shouldn't the capture member give back another true/false upon successful completion of the actual funds just as in gateway.purchase?

I should probably read more on active merchand and find the answer myself. Would be nice if you could elaborate on that edge case where the client maxes out his cards between authorize and capture method calls.

Or is authorise(1000, ... ) able to stop the client from going below 10$ of credit when he wants to try and max out because of the dangling authorise made earlier?

Maybe this has been asked/answered a thousand times before, in which I apologize for my ignorance ;)


18. David Trasbo Jan 13, 2009 at 01:55

@Tommy There is a new episode here every monday at midnight. :)


19. Jeffrey Lee Jan 13, 2009 at 07:21

Yes, Railscasts brings much joy to an otherwise bland Monday morning :)


20. Carl Jan 13, 2009 at 11:41

@Ryan,

I'm pretty sure you are beyond needing "Beginning Ruby". Unless it is a gift for someone else? Sometimes the things you do on your screencasts still look like magic to me, and I've been writing Ruby for a couple of years now.


21. alex Jan 13, 2009 at 15:24

Awesome screencast Ryan. Any chance on recurring billing for software as a service?


22. Sean Schofield Jan 13, 2009 at 18:01

For those of you interested in Rails commerce, you should check out the open source Spree project[1].

[1] http://spreehq.org


23. Gustavo Scanferla Jan 13, 2009 at 19:01

@alex same doubt as you.
Would be legal or possible to program a monthly "gateway.purchase" of the same value and same credit card?


24. Carl Jan 14, 2009 at 20:17

@Gustavo,

You have to be careful about storing credit card info in your system (they are many requirements, you can find some info here: http://usa.visa.com/merchants/risk_management/cisp_merchants.html )

The safest way to do reoccurring billing is using something that some providers offer that stores the credit card info on their servers and just returns a sort of key to you that allows you to adjust amounts, remaining payments, etc. I did this for Authorize.net and it was pretty simple.

If you go that route, ActiveMerchant has some methods that make it pretty simple to handle (update_recurring for example). http://github.com/Shopify/active_merchant/blob/2b1c6d8e960b06ac98ea223280ff6e81f30174a1/lib/active_merchant/billing/gateways/authorize_net.rb for reference.

Methods like this are only available if the gateway supports it (and only a few do, and some (all?) charge a bit more for it), so you do have to do some research, but it is worth it if you plan to use reoccurring billing (not every app requires it).

http://wiki.github.com/Shopify/active_merchant/gatewayfeaturematrix

I only have experience with Authorize.net, so I can't speak about the rest, but in general expect another fee every time you turn around ($5/month for reoccurring billing, $5/month as a "statement fee", 2.5%/transaction, $0.20/transaction for this, $0.05/transaction for that, $0.05/transaction for this other thing, $20/month for this, oh, and a $20/month minimum in case that 2.5% is less than that per month, etc. Once you get past that, it's not too bad.


25. Cody Fauser Jan 15, 2009 at 04:52

@Jeffrey Lee,

PayPal only supports referenced credits, which are based on a previous transaction. Some other gateways do support non-referenced credits by passing in a credit card object as the second argument to the credit() method. You'll have to check with your gateway provider and ActiveMerchant to see what your gateway supports.


26. Cody Fauser Jan 15, 2009 at 04:53

@Louis Vuitton Replica Handbags,

The authorization reserves the money from the customer's card for 3 days. Within the 3 days the funds are guaranteed to be there. You are can capture the funds with PayPal for up to 29 days, but after 3 days the funds are no longer guaranteed. You can attempt to have the funds guaranteed again one time within the 29 days by using the reauthorize() method of the gateway. See the PayPal Website Payments Pro Developer Guide for more info.


27. Cody Fauser Jan 15, 2009 at 04:59

@Carl,

You're responsible for those requirements as soon as you receive any cardholder data on your servers even if you don't store the card numbers.

Not storing card numbers does save you from section 3 of the PCI DSS, which is a complex section due to all of the encryption requirements, etc. Not having a load of cardholder data on your servers would also hopefully lessen the impact of a security breach on your servers.


28. Carl Jan 15, 2009 at 16:06

@Cody,

I didn't mean to come across that you didn't have those requirements, but that they become more extensive if you do store the data. Sorry for not making that more explicit (it sounded right in my head at the time).


29. Fredrik Gustafsson Jan 18, 2009 at 23:31

What about an episode on SAML


30. Raj Ojha Jan 26, 2009 at 13:22

Is there a way to integrate activemerchant with offline payment via paypal website payments standard?


31. jak Jan 26, 2009 at 21:32

Hi... it is really nice and good railscasts.. thanks for helping us... i have blogged about this topic..


32. Anton Jan 30, 2009 at 13:21

A big warning: US only at the beginning would be fine. Outside the US there are no gateways integrated in ActiveMerchent and it is the only program I know that has absolutely no documentation (except from the headers - not a single useful line of a comment). So it is absolutely useless for non-US companies. Even if you don't use PayPal as US company you have to guess what class might do the job and try some options, ... - because of the complete lack of documentation.

As great as your screencasts are (I watched them all) - as useless ist ActiveMerchant.

I am looking forward on useful screencasts :)


33. poka Feb 27, 2009 at 01:08

I am getting some errors like this--"Security header is not valid."


34. Michael Kahle Jul 25, 2009 at 13:27

Not sure why I am seeing this, but when I do this exercise I receive the error:

Error: There's an error with this transaction. Please enter a complete billing address.

Did something change in the PayPal API to require billing address? Why did your example work without this information?


35. linoj Sep 20, 2009 at 14:16

fyi, I just posted a screencast on my new SaasRamp plugin for doing recurring billing for software as a service (saas)
http://www.vaporbase.com/postings/SaasRamp_Screencast


36. Dipak Oct 14, 2009 at 04:03

Anyone knows if the Activemerchant works with RBSWorldpay ?


37. Daniel Fischer Dec 25, 2009 at 05:36

So I am trying out your code exactly sans your credentials and I am getting the following error:

Error: There's an error with this transaction. Please enter a complete billing address.

How come it worked in your example?


38. greenland Feb 01, 2010 at 19:39

Same error as 34 & 37
"There's an error with this transaction. Please enter a complete billing address."

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source