Skip to content

Instantly share code, notes, and snippets.

@VoltanBro
Created July 5, 2022 09:45
Show Gist options
  • Select an option

  • Save VoltanBro/9b4fbd151ecdb4c07bea4dd0e865b1c4 to your computer and use it in GitHub Desktop.

Select an option

Save VoltanBro/9b4fbd151ecdb4c07bea4dd0e865b1c4 to your computer and use it in GitHub Desktop.

Revisions

  1. VoltanBro created this gist Jul 5, 2022.
    52 changes: 52 additions & 0 deletions stripe.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    # frozen_string_literal: true

    class CustomerCreator < BaseInteractor
    def call
    validate_bot_owner
    create_stripe_customer
    end

    private

    def validate_bot_owner
    return if bot_owner?

    context.fail!(error: I18n.t('stripe.customer.errors.wrong_user'), status: :forbidden)
    end

    def bot_owner?
    context.user_profile.bot_owner?
    end

    def create_stripe_customer
    context.stripe_customer = if check_current_customer&.id.present?
    context.user_profile.stripe_customer
    else
    context.user_profile.create_stripe_customer(customer_id: new_stripe_customer.id)
    end
    end

    def current_customer_id
    @current_customer_id = context.user_profile.stripe_customer&.customer_id
    end

    def check_current_customer
    check_stripe_customer if current_customer_id.present?
    end

    def check_stripe_customer
    Stripe::Customer.retrieve(current_customer_id)
    rescue Stripe::StripeError => e
    context.stripe_error = e.message
    end

    def new_stripe_customer
    ::Stripe::Adapter.create_customer(params: params)
    rescue Stripe::StripeError => e
    context.fail!(error: e.message, status: :unprocessable_entity)
    end

    def params
    { email: context.user_profile.user.email }
    end
    end