Ruby on Rails Credit Card Processing with Active Merchant

Posted by acts_as_flinn Tue, 27 Feb 2007 23:41:00 GMT

(with Paypal Website Payments Pro)

by Flinn Mueller
Last Updated: 2007-02-27
actsasflinn.com
This is an exerpt of a presentation that I gave to the PhillyOnRails group on February 26th, 2007. In this document I have extracted all the relavent parts you will need to start using Ruby on Rails to process credit card with Paypal Website Payments Pro (WPP).

Click here if you know all about Active Merchant and want to skip to the WPP stuff.

Active Merchant – Rails Credit Card Processing

If you are familiar with Rails and have spent more than five minutes researching the subject you have heard of Active Merchant. If you haven't here is a brief background. Active Merchant is likely the most popular, if not the most developed, and supported credit card processing plugin for Rails. It supports a number of gateways, probably more than any other Rails plugin out there. At one time it included support for live shipment quotes from Fedex and possibly others(?) but as far as I know it seems to have removed that feature to focus on billing.

Active Merchant is the child of Shopify by Jaded Pixel. Shopify is eCommerce + Web 2.0 which entails everything you have come to know, love, and expect from Web 2.0. If you aren't in need of developing your own customized solution, or a better wheel, and you intend to use Active Merchant to build your own store, you can skip that and just Use Shopify, it's cheap (free), and easy to work with.

If you've been watching Active Merchant development you'll know that the 1.0.0 release just came out less than a week ago. I'm pretty happy about that because it makes this presentation a bit easier to follow with a proper gem an installable plugin.

If you point your web browser to activemerchant.org you will be presented with pretty much what I just said here, and a snippet of demo code that looks like this.

Active Merchant Example Code

creditcard = ActiveMerchant::Billing::CreditCard.new(
  :type       => 'visa'
  :number     => '4242424242424242',
  :month      => 8,
  :year       => 2009,
  :first_name => 'Bob',
  :last_name  => 'Bobsen',
)

if creditcard.valid?

  # Create a gateway object to the Authorize.net service
  gateway = ActiveMerchant::Billing::AuthorizeNetGateway.new

  # Authorize for 10 dollars (1000 cents)
  response = gateway.authorize(1000, creditcard)

  if response.success?

    # Capture the money right away
    gateway.capture(1000, response.authorization)
  else
    raise StandardError, response.message
  end
end

As you can see on the first line we are instantiating a credit card object and passing all of the usual suspects here. (yes Toby the Verification Number is missing).

On the next few lines we'll check to see if it is valid and if so we will ask for authorization and if we get it then we will make the transaction and charge the card.

So there it is, I am done with my presentation.

That's all folks! – Just Kidding (kinda)

Alright, not really. But you can see from the demo this is enough to start and it's simple enough to understand. If we peak at the documentation it isn't that great and the process of getting everything you need to make your gateway work isn't fully documented yet (hopefully you have found this if you are using Paypal WPP).

The code above is pretty much the entire subject of my presentation. Of course it's a little more complicated than that, but not much more.

I will only be covering a simple transaction like this because there are so many resources out there that already explain how to do a store, shopping cart, or whatever else you need and I will list some of those resources at the end of the presentation.

Gateway Support

Choosing a gateway is the #1 factor for a merchant and a huge factor for you as developer, consultant or the dreaded e-word (entrepreneur) that makes you all three of those. There are plenty of gateway options out there, and Active Merchant supports a bunch. In the US:

  • Authorize.net
  • LinkPoint
  • PayPal Payflow Pro
  • PayPal Website Payments Pro (WPP)
  • TrustCommerce
  • USA ePay
  • And a few offsite payment options

Because it is the easiest and fastest to get access to, we'll use Paypal Website Payments Pro (WPP) in our demonstration.

Getting Started with Active Merchant

To get started we're going to do the usual, create a rails project then install either the gem or plugin.

gem install activemerchant

- or -

ruby script/plugin install http://activemerchant.googlecode.com/svn/trunk/active_merchant

Next we'll generate an order controller to play with

ruby script/generate controller order checkout

ruby script/server

Open your web browser here http://0.0.0.0:3000

Bogus Testing

Now we'll open up the controller we just generated and add this code.

    creditcard = ActiveMerchant::Billing::CreditCard.new(
      :type       => 'bogus',
      :number     => '1',
      :month      => 12,
      :year       => 2012,
      :first_name => 'Flinn',
      :last_name  => 'Mueller'
    )
    
    if creditcard.valid?    
      # Create a gateway object to the Authorize.net service
      gateway = ActiveMerchant::Billing::BogusGateway.new
     
      # Authorize for 10 dollars (1000 cents)
      response = gateway.authorize(1000, creditcard)

      if response.success?    
        # Capture the money right away
        gateway.capture(1000, response.authorization)
        render :text => 'Hazaa!'
      else
        raise StandardError, response.message
      end
    end

This code will charge $10 on my credit card. As you can see we just put in my credit card number (1), set 'bogus' as the card type, and I have chosen the month and year the mayan calendar ends as the expiration date for all you doomsdayers out there.

Just the same as the demo on the Active Merchant home page, we'll check the validity of the card, and if it's valid we'll try to charge it. We'll instantiate a new gateway object using the BogusGateway class.

Next we'll try to authorize the transaction for 1000 pennies against the creditcard object that we previously verified.

Yes, I know you are asking "why 1000 pennies instead of $10.00?" This is a really good way of handling international currency. We bring it down to the lowest unit of measure making it very easy to deal with all types of currency. Someone at the PhillyOnRails meeting said “so you don't have to deal with float issues” which is also a great point.
* Also make note that we can make use of the Money gem for currency conversions and other fun stuff.

If the gateway authorization is successful, we'll then capture our 1000 pennies.

The credit card number 1 is used along with the bogus credit card type with the BogusGateway, which is really only used for testing purposes. The number 1 is a forced success, while 2 is used similarly for a forced failure. Inputting anything else will raise an error telling you to use 1 or 2.

Hazaa!

Open our web browsers to http://0.0.0.0:3000/order/checkout

Hazaa!

Ok, great but that's Bogus. What do we need to make an actual payment work? We'll use Website Payments Pro because its easy to get access to, fast to get setup and similar enough to anything else you are likely to work with in Active Merchant.

Paypal Website Payments Pro 

To get setup you will need a few things.

  • A Paypal Developer Central Login
  • A Sandbox business account (you create that with the above)
  • API Access with Paypal Key/Cert file.

To grant API access on the business account Enable Website Payments Pro during the Getting Started Steps, or click 'API Access', in your account Profile.

Paypal Profile

This will then take you to the API Setup page.

API Setup

Click Request API Credentials and you're presented with two options.

API Access

Select "API SSL client-side certificate" to download your key/cert and login/password.

Key Download

Write down your login and password and download the key to your RAILS_ROOT/config/paypal/test.pem

Install Your Paypal Certificate

Place this code into your config/environment.rb

# Ensure the gateway is in test mode
ActiveMerchant::Billing::Base.gateway_mode = :test

# Install the key
ActiveMerchant::Billing::PaypalGateway.pem_file = File.read(File.join(RAILS_ROOT, 'config', 'paypal', 'test.pem'))

Paypal Sandbox Testing

    creditcard = ActiveMerchant::Billing::CreditCard.new(
      :type       => 'visa',
      :number     => paypal_generated_cardnumber,
      :month      => 1,
      :year       => 2008,
      :first_name => 'Flinn',
      :last_name  => 'Mueller'
    )
    
    if creditcard.valid?
      # Create a gateway object to the Authorize.net service
      gateway = ActiveMerchant::Billing::PaypalGateway.new(:login => your_paypal_sandbox_login, :password => your_paypal_sandbox_password)
     
      # Authorize for 10 dollars (1000 cents)
      response = gateway.authorize(1000, creditcard, :ip => '127.0.0.1')

      if response.success?    
        # Capture the money right away
        gateway.capture(1000, response.authorization)
        render :text => "Hazaa!"
      else
        raise StandardError, response.message
      end
    end

Now we will add some real live sandbox code.

You can see here that I've left out my own login credentials and I am using a credit card number generated by Paypal to make the transaction. (To get a test credit card number, login to your sandbox account and open your profile to add a credit card, one will be generated for you.)

This will simulate the process with Paypal. We'll run our action to see the result. Hazaa!

Check Paypal

Login to your sandbox account and check that the transaction went successfully.

Transaction Successful

That's All Folks (really)

When you are ready to go to production use a real account instead of a sandbox account, make sure to grant API Access and download a production key/cert pem file instead of a test file.

Tada, that's really all there is to it. Other gateways will have slight differences in the processes but this example should hold true for most of the gateways Active Merchant supports. This demo should be similar enough at least to get you started.

At the PhillyOnRails meeting I promised to update this document with details on how to get Papal Express payments working in Active Merchant, which is a requirement of Paypal Website Payments Pro. So stay tuned.

* Paypal Website Payments Pro requires you to provide Paypal Express as a payment option.

Extra Credit 

Beginning Ruby on Rails E-CommerceBeginning Ruby on Rails E-Commerce
Apress – ISBN: 1-59059-736-2
http://www.railsecommerce.com/

The Money Train
http://agilewebdevelopment.com/rails-ecommerce

Processing Credit Cards with Ruby on Rails
http://www.omninerd.com/2007/01/23/articles/66

PhillyOnRails

Posted by acts_as_flinn Tue, 27 Feb 2007 00:03:00 GMT

Ok, so I left a bit early tonight because I am bad with directions, and it’s a good thing too, I got took two wrong turns. I’m turning my presentation into a page so you can follow along, I promise it will be up tomorrow.

Oh yeah, and I removed the bullet on the Meetings wiki page.

  • Using RoR to accept Credit Card payments

Yes!

eCommerce on Rails @ Feb PhillyOnRails

Posted by acts_as_flinn Sat, 24 Feb 2007 22:59:00 GMT

Credit Card Processing with ActiveMerchant

So for anyone interested in Rails based eCommerce I’ll be presenting on the subject at PhillyOnRails this Monday February 26th, at Drexel. I’ll be presenting on Credit Card Processing with ActiveMerchant. So anyone keeping up will know that I’m psyched about the fact that ActiveMerchant 1.0.0 was just released.

Secure Database Storage with Sentry

I’m also going to try to cover Secure Database Storage with Sentry if I have time. This is a controversial subject for eCommerce because you’re not supposed to store certain types of information related to a transaction (for example CVV). Sentry makes asymmetric encryption a cinch. That means you can take super secret information along with an order or transaction and encrypt it for later retrieval by the merchant. All the merchant needs to do to access the secret is provide his private key similar to PGP/GPG or SSH. This beats the heck out of a lot of eCommerce methods.

The very popular PHP based osCommerce production code actually stores full credit card information in the database if you aren’t using a gateway. Of course newer beta versions don’t store the card number in database, but they email them unsecured to the merchant. That sucks.

So you might be saying “who doesn’t use a gateway?” Merchants that don’t ship products automatically or will make order adjustments, or have some other special after order process that has to be manually handled.