Wednesday, 11 June 2008

Rails Access Different Payment Gatways Using ActiveMerchant

One of my Ruby on Rails projects in eSpace contains e-commerce process for charging the clients using their credit-card information. As there are many payment gateways (PayPal, Authorize.net, etc), then you just need a simple plugin/gem that helps you access those gateways. Ruby on Rails contains many plugins/gems that give you access to different payment gateways. One of the great plugins is ActiveMerchant. It gives Rails a unified API for accessing different payment gateways with very simple way.
Using ActiveMerchant you will get:

  1. Support for too many payment gateways

  2. Bogus gateway for testing all payment functions that can done on actual gateways (except recurring).

  3. Validates credit card format

The following steps shows you how to install ActiveMerchant, create a credit card object and validates it, then use the bogus gateway for processing e-commerce actions.

  1. You can install ActiveMerchant as gem:

    gem install activemerchant


    or as plugin

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


  2. Create a credit card object:

    credit_card = ActiveMerchant::Billing::CreditCard.new({
    :number => 5105105105105100,
    :month => 9,
    :year => Time.now.year + 1,
    :first_name => 'test',
    :last_name => 'account',
    :verification_value => '123',
    :type => 'visa'
    })

    You can check if the given credit card information is valid or not:

    puts credit_card.errors.to_json if !credit_card.valid?


  3. Create a bogus gateway instance:

    @gateway = ActiveMerchant::Billing::BogusGateway.new(
    :login => 'bogus',
    :password => 'bogus'
    )


  4. Now, you can use the bogus gateway instance to process any e-commerce request you want (authorize, purchase, credit, etc)

    response = @gateway.authorize(1000, @creditcard, @options)

    response = @gateway.purchase(1000, @creditcard, @options)


    Note: 1000 = 10$ (credit values in cents)

  5. If your application uses default currency different than the default currency in the targeted payment gateway, you need to initialize ActiveMerchant with your required currency. To do that, add the default currency in your environment configuration file:

    ActiveMerchant::Billing::PaypalExpressGateway.default_currency = 'GBP'


    or you can pass the currency in each interaction with the gateway:

    :currency => 'GBP'


Using the bogus gateway in your test will not help you in testing all credit card types (master card, visa, etc). Bogus gateway support only one card type "bogus" :).
Check the full documentation for ActiveMerchant.

1 comment:

Unknown said...

Wael,

That is a great summary and intro to ActiveMerchant. One thing to note is that we've recently moved over to github, so you can install the plugin from there now: ruby script/plugin install git://github.com/Shopify/active_merchant.git