diff --git a/app/controllers/spree/credit_cards_controller.rb b/app/controllers/spree/credit_cards_controller.rb index a92faf088b..330a59a500 100644 --- a/app/controllers/spree/credit_cards_controller.rb +++ b/app/controllers/spree/credit_cards_controller.rb @@ -63,8 +63,9 @@ module Spree # It destroys the whole customer object def destroy_at_stripe - stripe_customer = Stripe::Customer.retrieve(@credit_card.gateway_customer_profile_id, {}) + Stripe::CreditCardCloner.new.destroy_clones(@credit_card) + stripe_customer = Stripe::Customer.retrieve(@credit_card.gateway_customer_profile_id, {}) stripe_customer&.delete unless stripe_customer.deleted? end diff --git a/lib/stripe/credit_card_cloner.rb b/lib/stripe/credit_card_cloner.rb index 9bbd009342..7d90960bf5 100644 --- a/lib/stripe/credit_card_cloner.rb +++ b/lib/stripe/credit_card_cloner.rb @@ -17,11 +17,23 @@ module Stripe class CreditCardCloner - def find_or_clone(credit_card, connected_account_id) - if card = find_cloned_card(credit_card, connected_account_id) - card + def find_or_clone(card, connected_account_id) + if cloned_card = find_cloned_card(card, connected_account_id) + cloned_card else - clone(credit_card, connected_account_id) + clone(card, connected_account_id) + end + end + + def destroy_clones(card) + card.user.customers.each do |customer| + next unless stripe_account = customer.enterprise.stripe_account&.stripe_user_id + + customer_id, _payment_method_id = find_cloned_card(card, stripe_account) + next unless customer_id + + customer = Stripe::Customer.retrieve(customer_id, { stripe_account: stripe_account }) + customer&.delete unless customer.deleted? end end