#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 32 comments

1. Ben Jan 12, 2009 at 00:46

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


2. 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 :)


3. Josh Jan 12, 2009 at 04:40

Beautiful! Thanks, Ryan!


4. Marcello_BR Jan 12, 2009 at 05:03

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


5. 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)?


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

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


7. 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.


8. Ken Jan 12, 2009 at 08:44

Great episode Ryan. One of your best!


9. 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.


10. 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


11. 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.


12. Tole Jan 12, 2009 at 15:57

Another nice screencast. very useful again. Thanks Ryan


13. 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


14. 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!


15. 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 ;)


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

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


17. 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.


18. alex Jan 13, 2009 at 15:24

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


19. 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


20. 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?


21. 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.


22. 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.


23. 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.


24. 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.


25. 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).


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

What about an episode on SAML


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

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


28. 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..


29. 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 :)


30. poka Feb 27, 2009 at 01:08

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


31. 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?


32. 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


33. Dipak Oct 14, 2009 at 04:03

Anyone knows if the Activemerchant works with RBSWorldpay ?


34. 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?


35. 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."


36. Tomasso Mar 08, 2010 at 20:23

I get the same "Please enter a complete billing address", somebody found a solution? may be there is nothing bo ship :S


37. lawofaverage Mar 16, 2010 at 09:46

Try this for the "complete billing address error"

Add the billing_address hash after the ip address.

if credit_card.valid?
  response = gateway.purchase(1000, credit_card,
    :ip => "127.0.0.1",
    :billing_address => {
    :name => 'Test User',
    :company => '',
    :address1 => '123 S Main St',
    :address2 => '',
    :city => 'Akron',
    :state => 'OH',
    :country => 'US',
    :zip => '44333',
    :phone => '(310)555-5555'
  }
  )

 


38. colon cleanse Apr 23, 2010 at 21:58

I did this for Authorize.net and it was pretty simple.


39. ronald Jun 15, 2010 at 12:33

If you get error: There's an error with this transaction. Please enter a complete billing address, you will need to accept the billing agreement on your paypal account (one of the steps in the setup process)


40. guess handbags Jun 30, 2010 at 23:10

now, more and more and more peopel do a busniess online.it's convenience.


41. Matt Hodan Aug 02, 2010 at 13:17

I just setup ActiveMerchant with PayPal Website Payments Pro (US) to do recurring payments for a project I'm working on. If anyone wants to see how I wrapped the PayPal recurring API resources, I posted it all on my blog:

http://blog.matthodan.com/how-to-add-support-for-paypal-website-payment


43. mosaic glass Aug 08, 2010 at 16:37

Good article, Each and every point is good enough.Thanks for sharing with us your wisdom.


44. Jamal Abdul Nasir Aug 09, 2010 at 02:36

why am i getting the following error...

Error: This transaction cannot be processed due to an invalid merchant configuration.


45. Body Exercise Machines Aug 19, 2010 at 01:42

Body exercise machines such as Crazy Fit Massage, Vibration plate machine, Leg Magic, Leg Exerciser, Leg master, Mini stepper, Air climber, Cardio twister;


46. Home Fitness Machines Aug 19, 2010 at 01:42

As a branch factory of China Peteresa Group, Peteresa Fitness Equipment Co.,LTD was established in the year 2008, which is dedicated to design and manufacturer high quality home fitness equipments and machines.


47. China Fitness Equipment Aug 19, 2010 at 01:43

 These products are been exporting to Europe, United States, Asia, the Middle East, Russia and Latin America countries. We are expecting more partners from all over the world.


48. Hydraulic Fitness Equipment Aug 19, 2010 at 01:44

We are now experiencing annual sales turnovers worth in excess of USD 5,000,000. Outputing around 100,000,000 fitness equipment annually, our scientific management and strict operating systems ensure that all items meet the standards required for export into countries worldwide.


49. Wholesale baseball hats Aug 20, 2010 at 20:48

I really liked your article and I shared with my friends in my facebook account ..
I gave my site a few examples below. If you appreciate my comments in you enter.


50. authentic nike shoes Aug 22, 2010 at 23:02

Awesome post! Thanks for sharing such nice information with us. I am really interested in this learning about this. , I feel strongly about information and love learning more on this. Thanks for the information. This is a wonderful post!!


51. louis vuitton shoes Aug 26, 2010 at 23:14

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it. My readers have about the same interets


52. Wholesale Electronics Aug 27, 2010 at 00:18

Discount Wholesale Electronics, Wholesale Cell Phones, Electronic Gadgets and More from the Best Dropship Wholesaler


53. snow boots Aug 30, 2010 at 21:14

. Thanks for the information. This is a wonderful post!!


54. louis vuitton sunglasses Sep 01, 2010 at 21:22

I feel like I’m often looking for interesting things to read about a variety of subjects, but I manage to include your blog among my reads every day because you have interesting entries that I look forward to. Here’s hoping there’s a lot more great material coming!

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