Friday, 6 September 2013

Integrating Active Merchant with Rails 4?

Integrating Active Merchant with Rails 4?

I've seen a lot of tutorials on using Active Merchant with older versions
of Rails, but I can't seem to find any sort of documentation or help for
the version I'm working with, 4.0.
It seems that railscasts has the best tutorial for integrating with an old
version Rails, but it's way out of date. I was hoping someone could help
me figure out how to make my Credit model work with Rails 4.
This is what I've been able to figure out so far:
class Credit < Transaction # inheirits a broader class for things like
coupons, etc.
attr_accessor :number, :first_name, :last_name, :verification_value,
:month, :year, :ip
validates :amount_cents, numericality: {greater_than: 0}
validate :validate_card
before_save :charge_card
private
def gateway
Rails.application.config.gateway #defined in config
end
def validate_card
unless credit_card.valid?
credit_card.errors.full_messages.each do |message|
errors.add_to_base message
end
end
end
def credit_card
ActiveMerchant::Billing::CreditCard.new(
:number => number,
:month => month,
:year => year,
:first_name => first_name,
:last_name => last_name,
:verification_value => verification_value
)
end
def charge_card
if credit_card.valid?
response = gateway.authorize(amount_cents, credit_card, {ip: :ip})
if response.success?
gateway.capture(amount_cents, response.authorization)
else
errors.add(:base, response.message)
end
else
errors.add(:base, "This card information is not valid.")
end
end
end
The problem here is that validate_card doesn't seem to add any errors to
the form, and charge_card does not stop saves if a gateway does not
authorize the credit amount.

No comments:

Post a Comment