Last active
September 17, 2017 15:57
-
-
Save blackxored/9737985 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PaymentService | |
VALID_CURRENCIES = Money::Currency.table.keys.map(&:upcase) | |
DEFAULT_CURRENCY = :EUR | |
APP_FEE = ->(amount) { amount * 15 / 100} | |
def initialize(user) | |
@user = user | |
@app_id = ENV['STRIPE_APP_ID'] | |
@app_secret = ENV['STRIPE_KEY'] | |
@client = OAuth2::Client.new(@app_id, @app_secret, site: 'https://connect.stripe.com') | |
end | |
def exchange_token(auth_code) | |
begin | |
resp = @client.auth_code.get_token(auth_code, params: { scope: 'read_write'}) | |
token = resp.params['stripe_publishable_key'] | |
customer = create_customer(@app_secret) | |
@user.profile.payment_info.update(stripe: { token: token, customer_id: customer.id }) | |
rescue OAuth2::Error => e | |
Bugsnag.notify(e) | |
Rails.logger.error e.message | |
false | |
end | |
end | |
def charge_customer(customer, amount) | |
check_stripe_connect!(@user, customer) | |
charger_token = access_token_for(@user) | |
chargee_customer_id = customer_id_for(customer) | |
token = Stripe::Token.create({ customer: chargee_customer_id }, charger_token) | |
Stripe::Charge.create( | |
amount: amount, | |
currency: user_currency, | |
card: token['id'], | |
description: payment_description(customer) | |
#application_fee: APP_FEE[amount] # TODO: re-enable after response from Stripe | |
) | |
end | |
private | |
def create_customer(token) | |
Stripe::Customer.create( | |
{ email: @user.email, description: @user.full_name }, | |
token | |
) | |
end | |
def check_stripe_connect!(*users) | |
raise StripeNotConnectedError unless users.all?(&:stripe_connected?) | |
end | |
def customer_id_for(user) | |
stripe_info_for(user)['customer_id'] | |
end | |
def access_token_for(user) | |
stripe_info_for(user)['token'] | |
end | |
def stripe_info_for(user) | |
user.profile.payment_info.stripe | |
end | |
def self.find_customer(user) | |
Stripe::Customer.retrieve(customer_id_for(user)) | |
end | |
def payment_description(customer) | |
"Payment to #{@user.full_name} (#{@user.username})" | |
end | |
def user_currency | |
currency = @user.profile.payment_info.default_currency || DEFAULT_CURRENCY | |
currency.to_s.downcase | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment