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
Pay sellers through Stripe Connect
Damian Legawiece6365d644c40
diff --git a/spree/providers/stripe/app/jobs/spree_stripe/create_webhook_endpoint_job.rb b/spree/providers/stripe/app/jobs/spree_stripe/create_webhook_endpoint_job.rbindex c222d08015..1a8842e77a 100644--- a/spree/providers/stripe/app/jobs/spree_stripe/create_webhook_endpoint_job.rb+++ b/spree/providers/stripe/app/jobs/spree_stripe/create_webhook_endpoint_job.rb@@ -1,10 +1,16 @@module SpreeStripeclass CreateWebhookEndpointJob < BaseJob- def perform(payment_method_id)+ # @param connect [Boolean] true registers the connected-accounts endpoint,+ # which a marketplace holds alongside its payment one+ def perform(payment_method_id, connect: false)payment_method = Spree::PaymentMethod.find_by(id: payment_method_id)return if payment_method.blank?- payment_method.create_webhook_endpoint+ if connect+ payment_method.create_connect_webhook_endpoint+ else+ payment_method.create_webhook_endpoint+ endendendenddiff --git a/spree/providers/stripe/app/models/spree_stripe/gateway.rb b/spree/providers/stripe/app/models/spree_stripe/gateway.rbindex d69f571898..a7c03e09b7 100644--- a/spree/providers/stripe/app/models/spree_stripe/gateway.rb+++ b/spree/providers/stripe/app/models/spree_stripe/gateway.rb@@ -6,6 +6,7 @@ module SpreeStripeinclude SpreeStripe::Gateway::PaymentSessionsinclude SpreeStripe::Gateway::PaymentSetupSessionsinclude SpreeStripe::Gateway::Webhooks+ include SpreeStripe::Gateway::Connectpreference :publishable_key, :passwordpreference :secret_key, :passworddiff --git a/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rb b/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rbnew file mode 100644index 0000000000..e03d12e94b--- /dev/null+++ b/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rb@@ -0,0 +1,182 @@+module SpreeStripe+ class Gateway < ::Spree::Gateway+ # The marketplace half of the gateway: paying sellers out of the account+ # that charged their customers.+ #+ # This lives on the gateway rather than in settings of its own because it+ # is the same Stripe account either way. A marketplace pays sellers from+ # the money it took, and a transfer signed with a different key than the+ # charge cannot name that charge as its funding source — so a second copy+ # of the credentials could only ever drift out of agreement with the first.+ #+ # It does need a **second webhook endpoint**, though, and that is not a+ # detail. Stripe scopes events by where they originate: the marketplace's+ # own charges on one subscription, everything happening inside a seller's+ # connected account on another, each with its own signing secret. Adding+ # the seller events to the payment endpoint would not widen it — it would+ # switch it over, and the payment webhooks would stop arriving.+ module Connect+ extend ActiveSupport::Concern++ # `account.updated` — onboarding is finished when Stripe says the account+ # can receive transfers, which may be days after the seller stops typing.+ # `payout.*` — Stripe settling a connected account's balance to its bank,+ # which is what completes a payout here.+ CONNECT_EVENTS = %w[+ account.updated+ payout.paid+ payout.failed+ ].freeze++ included do+ preference :connect_webhook_signing_secret, :password+ preference :connect_webhook_endpoint_id, :string++ after_commit :create_connect_webhook_endpoint_async, on: %i[create update]+ end++ # Verifies and acts on one Connect event.+ #+ # @param raw_body [String]+ # @param headers [Hash]+ # @raise [Spree::PaymentMethod::WebhookSignatureError]+ def handle_payout_webhook(raw_body, headers)+ event = verify_connect_webhook_signature(raw_body, headers)++ case event.type+ when 'account.updated' then handle_account_updated(event)+ when 'payout.paid' then handle_payout(event, 'paid')+ when 'payout.failed' then handle_payout(event, 'failed')+ end+ end++ # Gives a seller a Stripe Express account and a link to finish setting it+ # up. Express is the right shape for a marketplace: Stripe collects+ # identity and bank details on its own pages, so the marketplace never+ # handles them and inherits Stripe's checks rather than building its own.+ #+ # The link is minted per call rather than stored — Stripe's onboarding+ # links are single-use and short-lived by design.+ #+ # @param seller [Spree::Seller]+ # @param refresh_url [String] where Stripe sends a seller whose link expired+ # @param return_url [String] where Stripe sends them when they finish+ # @return [String] the onboarding URL+ def create_connect_account_link(seller:, refresh_url:, return_url:)+ seller.update!(payout_account_reference: create_connect_account(seller)) if seller.payout_account_reference.blank?++ Stripe::AccountLink.create(+ {+ account: seller.payout_account_reference,+ refresh_url: refresh_url,+ return_url: return_url,+ type: 'account_onboarding'+ },+ api_options+ ).url+ end++ # @return [Hash] what every Stripe call from this gateway is signed with+ def api_options+ { api_key: preferred_secret_key }+ end++ # Where Stripe sends events originating in sellers' connected accounts.+ # @return [String, nil]+ def connect_webhook_url+ return nil unless store++ "#{store.url_or_custom_domain}/api/v3/webhooks/payouts/#{prefixed_id}"+ end++ def create_connect_webhook_endpoint+ SpreeStripe::CreateGatewayWebhooks.new.call(payment_method: self, connect: true)+ end++ private++ def 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 }+ },+ api_options.merge(idempotency_key: "spree-seller-#{seller.prefixed_id}")+ ).id+ 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.+ def handle_account_updated(event)+ account = event.data.object+ seller = store.sellers.find_by(payout_account_reference: account.id)+ return if seller.nil?++ seller.update!(payouts_enabled_at: account.payouts_enabled ? (seller.payouts_enabled_at || Time.current) : nil)+ end++ # Stripe's payout belongs to a connected account rather than to one of+ # our settlements, so the seller is found by the account the event names+ # and the settlement by being the one still owed in that currency.+ def handle_payout(event, status)+ object = event.data.object+ seller = store.sellers.find_by(payout_account_reference: event.account)+ return if seller.nil?++ payout = seller.seller_payouts.owed.where(currency: object.currency.to_s.upcase).order(:created_at).first+ return if payout.nil?++ if status == 'paid'+ Spree.seller_payout_complete_workflow.call(seller_payout: payout, reference: object.id)+ else+ payout.update!(status: 'failed')+ end+ end++ def verify_connect_webhook_signature(raw_body, headers)+ signature = headers['HTTP_STRIPE_SIGNATURE']++ connect_webhook_signing_secrets.each do |secret|+ return Stripe::Webhook.construct_event(raw_body, signature, secret)+ rescue Stripe::SignatureVerificationError+ next+ rescue JSON::ParserError+ raise Spree::PaymentMethod::WebhookSignatureError, 'Malformed webhook payload'+ end++ raise Spree::PaymentMethod::WebhookSignatureError, 'Invalid webhook signature'+ end++ # Development only, matching the payment endpoint: the Stripe CLI signs+ # forwarded events with its own secret rather than the endpoint's.+ def connect_webhook_signing_secrets+ secrets = [preferred_connect_webhook_signing_secret]+ secrets << ENV['STRIPE_CONNECT_SIGNING_SECRET'] if Rails.env.development?+ secrets.select(&:present?)+ end++ # Only registered once the store actually has sellers: an ordinary+ # merchant account has no connected accounts to hear about, and the+ # endpoint would receive nothing. Also the loop guard, as on the payment+ # endpoint — registration writes the secret back through `update!`.+ def create_connect_webhook_endpoint_async+ return if preferred_connect_webhook_signing_secret.present?+ return unless store&.sellers&.exists?++ SpreeStripe::CreateWebhookEndpointJob.perform_later(id, connect: true)+ end+ end+ end+enddiff --git a/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rbnew file mode 100644index 0000000000..5cf564adeb--- /dev/null+++ b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb@@ -0,0 +1,113 @@+module SpreeStripe+ # Pays sellers through Stripe Connect.+ #+ # The marketplace charges the customer on its own account, then moves each+ # seller's share to their connected account as the goods go out. Two things+ # make that work and are worth naming:+ #+ # **The transfer names the charge that funds it.** Stripe's `source_transaction`+ # ties a transfer to a specific charge, so the money moves as soon as that+ # charge settles rather than waiting for the platform's own balance to cover+ # it — a marketplace should not have to float its sellers.+ #+ # **Settlement is Stripe's own schedule.** Once money is on a connected+ # account, Stripe pays it out to the seller's bank on the schedule configured+ # for that account. So {#pay!} does not send anything: it records what Stripe+ # is going to do, and a webhook confirms when it did.+ #+ # Every call carries an idempotency key derived from the ledger row, so a+ # retry after a timeout finds the movement it already made instead of making+ # a second.+ class PayoutProvider < Spree::PayoutProvider::Base+ def self.display_name+ 'Stripe Connect'+ end++ # A seller must hold a connected account before anything can be sent to+ # them, so core will not credit one who does not.+ def self.requires_payout_account?+ true+ end++ def self.available_for_store?(store)+ gateway_for(store).present?+ end++ # The store's Stripe gateway — the account that charges customers, and so+ # the account that pays sellers.+ #+ # @return [SpreeStripe::Gateway, nil]+ def self.gateway_for(store)+ store.payment_methods.active.find { |method| method.is_a?(SpreeStripe::Gateway) }+ end++ # Moves one seller's earning to their connected account.+ def transfer!(seller_transfer)+ seller = seller_transfer.seller+ gateway = gateway_for(seller.store)++ transfer = Stripe::Transfer.create(+ {+ amount: minor_units(seller_transfer),+ currency: seller_transfer.currency.downcase,+ destination: seller.payout_account_reference,+ # Funds the transfer from the customer's own charge, so it settles+ # with that charge rather than out of the platform's balance.+ source_transaction: source_charge_for(seller_transfer, gateway),+ transfer_group: seller_transfer.order.order_group&.number || seller_transfer.order.number,+ metadata: {+ spree_seller_transfer_id: seller_transfer.id,+ spree_order_number: seller_transfer.order.number+ }+ }.compact,+ gateway.api_options.merge(idempotency_key: idempotency_key(seller_transfer))+ )++ seller_transfer.update!(status: 'completed', reference: transfer.id)+ seller_transfer+ end++ # Records the settlement Stripe will make on its own schedule.+ #+ # 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.+ def pay!(seller_payout)+ seller_payout+ end++ # Pulls a seller's money back after a refund.+ #+ # Ledger-only in open source: the row is written either way, so the books+ # stay correct, but reversing the Stripe transfer — and netting a negative+ # balance against future earnings — is where a marketplace needs the money+ # operations that Enterprise provides.+ def reverse!(seller_transfer)+ seller_transfer.update!(status: 'completed')+ seller_transfer+ end++ private++ def gateway_for(store)+ self.class.gateway_for(store) ||+ raise(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)+ end++ # The charge that paid for this order, so Stripe can fund the transfer from+ # it. Nil when the order was not paid by card — a store-credit sale has no+ # charge to draw on, and Stripe then funds from the platform balance.+ def source_charge_for(seller_transfer, gateway)+ payment = seller_transfer.order.settlement_payments.valid.completed.+ find { |candidate| candidate.payment_method_id == gateway.id }++ payment&.response_code+ end+ end+enddiff --git a/spree/providers/stripe/app/services/spree_stripe/create_gateway_webhooks.rb b/spree/providers/stripe/app/services/spree_stripe/create_gateway_webhooks.rbindex 183e47048a..16d9ab6e23 100644--- a/spree/providers/stripe/app/services/spree_stripe/create_gateway_webhooks.rb+++ b/spree/providers/stripe/app/services/spree_stripe/create_gateway_webhooks.rb@@ -1,11 +1,19 @@module SpreeStripe- # Registers the gateway's webhook endpoint with Stripe and stores the signing- # secret on the payment method.+ # Registers a webhook endpoint with Stripe and stores the signing secret on+ # the payment method.+ #+ # A marketplace registers two: one for its own payment events, one for the+ # events originating inside its sellers' connected accounts. Stripe scopes+ # those separately and signs each with its own secret, so which endpoint is+ # being registered decides the URL, the events, and the preference the secret+ # lands in.class CreateGatewayWebhooks# @param payment_method [SpreeStripe::Gateway]+ # @param connect [Boolean] true registers the connected-accounts endpoint# @return [Stripe::WebhookEndpoint, nil]- def call(payment_method:, events: SpreeStripe::Gateway::Webhooks::SUPPORTED_EVENTS, connect: false)- webhook_url = payment_method.webhook_url+ def call(payment_method:, events: nil, connect: false)+ events ||= connect ? SpreeStripe::Gateway::Connect::CONNECT_EVENTS : SpreeStripe::Gateway::Webhooks::SUPPORTED_EVENTS+ webhook_url = connect ? payment_method.connect_webhook_url : payment_method.webhook_urlreturn if webhook_url.blank?api_options = { api_key: payment_method.preferred_secret_key }@@ -13,8 +21,8 @@ module SpreeStripe# Stripe only returns the signing secret when the endpoint is created, so a# pre-existing endpoint whose secret we do not hold has to be replaced.- if existing.present? && payment_method.preferred_webhook_endpoint_id == existing[:id] &&- payment_method.preferred_webhook_signing_secret.present?+ if existing.present? && stored_endpoint_id(payment_method, connect) == existing[:id] &&+ stored_secret(payment_method, connect).present?return existingend@@ -31,15 +39,28 @@ module SpreeStripeendend+ def stored_endpoint_id(payment_method, connect)+ connect ? payment_method.preferred_connect_webhook_endpoint_id : payment_method.preferred_webhook_endpoint_id+ end++ def stored_secret(payment_method, connect)+ if connect+ payment_method.preferred_connect_webhook_signing_secret+ else+ payment_method.preferred_webhook_signing_secret+ end+ end+def create_webhook_endpoint(payment_method, webhook_url, events, connect, api_options)stripe_webhook = Stripe::WebhookEndpoint.create({ url: webhook_url, enabled_events: events, connect: connect },api_options)+ prefix = connect ? 'preferred_connect_webhook' : 'preferred_webhook'payment_method.update!(- preferred_webhook_endpoint_id: stripe_webhook[:id],- preferred_webhook_signing_secret: stripe_webhook[:secret]+ :"#{prefix}_endpoint_id" => stripe_webhook[:id],+ :"#{prefix}_signing_secret" => stripe_webhook[:secret])stripe_webhookdiff --git a/spree/providers/stripe/lib/spree_stripe/engine.rb b/spree/providers/stripe/lib/spree_stripe/engine.rbindex cd795ff5a2..012614d4eb 100644--- a/spree/providers/stripe/lib/spree_stripe/engine.rb+++ b/spree/providers/stripe/lib/spree_stripe/engine.rb@@ -16,6 +16,7 @@ module SpreeStripeconfig.after_initialize doRails.application.config.spree.payment_methods << SpreeStripe::GatewaySpree.subscribers << SpreeStripe::CustomerUpdatedSubscriber+ Spree.payout_providers << SpreeStripe::PayoutProviderendendenddiff --git a/spree/providers/stripe/spec/models/spree_stripe/gateway/connect_spec.rb b/spree/providers/stripe/spec/models/spree_stripe/gateway/connect_spec.rbnew file mode 100644index 0000000000..cf2417e74a--- /dev/null+++ b/spree/providers/stripe/spec/models/spree_stripe/gateway/connect_spec.rb@@ -0,0 +1,148 @@+require 'spec_helper'++RSpec.describe SpreeStripe::Gateway::Connect do+ let(:store) { @default_store }+ let(:gateway) { create(:stripe_gateway, store: store) }+ let(:seller) { create(:seller, :approved, store: store, payout_account_reference: 'acct_seller') }+ let(:headers) { { 'HTTP_STRIPE_SIGNATURE' => 'sig_test' } }+ let(:raw_body) { '{"id": "evt_test"}' }++ before { gateway.preferences = gateway.preferences.merge(connect_webhook_signing_secret: 'whsec_connect') }++ def stripe_event(type, object, account: nil)+ Stripe::StripeObject.construct_from({ type: type, account: account, data: { object: object } }.compact)+ end++ describe '#handle_payout_webhook' do+ context 'account.updated' do+ it 'lets a seller be paid once Stripe says the account can receive transfers' do+ allow(Stripe::Webhook).to receive(:construct_event).and_return(+ stripe_event('account.updated', { id: 'acct_seller', payouts_enabled: true })+ )++ expect { gateway.handle_payout_webhook(raw_body, headers) }.+ to change { seller.reload.payouts_enabled_at }.from(nil)+ end++ # A seller whose documents expire stops being payable, and the ledger has+ # to stop crediting them rather than promise money nothing can send.+ it 'stops a seller being paid when Stripe withdraws the capability' do+ seller.update!(payouts_enabled_at: 2.days.ago)+ allow(Stripe::Webhook).to receive(:construct_event).and_return(+ stripe_event('account.updated', { id: 'acct_seller', payouts_enabled: false })+ )++ gateway.handle_payout_webhook(raw_body, headers)++ expect(seller.reload.payouts_enabled_at).to be_nil+ end++ it 'leaves an already-payable seller alone rather than restamping them' do+ stamped = 3.days.ago.round+ seller.update!(payouts_enabled_at: stamped)+ allow(Stripe::Webhook).to receive(:construct_event).and_return(+ stripe_event('account.updated', { id: 'acct_seller', payouts_enabled: true })+ )++ gateway.handle_payout_webhook(raw_body, headers)++ expect(seller.reload.payouts_enabled_at).to be_within(1.second).of(stamped)+ end++ it 'ignores an account belonging to no seller here' do+ allow(Stripe::Webhook).to receive(:construct_event).and_return(+ stripe_event('account.updated', { id: 'acct_stranger', payouts_enabled: true })+ )++ expect { gateway.handle_payout_webhook(raw_body, headers) }.not_to raise_error+ end+ end++ context 'payout.paid' do+ let!(:payout) { create(:seller_payout, seller: seller, currency: 'USD') }++ it 'completes the settlement the seller was owed' do+ allow(Stripe::Webhook).to receive(:construct_event).and_return(+ stripe_event('payout.paid', { id: 'po_1', currency: 'usd' }, account: 'acct_seller')+ )++ gateway.handle_payout_webhook(raw_body, headers)++ expect(payout.reload).to be_completed+ expect(payout.reference).to eq('po_1')+ 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' }, account: 'acct_seller')+ )++ gateway.handle_payout_webhook(raw_body, headers)++ expect(payout.reload).to be_pending+ end+ end++ context 'payout.failed' do+ let!(:payout) { create(:seller_payout, seller: seller, currency: 'USD') }++ it 'marks the settlement failed so it is visible rather than silently stuck' do+ allow(Stripe::Webhook).to receive(:construct_event).and_return(+ stripe_event('payout.failed', { id: 'po_1', currency: 'usd' }, account: 'acct_seller')+ )++ gateway.handle_payout_webhook(raw_body, headers)++ expect(payout.reload).to be_failed+ end+ end++ it 'refuses an unsigned report — it could otherwise mark a seller payable' do+ allow(Stripe::Webhook).to receive(:construct_event).+ and_raise(Stripe::SignatureVerificationError.new('bad', 'sig_test'))++ expect { gateway.handle_payout_webhook(raw_body, headers) }.+ to raise_error(Spree::PaymentMethod::WebhookSignatureError)+ end++ # The two endpoints carry different traffic signed with different secrets,+ # so a payment event verified against the payment secret must not verify+ # here.+ it 'verifies against the Connect secret rather than the payment one' do+ expect(Stripe::Webhook).to receive(:construct_event).with(raw_body, 'sig_test', 'whsec_connect').+ and_return(stripe_event('account.updated', { id: 'acct_seller', payouts_enabled: true }))++ gateway.handle_payout_webhook(raw_body, headers)+ end+ end++ describe '#create_connect_account_link' do+ it 'creates an Express account for a seller who has none, then links to onboarding' do+ seller = create(:seller, :approved, store: store, payout_account_reference: nil)+ allow(Stripe::Account).to receive(:create).and_return(Stripe::StripeObject.construct_from(id: 'acct_new'))+ allow(Stripe::AccountLink).to receive(:create).+ and_return(Stripe::StripeObject.construct_from(url: 'https://connect.stripe.com/setup/x'))++ url = gateway.create_connect_account_link(seller: seller, refresh_url: 'https://s/r', return_url: 'https://s/d')++ expect(url).to eq('https://connect.stripe.com/setup/x')+ expect(seller.reload.payout_account_reference).to eq('acct_new')+ end++ it 'reuses the account a seller already holds' do+ allow(Stripe::AccountLink).to receive(:create).+ and_return(Stripe::StripeObject.construct_from(url: 'https://connect.stripe.com/setup/y'))++ expect(Stripe::Account).not_to receive(:create)++ gateway.create_connect_account_link(seller: seller, refresh_url: 'https://s/r', return_url: 'https://s/d')+ end+ end++ describe '#connect_webhook_url' do+ it 'is its own endpoint, separate from the payment one' do+ expect(gateway.connect_webhook_url).to end_with("/api/v3/webhooks/payouts/#{gateway.prefixed_id}")+ expect(gateway.connect_webhook_url).not_to eq(gateway.webhook_url)+ end+ end+enddiff --git a/spree/providers/stripe/spec/models/spree_stripe/payout_provider_spec.rb b/spree/providers/stripe/spec/models/spree_stripe/payout_provider_spec.rbnew file mode 100644index 0000000000..86669db0b4--- /dev/null+++ b/spree/providers/stripe/spec/models/spree_stripe/payout_provider_spec.rb@@ -0,0 +1,104 @@+require 'spec_helper'++RSpec.describe SpreeStripe::PayoutProvider do+ let(:store) { @default_store }+ let!(:gateway) { create(:stripe_gateway, store: store) }+ let(:seller) { create(:seller, :approved, store: store, payout_account_reference: 'acct_seller') }+ let(:order) { create(:order, store: store, seller: seller, total: 100, currency: 'USD') }+ let(:seller_transfer) { create(:seller_transfer, seller: seller, order: order, amount: 42.5, currency: 'USD') }++ before do+ allow(Stripe::Transfer).to receive(:create).and_return(Stripe::StripeObject.construct_from(id: 'tr_1'))+ end++ describe '#transfer!' do+ it 'sends the seller their earning and records what Stripe called it' do+ described_class.new.transfer!(seller_transfer)++ expect(seller_transfer.reload).to be_completed+ expect(seller_transfer.reference).to eq('tr_1')+ end++ it 'sends whole minor units, so a divided charge still adds up' do+ expect(Stripe::Transfer).to receive(:create).+ with(hash_including(amount: 4250, currency: 'usd', destination: 'acct_seller'), anything).+ and_return(Stripe::StripeObject.construct_from(id: 'tr_1'))++ described_class.new.transfer!(seller_transfer)+ end++ # A retry after a timeout must find the movement it already made rather+ # than making a second one.+ it 'carries an idempotency key derived from the ledger row' do+ expect(Stripe::Transfer).to receive(:create).+ with(anything, hash_including(:idempotency_key)).+ and_return(Stripe::StripeObject.construct_from(id: 'tr_1'))++ described_class.new.transfer!(seller_transfer)+ end++ it 'refuses when the store has no Stripe payment method to pay from' do+ gateway.update!(active: false)++ expect { described_class.new.transfer!(seller_transfer) }.to raise_error(Spree::Core::GatewayError)+ end++ context 'when the customer paid by card' do+ # Funds the transfer from that charge, so it settles with the charge+ # rather than out of the marketplace's own balance.+ it 'names the charge as the funding source' do+ create(:payment, order: order, payment_method: gateway, status: 'completed',+ response_code: 'ch_123', amount: 100)++ expect(Stripe::Transfer).to receive(:create).+ with(hash_including(source_transaction: 'ch_123'), anything).+ and_return(Stripe::StripeObject.construct_from(id: 'tr_1'))++ described_class.new.transfer!(seller_transfer)+ end+ end++ context 'when there is no charge to draw on' do+ it 'omits the funding source rather than sending a null one' do+ expect(Stripe::Transfer).to receive(:create) do |payload, _options|+ expect(payload).not_to have_key(:source_transaction)+ Stripe::StripeObject.construct_from(id: 'tr_1')+ end++ described_class.new.transfer!(seller_transfer)+ end+ end+ end++ describe '#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)++ expect(Stripe::Payout).not_to receive(:create)++ described_class.new.pay!(payout)++ expect(payout.reload).to be_pending+ end+ end++ describe '.requires_payout_account?' do+ it 'is true — nothing can be sent to a seller without a connected account' do+ expect(described_class.requires_payout_account?).to be(true)+ end+ end++ describe '.available_for_store?' do+ it 'is false without an active Stripe payment method' do+ gateway.update!(active: false)++ expect(described_class.available_for_store?(store)).to be(false)+ end++ it 'is true when the store charges through Stripe' do+ expect(described_class.available_for_store?(store)).to be(true)+ end+ end+end