2016-06-18 18:13:29 +05:30
|
|
|
class Payment < ActiveRecord::Base
|
|
|
|
|
has_many :ticket_purchases
|
|
|
|
|
belongs_to :user
|
|
|
|
|
belongs_to :conference
|
|
|
|
|
|
|
|
|
|
attr_accessor :credit_card_number
|
|
|
|
|
attr_accessor :credit_card_type
|
|
|
|
|
attr_accessor :card_verification_value
|
|
|
|
|
attr_accessor :expiration_month
|
|
|
|
|
attr_accessor :expiration_year
|
|
|
|
|
|
|
|
|
|
validates :first_name, presence: true
|
|
|
|
|
validates :last_name, presence: true
|
|
|
|
|
validates :credit_card_number, presence: true
|
|
|
|
|
validates :card_verification_value, presence: true, length: { minimum: 3, maximum: 4 }
|
|
|
|
|
validates :expiration_month, presence: true, numericality: { greater_than_or_equal_to: 1, less_than_or_equal_to: 12 }
|
|
|
|
|
validates :expiration_year, presence: true
|
|
|
|
|
validates :amount, presence: true, numericality: { greater_than: 0 }
|
2016-07-21 10:15:17 +05:30
|
|
|
validates :user_id, presence: true
|
|
|
|
|
validates :conference_id, presence: true
|
2016-06-18 18:13:29 +05:30
|
|
|
|
|
|
|
|
enum status: {
|
|
|
|
|
unpaid: 0,
|
|
|
|
|
success: 1,
|
|
|
|
|
failure: 2
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
def credit_card
|
2016-07-19 12:37:19 +05:30
|
|
|
@credit_card ||= ActiveMerchant::Billing::CreditCard.new(
|
2016-06-18 18:13:29 +05:30
|
|
|
first_name: first_name,
|
|
|
|
|
last_name: last_name,
|
|
|
|
|
number: credit_card_number,
|
|
|
|
|
month: expiration_month,
|
|
|
|
|
year: expiration_year,
|
|
|
|
|
verification_value: card_verification_value
|
|
|
|
|
)
|
|
|
|
|
end
|
|
|
|
|
|
2016-07-21 10:15:17 +05:30
|
|
|
def amount_to_pay
|
|
|
|
|
Ticket.total_price(conference, user, paid: false).cents
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
def purchase
|
2016-07-19 12:37:19 +05:30
|
|
|
gateway_response = begin
|
2016-07-21 10:15:17 +05:30
|
|
|
GATEWAY.purchase(amount_to_pay, credit_card, currency: conference.tickets.first.price_currency)
|
2016-06-18 18:13:29 +05:30
|
|
|
rescue
|
2016-07-19 12:37:19 +05:30
|
|
|
ActiveMerchant::Billing::Response.new(false, 'Unable to receive any response from the payment gateway.')
|
2016-06-18 18:13:29 +05:30
|
|
|
end
|
|
|
|
|
|
2016-07-19 12:37:19 +05:30
|
|
|
if gateway_response.success?
|
|
|
|
|
self.last4 = credit_card.display_number
|
|
|
|
|
self.authorization_code = gateway_response.authorization
|
|
|
|
|
self.status = 'success'
|
|
|
|
|
else
|
|
|
|
|
errors.add(:base, gateway_response.message)
|
2016-07-06 12:40:42 +05:30
|
|
|
self.status = 'failure'
|
2016-06-18 18:13:29 +05:30
|
|
|
end
|
2016-07-19 12:37:19 +05:30
|
|
|
|
|
|
|
|
success?
|
2016-07-06 23:50:04 +05:30
|
|
|
end
|
2016-06-18 18:13:29 +05:30
|
|
|
end
|