docbrown/app/services/payments/customer.rb
Kirk Haines ed74f2f245
Abstract DatadogStatsClient to ForemStatsClient (#12304)
* This change abstracts the DatadogStatsClient into a ForemStatsClient.
The purpose of this abstraction is to set the foundation for a subsequent PR that will allow one to use New Relic for recording Forem stats, instead of Datadog, if there is a New Relic configuration found.
This specific change creates an abstraction layer that can be built upon, without changing any actual default behavior. All specs still pass.

* Use delegate instead of explicit methods.

* Delegate instead of explicit methods.

* Fix the error.

* Refactor according to the suggestions in the comments.

* Ooops.  Stats work better when all of the code is committed.

* Removing the alias of count to increment since that was done in error.
2021-01-27 11:25:44 -05:00

80 lines
2 KiB
Ruby

module Payments
# A thin wrapper on Stripe Customers and Charges APIs
# see: <https://stripe.com/docs/api/customers/object>,
# <https://stripe.com/docs/api/charges>
class Customer
class << self
def get(customer_id)
request do
Stripe::Customer.retrieve(customer_id)
end
end
def create(**params)
request do
Stripe::Customer.create(**params)
end
end
def save(customer)
request do
customer.save
end
end
def create_source(customer_id, token)
request do
Stripe::Customer.create_source(customer_id, source: token)
end
end
def get_source(customer, source_id)
request do
customer.sources.retrieve(source_id)
end
end
def detach_source(customer_id, source_id)
request do
Stripe::Customer.detach_source(customer_id, source_id)
end
end
def get_sources(customer, **params)
request do
customer.sources.list(**params)
end
end
def charge(customer:, amount:, description:, card_id: nil)
source = card_id || customer.default_source
request do
Stripe::Charge.create(
customer: customer.id,
source: source,
amount: amount,
description: description,
currency: "usd",
)
end
end
private
def request
yield
rescue Stripe::InvalidRequestError => e
ForemStatsClient.increment("stripe.errors", tags: ["error:InvalidRequestError"])
raise InvalidRequestError, e.message
rescue Stripe::CardError => e
ForemStatsClient.increment("stripe.errors", tags: ["error:CardError"])
raise CardError, e.message
rescue Stripe::StripeError => e
Honeybadger.notify(e)
ForemStatsClient.increment("stripe.errors", tags: ["error:StripeError"])
raise PaymentsError, e.message
end
end
end
end