Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Key Stripe calls so a corrected request is not answered by a stale refusal
Damian Legawiec540a7e85233c
diff --git a/spree/api/app/controllers/spree/api/v3/seller/onboarding_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/onboarding_controller.rbindex 9bf6e1f874..3a72fe05ae 100644--- a/spree/api/app/controllers/spree/api/v3/seller/onboarding_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/onboarding_controller.rb@@ -59,6 +59,14 @@ module Spreerender_service_error(e.message)end+ protected++ def read_actions+ %w[show]+ end++ private+# Where a provider may send the seller back to.## Checked against the panel's own origin rather than echoed: a seller@@ -79,14 +87,6 @@ module Spreepanelend- protected-- def read_actions- %w[show]- end-- private-def requirements@requirements ||= Spree::Sellers::Requirements.new(current_seller.reload)enddiff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rbindex 75ab3a43f5..630d982f96 100644--- a/spree/core/app/models/concerns/spree/preference_schema.rb+++ b/spree/core/app/models/concerns/spree/preference_schema.rb@@ -51,6 +51,11 @@ module Spree# serializers don't allocate `pref.to_s` per request.def preference_schema@preference_schema ||= compute_preference_schema++ # An empty list to callers either way; only the memo tells the two+ # apart, so a schema that could not be computed is retried rather than+ # settled on.+ @preference_schema || []end# Wire-safe variant of `preference_schema` with `:password`@@ -63,7 +68,12 @@ module Spree# `Masking.serialize` to avoid `to_s` allocations per request, not# part of the documented `{ key, type, default }` wire shape.def serialized_preference_schema- @serialized_preference_schema ||= preference_schema.map do |field|+ fields = preference_schema+ # Nothing to memoize yet: the schema could not be computed, and+ # settling on its empty stand-in would outlive the reason for it.+ return fields if @preference_schema.nil?++ @serialized_preference_schema ||= fields.map do |field|wire = { key: field[:key], type: field[:type], default: field[:default] }wire[:default] = nil if field[:type] == :passwordwire.freeze@@ -74,7 +84,10 @@ module Spree# so write-side guards (e.g. the masked-round-trip check) don't# walk the schema or fall back to a `rescue NoMethodError`.def password_preference_keys- @password_preference_keys ||= preference_schema+ fields = preference_schema+ return Set.new.freeze if @preference_schema.nil?++ @password_preference_keys ||= fields.each_with_object(Set.new) { |field, set| set << field[:key] if field[:type] == :password }.freezeend@@ -86,10 +99,14 @@ module Spree# database. Describing the preferences themselves is pure Ruby, so an# error there is a real bug: left inside the rescue it would return an# empty schema and quietly strip every field from the admin form.+ # Nil rather than an empty list, so `preference_schema`'s `||=` asks+ # again next time. Memoizing the failure would leave a class describing+ # no preferences for the life of the process because it was first asked+ # before the database was up.instance = beginnewrescue StandardError- return []+ return nilendinstance.defined_preferences.filter_map do |pref|diff --git a/spree/core/spec/models/spree/payment_method_spec.rb b/spree/core/spec/models/spree/payment_method_spec.rbindex 38e705db71..1b9bee2155 100644--- a/spree/core/spec/models/spree/payment_method_spec.rb+++ b/spree/core/spec/models/spree/payment_method_spec.rb@@ -383,4 +383,40 @@ describe Spree::PaymentMethod, type: :model doexpect(keys).to include(:api_key, :issued_secret)endend++ # Describing a class needs a connection, so the schema can be asked for+ # before there is one — at boot, or in a rake task on an empty database.+ # Settling on the empty answer would leave that class describing no+ # preferences for the life of the process.+ describe 'a schema asked for before the database was up' do+ let(:gateway_class) do+ Class.new(Spree::Gateway) do+ def self.name = 'RetryableSchemaGateway'++ preference :api_key, :password+ end+ end++ it 'is retried rather than settled on' do+ allow(gateway_class).to receive(:new).and_raise(ActiveRecord::ConnectionNotEstablished)+ expect(gateway_class.preference_schema).to be_empty++ allow(gateway_class).to receive(:new).and_call_original++ expect(gateway_class.preference_schema.map { |field| field[:key] }).to eq([:api_key])+ end++ # These memoize off the schema, so caching what they derived from its+ # empty stand-in would outlive the reason for it.+ it 'does not leave the derived lists empty either' do+ allow(gateway_class).to receive(:new).and_raise(ActiveRecord::ConnectionNotEstablished)+ gateway_class.password_preference_keys+ gateway_class.serialized_preference_schema++ allow(gateway_class).to receive(:new).and_call_original++ expect(gateway_class.password_preference_keys).to contain_exactly(:api_key)+ expect(gateway_class.serialized_preference_schema.map { |field| field[:key] }).to eq([:api_key])+ end+ endenddiff --git a/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rb b/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rbindex a8ba6c9067..d1e98b6ffd 100644--- a/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rb+++ b/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rb@@ -103,9 +103,11 @@ module SpreeStripeprivatedef create_connect_account(seller)+ params = connect_account_params(seller)+Stripe::Account.create(- connect_account_params(seller),- api_options.merge(idempotency_key: account_idempotency_key(seller))+ params,+ api_options.merge(idempotency_key: account_idempotency_key(seller, params))).idend@@ -148,7 +150,7 @@ module SpreeStripeparamsend- # Identifies one attempt at creating this seller's account, not the seller.+ # Identifies one request, not the seller.## Two clicks a second apart must not open two Connect accounts, which is# what an idempotency key is for. But Stripe caches a failed response@@ -157,13 +159,14 @@ module SpreeStripe# request stays broken until tomorrow, and sees a confusing complaint# about mismatched parameters rather than the real problem.#- # Rolling on the day keeps double-submit protection where it matters- # while letting a fix take effect. `updated_at` moves whenever the- # seller record is touched, which a failed attempt does.- def account_idempotency_key(seller)- stamp = seller.updated_at.to_i-- "spree-seller-#{seller.prefixed_id}-#{stamp}"+ # Keying on the parameters themselves gets both: the identical request+ # is deduplicated, while a corrected one — a fixed country, an email the+ # seller has since filled in — is a different request and gets a fresh+ # attempt rather than yesterday's cached failure.+ def account_idempotency_key(seller, params)+ digest = Digest::SHA256.hexdigest(params.to_json)++ "spree-seller-#{seller.prefixed_id}-#{digest[0, 32]}"end# Where the seller trades, which decides what currency and bank detailsdiff --git a/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rbindex 1d2cf31633..1724cd7564 100644--- a/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb+++ b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb@@ -188,7 +188,7 @@ module SpreeStripecurrency: seller_payout.currency.downcase,metadata: { spree_seller_payout_id: seller_payout.id }},- gateway.api_options.merge(stripe_account: account_id, idempotency_key: payout_idempotency_key(seller_payout))+ gateway.api_options.merge(stripe_account: account_id, idempotency_key: idempotency_key(seller_payout)))# Stored now rather than waiting for the webhook, so the confirmation@@ -222,27 +222,6 @@ module SpreeStripeseller_transferend- # Keyed to the earnings being settled, not to the settlement row.- #- # A refused payout releases its earnings, so the next sweep assembles a- # *new* row for the same money — and a key derived from that row would be- # a new key, which is Stripe's cue to send the money a second time. The- # transfers are what the two attempts have in common, so they are what- # identifies the operation.- #- # This protects a retry only while Stripe keeps the record, which is a- # day. It is why a payout whose outcome was never established is held- # rather than retried at all: past that window the key is no defence, so- # core keeps those earnings claimed instead of relying on one.- def payout_idempotency_key(seller_payout)- transfer_ids = seller_payout.transfers.order(:id).pluck(:id)- digest = Digest::SHA256.hexdigest(- "#{seller_payout.seller_id}-#{seller_payout.currency}-#{transfer_ids.join(',')}"- )-- "spree-payout-#{digest[0, 32]}"- end-# Nil rather than raising: a checklist row asking why it is incomplete# must not take the page down because Stripe is unreachable.def retrieve_account(seller)diff --git a/spree/providers/stripe/spec/models/spree_stripe/gateway/connect_spec.rb b/spree/providers/stripe/spec/models/spree_stripe/gateway/connect_spec.rbindex 80a0ae4538..c817078ebe 100644--- a/spree/providers/stripe/spec/models/spree_stripe/gateway/connect_spec.rb+++ b/spree/providers/stripe/spec/models/spree_stripe/gateway/connect_spec.rb@@ -242,6 +242,41 @@ RSpec.describe SpreeStripe::Gateway::Connect dogateway.create_connect_account_link(seller: seller, refresh_url: 'https://s/r', return_url: 'https://s/d')end++ # Stripe caches a refusal against the key for a day. A key that does not+ # move with what is being sent would replay yesterday's failure at a+ # seller who has since corrected the thing that caused it.+ describe 'the idempotency key' do+ let(:new_seller) { create(:seller, :approved, store: store, contact_email: '[email protected]') }++ def keys_from_two_attempts+ keys = []+ allow(Stripe::Account).to receive(:create) do |_params, options|+ keys << options[:idempotency_key]+ raise Stripe::InvalidRequestError.new('bad email', 'email')+ end++ 2.times do+ gateway.create_connect_account_link(seller: new_seller, refresh_url: 'https://s/r',+ return_url: 'https://s/d')+ rescue Stripe::StripeError, Spree::Core::GatewayError+ next+ end++ keys+ end++ it 'repeats for an identical request, so two clicks open one account' do+ expect(keys_from_two_attempts.uniq.size).to eq(1)+ end++ it 'moves once the seller corrects what the request carried' do+ first = keys_from_two_attempts.first+ new_seller.update!(contact_email: '[email protected]')++ expect(keys_from_two_attempts.first).not_to eq(first)+ end+ endenddescribe 'the account a seller is onboarded to' dodiff --git a/spree/providers/stripe/spec/models/spree_stripe/payout_provider_spec.rb b/spree/providers/stripe/spec/models/spree_stripe/payout_provider_spec.rbindex 516a5417bc..d8c6238f77 100644--- a/spree/providers/stripe/spec/models/spree_stripe/payout_provider_spec.rb+++ b/spree/providers/stripe/spec/models/spree_stripe/payout_provider_spec.rb@@ -139,6 +139,31 @@ RSpec.describe SpreeStripe::PayoutProvider dodescribed_class.new.pay!(payout)end+ # Keyed to the settlement being attempted, not to the money in it. Stripe+ # caches a refusal against a key for a day, so a key shared with the+ # settlement that was already refused would replay that refusal instead of+ # genuinely trying again — and a refusal releases its earnings precisely so+ # the next sweep can retry them.+ it 'gives a fresh settlement of the same earnings its own key' do+ keys = []+ allow(Stripe::Payout).to receive(:create) do |_attributes, options|+ keys << options[:idempotency_key]+ Stripe::StripeObject.construct_from(id: "po_#{keys.size}")+ end+ transfer = create(:seller_transfer, :completed, seller: seller, payout: payout, amount: 40,+ order: create(:order, store: store, seller: seller))+ described_class.new.pay!(payout)++ # What a refusal leaves behind: the earnings released, then swept into a+ # settlement of their own.+ payout.fail!+ retried = create(:seller_payout, seller: seller, amount: 40, currency: 'USD')+ transfer.update!(payout: retried)+ described_class.new.pay!(retried)++ expect(keys.uniq.size).to eq(2)+ end+it 'refuses a seller who holds no Stripe account' doother = create(:seller_payout, seller: create(:seller, :approved, store: store))