Skip to content

Instantly share code, notes, and snippets.

@d1rtyvans
Created June 15, 2016 16:08
Show Gist options
  • Save d1rtyvans/bd694e6a4723c519cbb88e9c8d0eb7b3 to your computer and use it in GitHub Desktop.
Save d1rtyvans/bd694e6a4723c519cbb88e9c8d0eb7b3 to your computer and use it in GitHub Desktop.
class StripeCharger
def initialize(email:, token:, order:)
@email = email
@token = token
@order = order
end
def create_charge
Stripe.api_key = ENV.fetch("STRIPE_SECRET_KEY")
charge if order.costs_money?
end
private
attr_reader :email, :token, :order
def charge
Stripe::Charge.create(
customer: customer.id,
amount: order.total,
currency: "usd",
description: "HomeCookin' Meal")
end
def customer
if order.user.stripe_id
returning_customer.tap do |rc|
rc.source = token
rc.save
end
else
new_customer.tap do |nc|
order.user.update(stripe_id: nc.id) if nc.id
end
end
end
def returning_customer
Stripe::Customer.retrieve(order.user.stripe_id)
end
def new_customer
Stripe::Customer.create(
email: email,
source: token,
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment