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
Let Spree decide when a seller is paid, not Stripe
Damian Legawiec0388031d921e
diff --git a/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rb b/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rbindex 237ebffb8a..ccbf27578f 100644--- a/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rb+++ b/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rb@@ -94,25 +94,57 @@ module SpreeStripedef create_connect_account(seller)Stripe::Account.create(- {- type: 'express',- email: seller.contact_email,- business_profile: { name: seller.name },- # The platform pays Stripe's fees and owns the dispute- # relationship, which is what makes this a marketplace rather than- # a referral.- controller: {- fees: { payer: 'application' },- losses: { payments: 'application' },- stripe_dashboard: { type: 'express' }- },- capabilities: { transfers: { requested: true } },- metadata: { spree_seller_id: seller.id }- },+ connect_account_params(seller),api_options.merge(idempotency_key: "spree-seller-#{seller.prefixed_id}")).idend+ def connect_account_params(seller)+ country_code = seller_country_code(seller)++ params = {+ type: 'express',+ country: country_code,+ email: seller.contact_email,+ business_profile: { name: seller.name },+ # The platform pays Stripe's fees and owns the dispute relationship,+ # which is what makes this a marketplace rather than a referral.+ controller: {+ fees: { payer: 'application' },+ losses: { payments: 'application' },+ stripe_dashboard: { type: 'express' }+ },+ capabilities: { transfers: { requested: true } },+ # Spree decides when a seller is settled, so Stripe must not also be+ # paying their balance out on a schedule of its own — two clocks on+ # one relationship, and the seller's own setting would be the one+ # that did nothing.+ settings: { payouts: { schedule: { interval: 'manual' } } },+ metadata: { spree_seller_id: seller.id }+ }++ # Paying a seller abroad is a different agreement, not a variation on+ # the domestic one: Stripe requires the recipient service agreement,+ # under which the seller may not accept card payments in their own+ # right. Without it the account cannot be created at all.+ params[:tos_acceptance] = { service_agreement: 'recipient' } if cross_border?(country_code)++ params+ end++ # Where the seller trades, which decides what currency and bank details+ # their account can hold. Falls back to the marketplace's own country —+ # Stripe would otherwise assume it anyway, and assuming it silently is+ # how a seller ends up with an account no local bank can receive.+ def seller_country_code(seller)+ seller.billing_address&.country_code.presence || store.default_country_code+ end++ def cross_border?(country_code)+ country_code.present? && store.default_country_code.present? &&+ country_code.to_s.upcase != store.default_country_code.to_s.upcase+ end+# Whether Stripe will let this seller be paid. It can go back to false —# a seller whose documents expire stops being payable, and the ledger# must stop crediting them rather than promise money nothing can send.@@ -169,18 +201,12 @@ module SpreeStripeseller.payout_account_reference(SpreeStripe::PayoutProvider)end- # Stripe's own id first. The fallback is for a settlement recorded before- # Stripe named it, and it must match on amount as well as currency:- # Stripe batches a connected account's balance on its own schedule, so- # one payout of 250 does not mean the oldest settlement of 40 landed —- # completing that would debit the wrong figure and stamp Stripe's id- # where the settlement it really belongs to can no longer find it.+ # By Stripe's own id alone. Spree creates the payout, so it stored that+ # id when it did — an event naming an id we hold no settlement for is+ # about a payout somebody made outside Spree, and guessing which of our+ # settlements it meant would complete the wrong one.def find_payout(seller, object)- seller.seller_payouts.find_by(reference: object.id) ||- seller.seller_payouts.owed.- where(currency: object.currency.to_s.upcase, reference: nil).- where(amount: Spree::Money::Rounding.from_minor_units(object.amount, object.currency)).- order(:created_at).first+ seller.seller_payouts.find_by(reference: object.id)enddef verify_connect_webhook_signature(raw_body, headers)diff --git a/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rbindex 4f87699080..4acee799c1 100644--- a/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb+++ b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb@@ -73,14 +73,36 @@ module SpreeStripeseller_transferend- # Records the settlement Stripe will make on its own schedule.+ # Sends a settlement from the seller's connected account to their bank.#- # Nothing is sent here: money that has reached a connected account is paid- # out to the seller's bank by Stripe, on the schedule that account carries.- # The payout stays pending until the `payout.paid` webhook says it landed,- # which is the same shape as the built-in provider — an operator's bank- # transfer and Stripe's are both claims about the outside world.+ # Spree decides when — connected accounts are created on a manual schedule+ # precisely so Stripe is not also paying out on one of its own. Two clocks+ # on one relationship do not compose: honour both and a monthly seller+ # waits up to two months, honour neither and the operator's setting is a+ # decoration.+ #+ # Made as the connected account rather than as the platform, because the+ # money being moved is the seller's own balance. The payout stays pending+ # until `payout.paid` says it reached the bank — a settlement is a claim+ # about the outside world whoever makes it.def pay!(seller_payout)+ seller = seller_payout.seller+ gateway = gateway_for(seller.store)+ account_id = seller.payout_account_reference(self.class)+ raise Spree::Core::GatewayError, 'Seller holds no Stripe account' if account_id.blank?++ payout = Stripe::Payout.create(+ {+ amount: minor_units(seller_payout),+ currency: seller_payout.currency.downcase,+ metadata: { spree_seller_payout_id: seller_payout.id }+ },+ 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+ # matches on Stripe's own id instead of guessing by amount.+ seller_payout.update!(reference: payout.id)seller_payoutend@@ -102,8 +124,8 @@ module SpreeStriperaise(Spree::Core::GatewayError, 'No active Stripe payment method on this store')end- def minor_units(seller_transfer)- Spree::Money::Rounding.to_minor_units(seller_transfer.amount.abs, seller_transfer.currency)+ def minor_units(record)+ Spree::Money::Rounding.to_minor_units(record.amount.abs, record.currency)end# The charge that paid for this order, so Stripe can fund the transfer fromdiff --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 28af1cb670..e85366bef7 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@@ -63,7 +63,7 @@ RSpec.describe SpreeStripe::Gateway::Connect doendcontext 'payout.paid' do- let!(:payout) { create(:seller_payout, seller: seller, currency: 'USD') }+ let!(:payout) { create(:seller_payout, seller: seller, currency: 'USD', reference: 'po_1') }it 'completes the settlement the seller was owed' doallow(Stripe::Webhook).to receive(:construct_event).and_return(@@ -76,21 +76,12 @@ RSpec.describe SpreeStripe::Gateway::Connect doexpect(payout.reference).to eq('po_1')end- # Stripe batches a connected account's balance on its own schedule, so a- # payout of one amount says nothing about a settlement of another.- it 'leaves a settlement of a different amount alone' do+ # Spree created the payout and stored Stripe's id for it, so an event+ # naming an id we hold nothing for is about somebody else's payout —+ # guessing which of ours it meant would complete the wrong one.+ it 'leaves settlements alone when it names an id we do not hold' doallow(Stripe::Webhook).to receive(:construct_event).and_return(- stripe_event('payout.paid', { id: 'po_1', currency: 'usd', amount: 25_000 }, account: 'acct_seller')- )-- gateway.handle_payout_webhook(raw_body, headers)-- expect(payout.reload).to be_pending- end-- it 'leaves a settlement in another currency alone' do- allow(Stripe::Webhook).to receive(:construct_event).and_return(- stripe_event('payout.paid', { id: 'po_1', currency: 'eur', amount: 2_000 }, account: 'acct_seller')+ stripe_event('payout.paid', { id: 'po_elsewhere', currency: 'usd', amount: 2_000 }, account: 'acct_seller'))gateway.handle_payout_webhook(raw_body, headers)@@ -100,7 +91,7 @@ RSpec.describe SpreeStripe::Gateway::Connect doendcontext 'payout.failed' do- let!(:payout) { create(:seller_payout, seller: seller, currency: 'USD') }+ let!(:payout) { create(:seller_payout, seller: seller, currency: 'USD', reference: 'po_1') }before doallow(Stripe::Webhook).to receive(:construct_event).and_return(@@ -131,8 +122,8 @@ RSpec.describe SpreeStripe::Gateway::Connect do# payout id, a second delivery would skip the settlement it already# completed and land on the next one still owed.context 'when payout.paid is delivered twice' do- let!(:first) { create(:seller_payout, seller: seller, currency: 'USD', amount: 40) }- let!(:second) { create(:seller_payout, seller: seller, currency: 'USD', amount: 40) }+ let!(:first) { create(:seller_payout, seller: seller, currency: 'USD', amount: 40, reference: 'po_1') }+ let!(:second) { create(:seller_payout, seller: seller, currency: 'USD', amount: 40, reference: 'po_2') }before doallow(Stripe::Webhook).to receive(:construct_event).and_return(@@ -191,6 +182,72 @@ RSpec.describe SpreeStripe::Gateway::Connect doendend+ describe 'the account a seller is onboarded to' do+ let(:new_seller) { create(:seller, :approved, store: store) }++ before do+ allow(Stripe::AccountLink).to receive(:create).+ and_return(Stripe::StripeObject.construct_from(url: 'https://connect.stripe.com/setup/x'))+ allow(Stripe::Account).to receive(:create).and_return(Stripe::StripeObject.construct_from(id: 'acct_new'))+ store.update!(default_country_code: 'US')+ end++ def onboard(seller = new_seller)+ gateway.create_connect_account_link(seller: seller, refresh_url: 'https://s/r', return_url: 'https://s/d')+ end++ # Spree decides when a seller is settled, so Stripe must not also be paying+ # their balance out on a schedule of its own.+ it 'never pays out on a schedule of its own' do+ expect(Stripe::Account).to receive(:create).+ with(hash_including(settings: { payouts: { schedule: { interval: 'manual' } } }), anything).+ and_return(Stripe::StripeObject.construct_from(id: 'acct_new'))++ onboard+ end++ # Stripe would otherwise assume the platform's country, and a seller ends+ # up with an account no local bank can receive.+ it 'is created where the seller trades' do+ new_seller.update!(billing_address: create(:address, country_code: 'FR', state_code: nil))++ expect(Stripe::Account).to receive(:create).+ with(hash_including(country: 'FR'), anything).+ and_return(Stripe::StripeObject.construct_from(id: 'acct_new'))++ onboard+ end++ it 'falls back to the marketplace’s own country' do+ expect(Stripe::Account).to receive(:create).+ with(hash_including(country: 'US'), anything).+ and_return(Stripe::StripeObject.construct_from(id: 'acct_new'))++ onboard+ end++ # Paying a seller abroad is a different agreement, and without it Stripe+ # refuses to create the account at all.+ it 'accepts the recipient agreement for a seller abroad' do+ new_seller.update!(billing_address: create(:address, country_code: 'FR', state_code: nil))++ expect(Stripe::Account).to receive(:create).+ with(hash_including(tos_acceptance: { service_agreement: 'recipient' }), anything).+ and_return(Stripe::StripeObject.construct_from(id: 'acct_new'))++ onboard+ end++ it 'does not ask for it at home' do+ expect(Stripe::Account).to receive(:create) do |params, _options|+ expect(params).not_to have_key(:tos_acceptance)+ Stripe::StripeObject.construct_from(id: 'acct_new')+ end++ onboard+ end+ end+describe '#connect_webhook_url' doit 'is its own endpoint, separate from the payment one' doexpect(gateway.connect_webhook_url).to end_with("/api/v3/webhooks/payouts/#{gateway.prefixed_id}")diff --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 6db663e9f8..172a817fb9 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@@ -75,17 +75,57 @@ RSpec.describe SpreeStripe::PayoutProvider doenddescribe '#pay!' do- # Money on a connected account is settled by Stripe on that account's own- # schedule, so a payout is confirmed by webhook rather than sent here.- it 'sends nothing and leaves the settlement pending' do- payout = create(:seller_payout, seller: seller)+ let(:payout) { create(:seller_payout, seller: seller, amount: 42.5, currency: 'USD') }- expect(Stripe::Payout).not_to receive(:create)+ before do+ allow(Stripe::Payout).to receive(:create).and_return(Stripe::StripeObject.construct_from(id: 'po_1'))+ end++ it 'sends the settlement to the seller’s bank' do+ expect(Stripe::Payout).to receive(:create).+ with(hash_including(amount: 4250, currency: 'usd'), anything).+ and_return(Stripe::StripeObject.construct_from(id: 'po_1'))++ described_class.new.pay!(payout)+ end++ # The money is the seller's own balance, so the payout is made as them.+ it 'acts as the connected account' do+ expect(Stripe::Payout).to receive(:create).+ with(anything, hash_including(stripe_account: 'acct_seller')).+ and_return(Stripe::StripeObject.construct_from(id: 'po_1'))described_class.new.pay!(payout)+ end++ # Stored now, so the confirming webhook matches on Stripe's own id rather+ # than guessing which settlement it meant.+ it 'keeps Stripe’s id for the settlement' do+ described_class.new.pay!(payout)++ expect(payout.reload.reference).to eq('po_1')+ end++ # A settlement is a claim about the outside world whoever makes it.+ it 'leaves it pending until the bank confirms' do+ described_class.new.pay!(payout)expect(payout.reload).to be_pendingend++ it 'carries an idempotency key, so a retry finds the payout it made' do+ expect(Stripe::Payout).to receive(:create).+ with(anything, hash_including(:idempotency_key)).+ and_return(Stripe::StripeObject.construct_from(id: 'po_1'))++ described_class.new.pay!(payout)+ end++ it 'refuses a seller who holds no Stripe account' do+ other = create(:seller_payout, seller: create(:seller, :approved, store: store))++ expect { described_class.new.pay!(other) }.to raise_error(Spree::Core::GatewayError)+ endenddescribe '.requires_payout_account?' do