17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
# File 'lib/shoppe/stripe.rb', line 17
def setup
Shoppe.add_settings_group :stripe, [:stripe_api_key, :stripe_publishable_key, :stripe_currency]
require 'stripe'
require 'shoppe/stripe/order_extensions'
Shoppe::Order.send :include, Shoppe::Stripe::OrderExtensions
require 'shoppe/stripe/payment_extensions'
Shoppe::Payment.send :include, Shoppe::Stripe::PaymentExtensions
Shoppe::Order.before_confirmation do
if self.properties['stripe_customer_token']
begin
charge = ::Stripe::Charge.create({:customer => self.properties['stripe_customer_token'], :amount => (self.total * BigDecimal(100)).round, :currency => Shoppe.settings.stripe_currency, :capture => false}, Shoppe.settings.stripe_api_key)
self.payments.create(:amount => self.total, :method => 'Stripe', :reference => charge.id, :refundable => true, :confirmed => false)
rescue ::Stripe::CardError
raise Shoppe::Errors::PaymentDeclined, "Payment was declined by the payment processor."
end
end
end
Shoppe::Order.before_acceptance do
self.payments.where(:confirmed => false, :method => 'Stripe').each do |payment|
begin
payment.stripe_charge.capture
payment.update_attribute(:confirmed, true)
rescue ::Stripe::CardError
raise Shoppe::Errors::PaymentDeclined, "Payment ##{payment.id} could not be captured by Stripe. Investigate with Stripe. Do not accept the order."
end
end
end
Shoppe::Order.before_rejection do
self.payments.where(:confirmed => false, :method => 'Stripe').each do |payment|
payment.refund!(payment.refundable_amount)
end
end
Shoppe::Payment.before_create do
if self.refund? && self.parent && self.parent.method == 'Stripe'
begin
options = {}
if self.parent.confirmed?
options[:amount] = (self.amount * BigDecimal(100)).round.abs
else
if self.amount.abs != self.parent.refundable_amount
raise Shoppe::Errors::RefundFailed, :message => "Refund could not be processed because charge hasn't been captured and the amount is not the same as the original payment."
end
end
refund = self.parent.stripe_charge.refund(options)
self.method = 'Stripe'
self.reference = refund.id
true
rescue ::Stripe::CardError, ::Stripe::InvalidRequestError => e
raise Shoppe::Errors::RefundFailed, :message => "Refund could not be processed with Stripe (#{e.class}: #{e.message}). Please investigate with Stripe."
end
end
end
end
|