-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstripe_handler_module.rb
More file actions
54 lines (45 loc) · 1.56 KB
/
stripe_handler_module.rb
File metadata and controls
54 lines (45 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
require "stripe"
module StripeHandlerModule
extend ActiveSupport::Concern
# Set the stripe API key when we include the module
included do
Stripe.api_key = ENV['YOUR_API_KEY'] # tp api key
end
# Create a charge
def create_charge(amount, token)
result = stripe_handler do
Stripe::Charge.create(
:amount => (amount.to_f * 100).to_i,
:currency => "usd",
:source => token,
:description => "Charge for testing.pays@example.com"
)
end
return result
end
# Function for logging the response of a stripe request
def stripe_handler
begin
result = yield
rescue Stripe::CardError, # Most common error, occurs when card cannot be charged
Stripe::RateLimitError, # Too many requests hit the API too quickly
Stripe::InvalidRequestError, # The request has invalid params
Stripe::AuthenticationError, # Failed to authenticate with stripes api
Stripe::APIConnectionError, # Failed to connect to stripes api
Stripe::StripeError => e # Generic stripe error
if e.json_body
error = {error: e.json_body[:error], status: e.http_status}
else
error = {error: e.message}
end
rescue => e
# Something else happened, completely unrelated to Stripe
Rails.logger.info "500 error"
Rails.logger.info e.message
Rails.logger.info e.backtrace
error = {error: "err_not_stripe"} # The error was not generated by stripe
end
# Return the result or error from the request
return result || error
end
end