5 Nerd-Its - +

Processing Credit Cards with Ruby on Rails

Page_white_text an academic article by Mark A. McBride (markmcb), published on 23 January 2007
tagged as webdesign, computing, programming, and rubyonrails
other nerds have left 14 comments below

This article is for anyone who is trying to handle credit card transactions on-line using Ruby on Rails.1 If you are like me, the fact that Ruby on Rails is still in its infancy has probably left you pounding your head against the wall while looking for quick solutions to old problems like e-commerce. More than likely, the source of your headaches (aside from the pounding) is the lack of documentation, even with popular plugins. This article is the sum of hours of scouring the Internet trying to piee together everything about Active Merchant, SSL, Apache, et al., and make them all play nicely in a Ruby on Rails application.

For the entirety of this article, I will assume you have a bank merchant account and an Authorize.net merchant account.2 (Even if you don’t, the article should help if you plan on using the Active Merchant payment abstraction library plugin, which is what I use for my transactions.) Authorize.net will serve as an on-line third party to revie our credit card transactions and issue an approval/rejection. It will then be up to our code to handle the response. Simple enough? Let’s get to work.

Get Your Login/Password (AKA Your API Login ID and Transaction Key)

To make all of this work, you are going to need to be able to talk to the Authorize.net servers. They won’t talk to you unless you have a login and password. If you have an account, then you should have a login and password to access their web site, but this isn’t the combo tat you will need to process transactions. Instead, use that login to get into your account on their site, go to settings and look for the "API Login ID and Transaction Key." This is what you need. These two random strings of characters are what your application will pass to Authorize.net to establish a connection.

If you haven’t already, now would be a good time to put your account in test mode to ensure you don’t accidentally process a transaction. If you don’t see big red banners all over your ccount page that read "test mode," then your account is not in test mode.

Install Active Merchant with Subversion

Now, let’s get a copy of Active Merchant. Active Merchant is available from leetsoft.com.3 I have two things to say about Active Merchant: the code is great, but the lack of documentation makes it tough to start using, especially if you’ve never handled credit crd transactions before. Hopefully this will help fill in some gaps.

Assuming you’ve already got your rails application built,4 change to the vendor/plugin folder and issue the following Subversion command:


svn co svn://home.leetsoft.com/active_merchant/trunk/active_merchant/

Generate Built-in Documentation

Congratulations! Active Merchant is now installed on your system. You probably feel more 1337 now, too, since you had some text scrolling on your screen, but I digress. Active Merchant will automatically be available to your aplication due to the init.rb file, which you can investigate if you’re curious.5 However, there is still some work left to do. One thing I definitely recommend is changing to the active_merchant folder you just installed and issuing the following command to install the built-in documentation:


rake rdoc

Once you do this you will be able to open doc/index.html and view the generated documentation. It’s semi-helpful and will at least give you a baseline of what is available with the plug-in.

2_article_66_thumb_active_merchant_built-in_documentation

Built-in Active Merchant Documentation.|border

Test the Active Merchant Plugin

Next, you will need a few gems installed:


gem install money
gem install activesupport
gem install actionpack

If you want to run the unit tests for Active Merchat after installing these gems, first locate the test files in the test folder and replace the login and password with your API Login ID and Transaction Key. Then, from the active_merchant folder, there are unit tests and remote tests that you can run with:


rake test
rake test_remote

From this point, you are ready to start writing your test application to get the hang of Active Merchant. The next section deals with secure socket layer (SSL) connections that will allow you to encrypt the dta your users send you. If you’re not interested in this just yet, skip ahead to the next section to start writing test code for Active Merchant.

Encryption Key and Certificate Generation for SSL Security

One thing you will definitely want to do is receive your customers’ sensitive information over an encrypted connection. To do it right, you’ll need to generate some encryption keys. This can easily be done with openssl:


openssl req -new -nodes -keyout private_ssl.key -out public_ssl.sr

This will create two keys, a private and public key. The details of each are well documented6 so I’ll not cover the details here. However, before you turn on your production server, you’ll want to get your certificate signed by an authoritative agent to avoid warning messages displaying on your clients’ browsers. You will have to pay for a signed certificate. In the meantime, you can sign your certificate yourself for testing:


openssl x509 -req -days 30 -in public_ssl.csr -signkey private_ssl.key -out public_ssl.cert

Configure Apache to Handle HTTPS on Port 443

Lastly, you need to set up Apache to accept connections on port 443 and use your keys to encrypt them. Assuming you’re using virtual hosts, the following is a minimal virtual host file:


<VirtualHost *:443>
    DocumentRoot /path/to/your/webroot/
    ServerName yourserver.org:443n    <Directory "/path/to/your/webroot/">
      Options ExecCGI FollowSymLinks
      AllowOverride all
      Allow from all
      Order allow,deny
    </Directory>
   SSLEngine on
   SSLCertificateFile /path/to/your/ssl/public_ssl.cert
   SSLCertificateKeyFile /path/to/your/ssl/private_ssl.key
</VirtualHost>

With that virtual host installed, restart Apache. You can test your SSL connection with the following command:


openssl s_client -connect yourserver.org:443

Or you cn just go to https://yourserver.org in your web browser (note: https, not http).

Outbound SSL

One thing you should make note of is that Active Merchant will connect to Authorize.net using an encrypted SSL connection on port 443. Much like you will encrypt your users’ data coming in, Authorize.net will do the same. If your firewall is blocking outbound traffic on this port, you may get some interesting errors. Ensure you allow this traffic out.

Build Your Test Ruby on Rais Application

Great! We’ve got Active Merchant installed and we’ve got a secure server. All we need to do now is process some transactions. The leetsoft web page, as well as the built-in documentation, gives you a snippet of sample code to get started with, but you’ll probably just end up more confused and informed just enough to be dangerous. The following is a modification of that code with some explanations and some variables that can send output to a view file for quick feedback in your browse of choice.

I recommend you create a controller to handle your testing. Later on you can choose to modify it, delete it, or whatever. For now we just want to pass a successful transaction to Authorize.net, have them acknowledge it, and see some sort of status.



class PaymentTransactionTestController < ApplicationController

  require 'money'

  def process_payment
    amount_to_charge = Money.ca_dollar(1000) #ten US dollars
    creditcard = ActiveMerchant::Billing::CreditCard.new(
     :number => '4222222222222', #Authorize.net test card, error-producing
    # :number => '4007000000027', #Authorize.net test card, non-error-producing
      :month => 3,                #for test cards, use any date in the future
      :year => 2010,              
      :first_name => 'Mark',      
      :last_name => 'McBride',
      :type => 'visa'             #note that MasterCard is 'master'
    )

    if creditcard.valid?
      gateway = ActiveMerchant::Billing::Base.gateway(:authorized_net.new(
        :login => 'abcdefgh',         #API Login ID
        :password => 'abcdefghijklm') #Transaction Key

      options = {
        :address => {},
        :billing_address => { 
          :name     => 'Mark McBride',
          :address1 => '1 Show Me The Money Lane',
          :city     => 'San Francisco',
          :state    => 'CA',
          :country  => 'US',
          :zip      => '23456',
          :phone    => '(555)555-5555'
        }
      }

      response = gateway.autorize(amount_to_charge, creditcard, options)

      if response.success?
        gateway.capture(amount_to_charge, response.authorization)
        @result = "Success: " + response.message.to_s
      else
        @result = "Fail: " + response.message.to_s
      end
    else
      @result = "Credit card not valid: " + creditcard.validate.to_s
    end
  end
end

Your view code can be quite simple:


<%= h @result %>

That’s it. This small code not only allows you to do he testing described in the next section, but it should be the bulk of what you need to get up and running. You’ll obviously need to make this fit your application, but the basic template and data structures will still apply.

Logic of Active Merchant Test Application

The code above is fairly self-explanatory, but here are the functionality highlights. First, it uses the Money class to create an object that represents $10. Second, it creates an object to represent the credit card against whih the $10 will be charged. Next, it checks to see if the card is valid and if so, it attempts to authorize the $10 against it using the billing address passed in the options hash. If the authorization is successful, it captures the charge against the card and the transaction is complete. If any of the steps above fail, it returns an appropriate status code.

Testing with Mock Data

Authorize.net offers some nice features when it comes to testing. With minimal effort, you should be able to pass tansactions in a test environment in the same manner you will do in your production environment.

First, ensure your account is in test mode by logging on through the web site and ensuring you see the appropriate big, red test mode banner. If it’s not, you can find the option to turn it on in your settings. Once it’s on, you can use Active Merchant to send as many test transactions as you like.

As you probably noticed in the credit card hash above, there are two numbers. Both of these numbers aretest credit cards provided by Authorize.net. They will aid you greatly while in test mode.7

The non-error code number (annotated in the comments in the code) will act just like a real card with the exception that you can’t validate it against a billing address. By using the non-error number, you can successfully use methods like "apture," which will charge the card for the amount specified. If you have them turned on, you’ll get email receipts from Authorize.net in addition to the successful responses your view will produce.

2_article_66_thumb_email_receipt

Text from an emailed transaction receipt.|border

Perhaps even more useful, though, is the error producing card number. This card will intentionally return the Response Reason Code8 equaling the passed dollar amount. For example, if you pass $10 as thecapture value, you will get the Response Reason Code 10, "The account number is invalid."

Just the Tip of the Iceberg

As stated in the intro, this guide only covers the essential functionality of Active Merchant and only for the Authorize.net AIM API. The Active Merchant project is up and coming so be sure to check the source for updates and hopefully someday, more formal documentation than this.9

1 Ruby on Rails is an MVC framework for the Ruby language. More information can be found at http://www.rubyonrails.org.

2 A bank merchant account is necessary to have money deposited into your back account via sales transactions. Most major banks offer merchant accounts, so a call to their sales department will likely yield all the information you need. As for Authorize.et, they provide the APIs necessary to take one of your customer’s credit card numbers and securely create a purchase transaction against it. Again, if you have questions, their sales department is more than helpful and will give you all sorts of details not covered in this article.

3 Tobias Luetke, Active Merchant, leetsoft.com, accessed from http://home.leetsoft.com/am on 20 January 2007.

4 If you don’t already have your rails application built, make a folder and type "rails test_active_merchant" to build one. The only code you’re going to need for the remainder of this test is included in the remainder of this article. However, you should note that this article is geared toward the Apache web server, so if you’re planning on using the WEBrick server, you ma want to skip the SSL section and test your server without encryption.

5 If you’re unfamiliar with how plugins work, check out http://nubyonrails.com/articles/2006/05/04/the-complete-guide-to-rails-plugins-part-i for a nice walk through.

6 OpenSSL Manual Page, OpenSSL.org, accessed from http://www.openssl.org/docs/apps/openssl.html on 22 January 2007.

7 Advanced Integration Method (AIM) Implementation Guide, Authorize.Net, pgs. 49-50, accessed from http://www.authorize.net/support/AIM_guide.pdf on 20 January 2007.

8 Ibid, 26.

9 The Google forum for Active Merchant provided me with quick answers when I started with Active erchant. Be sure to look there if you have detailed questions and problems. http://groups.google.com/group/activemerchant

Similarly tagged OmniNerd content:

Thread parent sort order:
Thread verbosity:

The article author was absolutely correct when he/she said to be sure that your account is in test mode if you are not really trying to charge a live transaction. I learned this the hard way. :) Luckily, it was with my own credit card and so it didn’t matter too much, but I did have to fix it before it settled and the void cost me a small transaction fee. Know your interface!

If you need a quick Authorize.Net account setup call 801-805-4802 because they are cheap and quick!!! That’s where I got mine from.

—Another nerd

Paypal is pretty cool as a payment gateway if you have a pro account. Then I’d say go grab this article to get you started.

I am currently working on implementing processing credit cards with ruby on rails. I have read your article and followed these intructions. However I have a problem, which I cannot find solution to. I work in test mode and I try to use the error producing credit card number: 4222222222222. But instead of receiving errors, the gateway response is as follows: "Success: This transaction has been approved".

0 Nerd-Its - +
View code broken by Anonymous :: NR0

The example view code doesn’t seem to be there…

1 Nerd-It - +
svn repo update by Anonymous :: NR0

Hello, thanks for your article.

Just wanted to tip of any new viewers to the new locale of the svn repo:

http://activemerchant.googlecode.com/svn/trunk/active_merchant

Cheers,
D

0 Nerd-Its - +
Test Controller Error by Anonymous :: NR0

You’re missing a closing ")" where you define gateway. And thanks, this tutorial has been helpful :)

0 Nerd-Its - +
Credit Cards Australia by Anonymous :: NR0

Your blog is very informative. However, earning money and balance your credit cards is pretty hard task but your post and experienced serve and teach me how to handle and make it more simple and manageable.

Thanks for the tips… Best regards.

http://www.creditworld.com.au/credit-cards.html

0 Nerd-Its - +
Great Article by Anonymous :: NR0

Great article, wish i had seen the Money gem a little earlier.

You should also do a writeup on encrypting the cc data while on the server for PCI compliance. This is needed if you want to provide a preview of the order information before you charge their card.

OmniNerd Article Propagation

The Showcase

Nerd-Its   Nerd Trends   Last Ten  

  1. RE: Please read the Book of Mormon! // Jake is way off base in God before Country in the Military
  2. RE: Discussing Book of Mormon anachronisms in God before Country in the Military
  3. RE: Discussing Book of Mormon anachronisms in God before Country in the Military
  4. RE: Discussing Book of Mormon anachronisms in God before Country in the Military
  5. RE: Discussing Book of Mormon anachronisms in God before Country in the Military
  6. RE: Now it's, "Please watch Expelled"? in God before Country in the Military
  7. RE: Please read the Book of Mormon! // Jake is way off base in God before Country in the Military
  8. But she didn't do the right thing right in Nurse Does "Right Thing", Goes To Jail
  9. RE: Please read the Book of Mormon! // Jake is way off base in God before Country in the Military
  10. RE: nerdy? in God before Country in the Military

What is OmniNerd?

Omninerd_icon Welcome! OmniNerd's content is generated by nerds like you. Learn more.

Voting Booth

Legalizing medical marijuana?

26 votes, 1 comment