TL;DR: Marketplaces that collect money from buyers and pay sellers should let a licensed payment provider move the funds instead of routing them through the company bank account. This guide uses Stripe Connect's Separate Charges and Transfers to charge the buyer on the platform, keep the funds in the platform's Stripe balance until fulfilment, then transfer each seller's share. Stripe is explicit that it does not offer legal escrow, so the pattern here is delayed transfer, not escrow in the legal sense. The Node.js code models each transaction as a state machine in Prisma, driven by verified webhooks.
Key Takeaways
- Keep buyer funds out of your corporate bank account and let Stripe hold them in your platform balance. Stripe does not provide escrow services, and whether your model needs money transmitter licensing is a legal question for your counsel, not an architecture decision.
- Implement Stripe's "Separate Charges and Transfers" flow to safely handle delayed fulfillment, multi-vendor shopping carts, and partial refunds.
- Model payments as a state machine in your database (e.g.,
AUTHORIZED,CAPTURED,PARTIALLY_TRANSFERRED) using verified Stripe webhooks as the source of truth rather than optimistic UI updates. - Store all currency amounts as integers (cents) in your Prisma schema to prevent floating-point rounding errors that cause failed Stripe API calls and accounting discrepancies.
- Create connected accounts with controller properties that match Express behaviour (Stripe collects requirements, sellers get the Express Dashboard). Stripe now recommends controller properties over the legacy
typeparameter for new platforms. - Pass the charge ID as
source_transactionon every transfer so it does not fail while the charge's funds are still pending.
You've built the core features of your multi-sided marketplace. Buyers can browse, sellers can list, and matches are made. But then you hit the hardest part of any marketplace business: moving the money.
In a naive implementation, a buyer pays the platform, the platform holds the funds in a corporate bank account, and later manually wires the platform's cut to itself and the remainder to the seller. This architecture is hard to operate and can carry regulatory risk: in the United States, holding and transmitting funds on behalf of third parties can fall under state money transmitter laws and FinCEN's Money Services Business rules, and other regions have their own payment institution regimes. The exact answer depends on your business model and jurisdiction, so treat it as a question for legal counsel.
Even if you dodge regulatory scrutiny, poor payment architectures inevitably lead to fragile systems. When you introduce delayed fulfillment, multi-vendor shopping carts, partial refunds, chargebacks, and continuous seller KYC requirements, simple point-to-point transfers fail. Your database state drifts from the payment gateway's actual state. Sellers report missing payouts, and your finance team ends up covering refunds that cannot be recovered.
The solution requires abandoning simple linear payment flows. Instead, you must build an idempotent, event-driven architecture using Stripe Connect, managed by a strict backend state machine. By using Separate Charges and Transfers, treating verified webhooks as the source of truth, and making every Stripe call idempotent in Node.js, you keep money movement inside Stripe and keep your database consistent with it.
Let’s architect a production-grade marketplace payment engine.
The Architecture of Multi-Sided Money Movement
Funds should never pass through your company bank account. The flow is: Buyer → platform's Stripe balance → transfer to the seller's connected account, with the platform keeping the difference as its fee. Stripe's own documentation notes that escrow has a precise legal definition and that Stripe does not provide escrow services, so describe this to customers as delayed payouts rather than escrow.
To track this safely, your application database must model a payment not as a single action, but as a lifecycle. A Transaction acts as a state machine that transitions based only on confirmed webhook events from Stripe, never on optimistic UI interactions.
Here is a Prisma schema designed to safely track complex multi-party splits:
// schema.prisma
enum TransactionState {
PENDING
REQUIRES_ACTION
AUTHORIZED
CAPTURED
PARTIALLY_TRANSFERRED
TRANSFERRED
REFUNDED
DISPUTED
}
model Transaction {
id String @id @default(uuid())
buyerId String
buyer User @relation("Buyer", fields: [buyerId], references: [id])
totalAmount Int // In cents
currency String @default("usd")
state TransactionState @default(PENDING)
// Stripe Identifiers
stripePaymentIntentId String? @unique
stripeChargeId String? @unique
transferGroup String @unique // Crucial for tying charges to multiple transfers
// Relations
payouts Payout[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Payout {
id String @id @default(uuid())
transactionId String
transaction Transaction @relation(fields: [transactionId], references: [id])
sellerId String
seller User @relation("Seller", fields: [sellerId], references: [id])
amount Int // Seller's cut in cents
platformFee Int // Platform's cut in cents
stripeTransferId String? @unique
stripeReversalId String? @unique
isProcessed Boolean @default(false)
createdAt DateTime @default(now())
}
Production Note: Always store currency amounts as integers (cents/smallest currency unit). Using floating-point arithmetic for financial ledgers inevitably introduces fractional rounding errors over time, leading to failed Stripe API calls and reconciliation problems.
Onboarding and Compliance: Delegating KYC to Stripe
Before a seller can receive a single cent, they must be KYC (Know Your Customer) verified. Stripe handles verification, but you decide who collects requirements, who pays Stripe fees and who is liable for negative balances. Older integrations expressed this as an account type of Standard, Express or Custom. Stripe now recommends setting controller properties instead, and documents which combination reproduces each legacy type.
For most marketplaces, Express-like behaviour is a good default: Stripe hosts the onboarding and identity verification UI and sellers get the lightweight Express Dashboard, while the platform controls charge types and payout timing. Custom-like accounts give you full UX control but make your team responsible for collecting and updating every requirement. Because this design uses separate charges and transfers, the platform must also own negative balances (losses.payments: 'application'), which matches Stripe's recommendation to use that charge type only when the platform is responsible for connected account losses.
Here is the TypeScript service to create such an account and generate an onboarding link:
// services/stripe/onboarding.ts
import Stripe from 'stripe';
// stripe-node pins the API version it was released with; upgrade the SDK and
// the API version together and test webhooks after each upgrade.
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function createSellerAccount(userEmail: string, userId: string) {
// 1. Create the connected account with Express-equivalent controller properties
const account = await stripe.accounts.create({
controller: {
stripe_dashboard: { type: 'express' },
fees: { payer: 'application' },
losses: { payments: 'application' },
requirement_collection: 'stripe',
},
email: userEmail,
capabilities: {
card_payments: { requested: true },
transfers: { requested: true },
},
business_type: 'individual',
metadata: {
internalUserId: userId,
},
});
// 2. Generate an Account Link for onboarding
const accountLink = await stripe.accountLinks.create({
account: account.id,
refresh_url: `${process.env.APP_URL}/api/stripe/onboarding/refresh?accountId=${account.id}`,
return_url: `${process.env.APP_URL}/dashboard/seller/success`,
type: 'account_onboarding',
});
return {
accountId: account.id,
onboardingUrl: accountLink.url,
};
}
Your database must store the resulting account.id against the seller's user profile. Until the seller completes onboarding (tracked via the account.updated webhook, checking that details_submitted is true and that the transfers capability is active), all payouts to them must remain queued.
Holding Funds: Separate Charges and Transfers
Most marketplaces require holding funds until a specific condition is met-a product is shipped, a gig is finished, or a rental period ends.
Instead of using Destination Charges (which rigidly couple the buyer charge to a single seller payout instantly), we use Separate Charges and Transfers. This decouples inbound money movement from outbound money movement. You charge the buyer, let the funds sit in your platform's Stripe balance, and then trigger a transfer to the seller only when business logic permits.
Here is how you create the platform charge via a PaymentIntent:
// services/stripe/checkout.ts
import Stripe from 'stripe';
import { prisma } from '../db';
import { v4 as uuidv4 } from 'uuid';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function createEscrowCharge(buyerId: string, cartTotalCents: number) {
// 1. Generate a unique Transfer Group ID
const transferGroup = `GROUP_${uuidv4()}`;
// 2. Create the Database Transaction Record (State: PENDING)
const transaction = await prisma.transaction.create({
data: {
buyerId,
totalAmount: cartTotalCents,
transferGroup,
state: 'PENDING',
},
});
// 3. Create the PaymentIntent
const paymentIntent = await stripe.paymentIntents.create({
amount: cartTotalCents,
currency: 'usd',
transfer_group: transferGroup,
// We do not specify application_fee_amount here!
// The platform fee is realized by transferring *less* to the seller later.
metadata: {
transactionId: transaction.id,
},
});
// 4. Update the DB with Stripe's Intent ID
await prisma.transaction.update({
where: { id: transaction.id },
data: { stripePaymentIntentId: paymentIntent.id },
});
return paymentIntent.client_secret;
}
Warning: Holding funds is not open-ended. Check Stripe's current rules for your platform's country before designing long holds: for example, when a connected account uses manual payouts, Stripe requires funds to be paid out within a country-specific window (90 days in most countries, two years in the United States at the time of writing). If your marketplace takes bookings far in advance, consider charging closer to the event instead of holding funds for months.
If you would rather have a team review the full charge, transfer and dispute lifecycle before launch, our API integration and payment gateway services cover exactly this kind of Stripe Connect integration.
Managing Split Payouts and Platform Fees
Once the trigger condition is met (e.g., the buyer marks the item as "Delivered"), the platform executes the payout. The transfer_group only labels related objects for reconciliation. What actually ties the transfer to the buyer's money is source_transaction: with the charge ID set, the transfer request succeeds even if the charge has not settled yet, and the seller receives the funds when the charge's funds become available in the platform balance. Without it, a transfer that exceeds your available balance fails.
With Separate Charges and Transfers, the platform fee isn't explicitly defined in an API parameter. Instead, the platform fee is simply the remainder left in your platform balance after you transfer the seller's cut.
// services/stripe/payouts.ts
import Stripe from 'stripe';
import { prisma } from '../db';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function executeMarketplacePayout(payoutId: string) {
const payout = await prisma.payout.findUnique({
where: { id: payoutId },
include: {
transaction: true,
seller: true,
},
});
if (!payout || payout.isProcessed) {
throw new Error('Invalid or already processed payout');
}
// Execute the transfer using an Idempotency Key to prevent double-payouts
const transfer = await stripe.transfers.create(
{
amount: payout.amount,
currency: 'usd',
destination: payout.seller.stripeAccountId,
transfer_group: payout.transaction.transferGroup,
// Ties the transfer to the buyer's charge so it waits for those funds
source_transaction: payout.transaction.stripeChargeId!,
metadata: {
payoutId: payout.id,
},
},
{
idempotencyKey: `payout_exec_${payout.id}`,
},
);
// Update State
await prisma.payout.update({
where: { id: payout.id },
data: {
isProcessed: true,
stripeTransferId: transfer.id,
},
});
return transfer;
}
Notice the use of idempotencyKey. Network requests fail. If Node.js crashes right after Stripe successfully processes the transfer but before Prisma updates the database, a background cron job might run this function again. Stripe returns the original result for a repeated request with the same idempotency key, so the retry does not pay the seller twice. Stripe keeps idempotency keys for at least 24 hours, so a retry job must also check your own stripeTransferId column or list transfers by transfer_group before creating a new key for an old payout.
Webhooks and Idempotency: The Source of Truth
Never trust the frontend. If a user closes their browser during a 3D Secure redirect, the frontend will never send the success signal to your server, but Stripe will still process the money.
Your webhook handler must be the single source of truth for updating the TransactionState in your database. Here is a Next.js (Pages Router) example that safely processes these events:
// pages/api/webhooks/stripe.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { buffer } from 'micro';
import Stripe from 'stripe';
import { prisma } from '../../../db';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET!;
// Disable Next.js body parsing to access the raw buffer for signature validation
export const config = { api: { bodyParser: false } };
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).end('Method Not Allowed');
}
const reqBuffer = await buffer(req);
const signature = req.headers['stripe-signature'] as string;
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(reqBuffer, signature, endpointSecret);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : 'Unknown error';
return res.status(400).send(`Webhook Error: ${message}`);
}
// Handle the event idempotently
try {
switch (event.type) {
case 'payment_intent.succeeded': {
const paymentIntent = event.data.object as Stripe.PaymentIntent;
await prisma.transaction.updateMany({
where: {
stripePaymentIntentId: paymentIntent.id,
state: { notIn: ['CAPTURED', 'TRANSFERRED'] }, // Idempotency check
},
data: {
state: 'CAPTURED',
// Needed later as source_transaction and for dispute lookups
stripeChargeId: paymentIntent.latest_charge as string,
},
});
break;
}
case 'transfer.created': {
const transfer = event.data.object as Stripe.Transfer;
await prisma.payout.updateMany({
where: {
stripeTransferId: transfer.id,
isProcessed: false,
},
data: { isProcessed: true },
});
break;
}
default:
console.log(`Unhandled event type ${event.type}`);
}
} catch (error) {
console.error('Database update failed:', error);
// Return 500 so Stripe explicitly retries the webhook later
return res.status(500).send('Database Error');
}
res.status(200).json({ received: true });
}
Production Note: Stripe can deliver the same event more than once and does not guarantee ordering. Because
updateManyincludes the state check (state: { notIn: ['CAPTURED', 'TRANSFERRED'] }) in itsWHEREclause, a duplicatepayment_intent.succeededdelivery matches zero rows instead of rewriting the transaction. For handlers with side effects beyond a single update, record processedevent.idvalues in a table with a unique constraint.
Handling the Dark Side: Chargebacks, Refunds, and Reversals
In a multi-sided marketplace using Separate Charges and Transfers, the platform is ultimately liable for disputes. If a buyer files a chargeback, Stripe debits the disputed amount (plus a dispute fee) from your platform balance, not the seller's. Refunds behave the same way: refunding a charge has no effect on the transfers you already made.
You must build automated defenses. If a dispute arrives, immediately halt any pending payouts to that seller. If the payout has already occurred, you must create a TransferReversal to pull the funds back from the connected seller account to your platform balance to cover your loss.
// snippet from within the webhook switch statement
case 'charge.dispute.created': {
const dispute = event.data.object as Stripe.Dispute;
const chargeId = dispute.charge as string;
// 1. Find the transaction
const disputedTx = await prisma.transaction.findUnique({
where: { stripeChargeId: chargeId },
include: { payouts: true }
});
if (!disputedTx) break;
// 2. Mark Transaction as Disputed
await prisma.transaction.update({
where: { id: disputedTx.id },
data: { state: 'DISPUTED' }
});
// 3. Attempt to reverse the transfer from the seller
for (const payout of disputedTx.payouts) {
if (payout.isProcessed && payout.stripeTransferId) {
try {
const reversal = await stripe.transfers.createReversal(
payout.stripeTransferId,
{
description: `Reversal due to chargeback: ${dispute.id}`,
},
{ idempotencyKey: `reversal_${dispute.id}_${payout.id}` }
);
await prisma.payout.update({
where: { id: payout.id },
data: { stripeReversalId: reversal.id }
});
} catch (err: unknown) {
// A reversal only succeeds if the seller's available balance covers it
// (or connected reserves are enabled). Otherwise record the amount owed
// and deduct it from that seller's future transfers.
const msg = err instanceof Error ? err.message : 'Unknown error';
console.error(`Reversal failed for payout ${payout.id}:`, msg);
}
}
}
break;
}
Without automated transfer reversals, the platform absorbs every chargeback by default. Stripe only allows a reversal when the connected account's available balance covers it, so a seller who has already been paid out may have nothing left to reverse. Keep an internal ledger of amounts owed by each seller and net them against future transfers, and consider holding transfers for part of your dispute window for high-risk categories.
Architecting a compliant, failure-resistant payment engine requires more than just calling the Stripe API. It requires treating money movement as a distributed systems problem where network partitions, race conditions, and hostile actors are expected norms.
Sources
- Stripe Docs: Create separate charges and transfers (
transfer_group,source_transaction, refunds and transfer reversals) - Stripe Docs: Migrate to controller properties (controller values that reproduce Express, Custom and Standard behaviour)
- Stripe Docs: Connected account types (legacy account types and Stripe's recommendation)
- Stripe Docs: Manual payouts (holding periods and Stripe's note on escrow)
- stripe-node on npm
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
How does escrow work with Stripe Connect?
Stripe does not offer escrow in the legal sense, but separate charges and transfers give a similar delayed-payout flow: the buyer is charged on the platform account, the funds stay in the platform balance while the order is fulfilled, and the platform creates a transfer to the seller's connected account when release conditions are met. The platform controls when money moves instead of paying sellers at checkout.
Who is responsible for seller KYC on a marketplace?
Stripe Connect handles identity verification for connected accounts, but the platform decides which account type to use and must not pay out until the account is verified. Accounts where the platform owns losses (Express-like or Custom-like controller settings) put more responsibility on the platform than Standard-like accounts, and Custom-like accounts also make the platform collect verification requirements.
How do you take a platform fee from each order?
With separate charges and transfers, the platform simply transfers less than it charged and keeps the difference. With destination charges, you set an application fee on the charge. Record the fee per order in your own ledger so payouts and reporting reconcile.
What happens to a seller payout when the buyer files a chargeback?
The disputed amount is debited from the platform balance, not automatically from the seller. Hold funds long enough to cover your dispute window, and use transfer reversals to recover money from the seller when a refund or chargeback happens after the transfer.
