2017-09-05 22:23:34 +03:00
|
|
|
class Payment < ApplicationRecord
|
2016-07-27 19:27:39 +05:30
|
|
|
has_many :ticket_purchases
|
|
|
|
|
belongs_to :user
|
|
|
|
|
belongs_to :conference
|
|
|
|
|
|
2016-07-29 00:34:03 +05:30
|
|
|
attr_accessor :stripe_customer_email
|
|
|
|
|
attr_accessor :stripe_customer_token
|
2016-07-28 15:27:30 +05:30
|
|
|
|
2016-07-27 19:27:39 +05:30
|
|
|
validates :status, presence: true
|
|
|
|
|
validates :user_id, presence: true
|
|
|
|
|
validates :conference_id, presence: true
|
|
|
|
|
|
|
|
|
|
enum status: {
|
|
|
|
|
unpaid: 0,
|
|
|
|
|
success: 1,
|
|
|
|
|
failure: 2
|
|
|
|
|
}
|
|
|
|
|
|
2016-07-28 15:27:30 +05:30
|
|
|
def amount_to_pay
|
|
|
|
|
Ticket.total_price(conference, user, paid: false).cents
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
def purchase
|
2016-08-04 13:44:09 +05:30
|
|
|
gateway_response = Stripe::Charge.create source: stripe_customer_token,
|
2016-07-29 00:34:03 +05:30
|
|
|
receipt_email: stripe_customer_email,
|
2016-08-04 13:44:09 +05:30
|
|
|
description: "ticket purchases(#{user.username})",
|
2016-07-29 00:34:03 +05:30
|
|
|
amount: amount_to_pay,
|
|
|
|
|
currency: conference.tickets.first.price_currency
|
|
|
|
|
|
2016-08-09 02:29:44 +05:30
|
|
|
self.amount = gateway_response[:amount]
|
2016-07-29 00:34:03 +05:30
|
|
|
self.last4 = gateway_response[:source][:last4]
|
|
|
|
|
self.authorization_code = gateway_response[:id]
|
|
|
|
|
self.status = 'success'
|
|
|
|
|
true
|
|
|
|
|
|
2016-08-10 13:54:24 +05:30
|
|
|
rescue Stripe::StripeError => error
|
2016-07-29 00:34:03 +05:30
|
|
|
errors.add(:base, error.message)
|
|
|
|
|
self.status = 'failure'
|
|
|
|
|
false
|
2016-07-27 19:27:39 +05:30
|
|
|
end
|
|
|
|
|
end
|