Fix checkout Stripe: ricrea customer se ID test su ambiente live.

Evita errore «No such customer» dopo passaggio da sk_test a sk_live.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-06-02 19:11:42 +02:00
parent 2b8f842752
commit 1a84d6ae42
3 changed files with 90 additions and 15 deletions

View File

@@ -0,0 +1,59 @@
module Billing
module Stripe
# Garantisce un Customer Stripe valido per la modalità API attiva (test vs live).
class EnsureCustomer
def self.call(club:, user:)
new(club: club, user: user).call
end
def initialize(club:, user:)
@club = club
@user = user
end
def call
sub = @club.subscription || @club.build_subscription(plan: Plan["free"], status: "active")
if sub.stripe_customer_id.present? && !customer_valid?(sub.stripe_customer_id)
reset_stripe_billing!(sub)
end
return sub.stripe_customer_id if sub.stripe_customer_id.present?
customer = ::Stripe::Customer.create(
email: billing_email,
name: @club.billing_legal_name.presence || @club.name,
metadata: { club_id: @club.id }
)
sub.update!(stripe_customer_id: customer.id)
customer.id
end
private
def billing_email
@club.billing_email.presence || @user.email
end
def customer_valid?(customer_id)
::Stripe::Customer.retrieve(customer_id)
true
rescue ::Stripe::InvalidRequestError => e
return false if e.code == "resource_missing" || e.message.include?("No such customer")
raise
end
def reset_stripe_billing!(sub)
Rails.logger.info(
"[Stripe] Customer #{sub.stripe_customer_id} non valido per club #{@club.id} — reset ID Stripe locali"
)
sub.update!(
stripe_customer_id: nil,
stripe_subscription_id: nil,
cancel_at_period_end: false
)
end
end
end
end