How To Integrate Authorize Net (AIM) Payment In Rails

Authorize Net (AIM) method enables internet merchants to accept online payments via credit card. We shall see how to integrate authorize net payment gateway inside a rails app to accept online payments using activemerchant library.

# Gemfile
gem 'activemerchant', :require => 'active_merchant'

Register for authorize net sandbox account click here

Payment gateway credentials

# config/authorize_net.yml
development: &development
mode: test
login: 9gdLh6T
key: 67fu45xw6VP92LX1

production:
<<: *development

test:
<<: *development

Payment & creditcard form

# app/views/payments/new
= form_for @payment, :url => payments_url do |f|
= f.text_field :amount
= fields_for :creditcard, @creditcard do |cc|
= cc.text_field :name
= cc.text_field :number
= cc.select :month, Date::ABBR_MONTHNAMES.compact.each_with_index.collect{|m, i| [m, i+1]}, {:prompt => 'Select'}
= cc.select :year, Array.new(15){|i| Date.current.year+i}, {:prompt => 'Select'}
= cc.text_field :verification_value
= f.submit 'Pay'

Payments Controller

# app/controllers/payments_controller.rb
class PaymentsController < ApplicationController

def new
@payment = Payment.new
@creditcard = ActiveMerchant::Billing::CreditCard.new
end

def create
@payment = Payment.new(params[:payment])
@creditcard = ActiveMerchant::Billing::CreditCard.new(params[:creditcard])
@payment.valid_card = @creditcard.valid?
if @payment.valid?
@payment = @payment.process_payment(@creditcard)
if @payment.success?
@payment.save
flash[:notice] = I18n.t('payment.success')
redirect_to payments_url and return
else
flash[:error] = I18n.t('payment.failed')
end
end
render :action => :new
end
end

Generate & Migrate Payment Model

rails g model payment status:string amount:float transaction_number:string
rake db:migrate

Payment Model

# app/models/payment.rb
class Payment < ActiveRecord::Base

PROCESSING, FAILED, SUCCESS = 1, 2, 3

validates :valid_card, :inclusion => {:in => [true], :message => 'Invalid Credit Card'}
validates :amount, :presence => true, :numericality => { :greater_than => 0 }

def process_payment(creditcard)
ActiveMerchant::Billing::Base.mode = auth['mode'].to_sym
self.status = PROCESSING
response = gateway.purchase(amount * 100, creditcard)

if response.success?
self.transaction_number = response.subscription_id
self.status = SUCCESS
else
self.status = FAILED
end
return self
rescue Exception => e
self.status = FAILED
return self
end

def success?
self.status == SUCCESS
end

private
def gateway
ActiveMerchant::Billing::AuthorizeNetGateway.new(
:login    => auth['login'],
:password => auth['key'])
end

def auth
@@auth ||= YAML.load_file("#{Rails.root}/config/authorize_net.yml")[Rails.env]
end
end

3 thoughts on “How To Integrate Authorize Net (AIM) Payment In Rails

  1. Have you ever done this with spree? I’m having more trouble integrating it with spree than doing it from scrap.

  2. In Rails application Authorize.net CIM is not created the customer profile id and customer payment profile id i used the below code could you please help what is i missed in the below code

    ———————————————————-
    def purchase
    options = {:profile => {
    :merchant_customer_id => self.ordid,
    :email => self.user.present? ? self.user.email.to_s : “ashok@dine-media.com”
    }
    }
    customer_profile = GATEWAY.create_customer_profile(options)
    customer_profile_id = customer_profile.params[“customer_profile_id”]
    payment_profile = {
    :bill_to => {
    :first_name => billing_first_name,
    :last_name => billing_last_name,
    :address => billing_address,
    :state => billing_state,
    :zip => billing_zip,
    :phone_number => billing_phone
    },
    :payment => {
    :credit_card => credit_card
    }
    }
    options = {
    :customer_profile_id => customer_profile_id,
    :payment_profile => payment_profile
    }
    payment_profile = GATEWAY.create_customer_payment_profile(options)
    customer_payment_profile_id = payment_profile.params[“customer_payment_profile_id”]
    transaction =
    {:transaction => {
    :type => :auth_capture,
    :amount => price_in_cents,
    :customer_profile_id => customer_profile_id,
    :customer_payment_profile_id => customer_payment_profile_id
    }
    }
    response = GATEWAY.create_customer_profile_transaction(transaction)
    response.success?
    end

    ———————————-

  3. Awsome example, but i face some error that undefined method “valid_card” can you explain this .

    Thanks for the help

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.