Created
April 15, 2010 00:59
-
-
Save erikpukinskis/366561 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_merchant' | |
class Charge < ActiveRecord::Base | |
attr_accessor :auth_response, :capture_response | |
belongs_to :user | |
validate :credit_card_must_be_valid | |
validates_presence_of :billing_address | |
validates_presence_of :city, :message => "for billing address can't be blank" | |
validates_presence_of :state, :message => "for billing address can't be blank" | |
validates_presence_of :billing_zip | |
def credit_card_must_be_valid | |
unless credit_card.valid? | |
fields = { | |
"number" => :card_number, | |
"month" => :exp_month, | |
"year" => :exp_year, | |
"name_on_card" => :name_on_card | |
} | |
credit_card.errors.each do |card_field,messages| | |
errors.add fields[card_field], messages.last | |
end | |
end | |
end | |
def card_number=(number) | |
super(clean_number(number)) | |
end | |
def clean_number(number) | |
number.gsub(/[-\s]/, '') | |
end | |
def give_address_to(user) | |
user.update_attributes(:address => billing_address, :city => city, :state => state, | |
:shipping_zip => billing_zip) | |
end | |
def Charge.pending | |
find_all_by_pending(true) | |
end | |
def queue | |
unless pending | |
update_attributes(:pending => true) | |
Delayed::Job.enqueue ChargeCardJob.new(id) | |
end | |
end | |
def card_number_masked | |
card_number[12,4] | |
end | |
def credit_card | |
@credit_card ||= CreditCard.new( | |
:number => card_number, | |
:month => exp_month, | |
:year => exp_year, | |
:name_on_card => name_on_card | |
) | |
end | |
def gateway | |
@gateway ||= ActiveMerchant::Billing::Base.gateway(:paypal).new( | |
:login => ENV['PAYPAL_LOGIN'], | |
:password => ENV['PAYPAL_PASSWORD'], | |
:signature => ENV['PAYPAL_SIGNATURE'] | |
) | |
end | |
def run | |
ActiveMerchant::Billing::Base.mode = :test | |
address = { | |
:zip => billing_zip, | |
:country => "US", | |
:state => state, | |
:city => city, | |
:address1 => billing_address | |
} | |
if credit_card.valid? | |
self.auth_response = gateway.authorize(amt, credit_card, :address => address, | |
:ip => "1.1.1.1") # FIXME this should come from the charge | |
if auth_response.success? | |
debugger | |
self.capture_response = gateway.capture(amt, auth_response.authorization) | |
end | |
end | |
if credit_card.valid? && auth_response.success? && capture_response.success? | |
update_attributes(:success => true, :pending => false) | |
user.update_attributes(:paid => true, :plan => towards_plan) | |
else | |
logger.error("Charge for #{user.email} failed: ") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment