Created
February 2, 2017 05:19
-
-
Save fylooi/bfab6be03c85a80f64bab301cda393bb to your computer and use it in GitHub Desktop.
This file contains 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
# this class builds a Spree::CreditCard for saved payment | |
# from our existing user profile structure | |
class SpreeCreditCardBuilder | |
def self.create!(user) | |
new(user).create_without_validation! | |
end | |
def initialize(user) | |
@params = {} | |
# spree cc icons depend on downcased cc type | |
@params[:cc_type] = user.cc_brand.downcase | |
@params[:last_digits] = user.cc_last4 | |
@params[:gateway_customer_profile_id] = user.stripe_customer_id | |
@params[:user_id] = user.id | |
raise "Invalid payment details on profile for user #{user.email}" if @params.values.find(&:blank?) | |
end | |
def build | |
Spree::CreditCard.new( | |
@params.merge( | |
payment_method_id: stripe_payment_method.id, | |
gateway_payment_profile_id: stripe_default_source(@params[:gateway_customer_profile_id]) | |
) | |
) | |
end | |
def create_without_validation! | |
raise 'Stripe payment method not created' if stripe_payment_method.blank? | |
build.save!(validate: false) | |
end | |
def stripe_payment_method | |
Spree::PaymentMethod.find_by(type: 'Spree::Gateway::StripeGateway') | |
end | |
def stripe_default_source(stripe_customer) | |
Stripe::Customer.retrieve(stripe_customer).default_source | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment