The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Delay PayPal, Tremendous, and stablecoin payouts until charge funds settle (#4043)
Kiran K3ec68acc0de8
diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.tsindex cef741ba64..622c09633f 100644--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts@@ -1,31 +1,82 @@+import {+ MIN_WITHDRAWAL_AMOUNT_CENTS,+ STABLECOIN_PAYOUT_FIXED_FEE_CENTS,+} from "@/lib/constants/payouts";import { qstash } from "@/lib/cron";+import { fundFinancialAccount } from "@/lib/stripe/fund-financial-account";import { prisma } from "@dub/prisma";import { Invoice, PartnerPayoutMethod } from "@dub/prisma/client";import { APP_DOMAIN_WITH_NGROK, chunk, log } from "@dub/utils";-import * as z from "zod/v4";--const stripeChargeMetadataSchema = z.object({- id: z.string(), // Stripe charge id-});+import { stripeChargeMetadataSchema } from "./utils";const queue = qstash.queue({queueName: "send-stripe-payout",});-export async function queueStripePayouts(+export async function queueStripePayouts({+ invoice,+ fundsAvailable,+}: {invoice: Pick<Invoice,"id" | "paymentMethod" | "stripeChargeMetadata" | "payoutMode"- >,- skipStablecoinPayouts: boolean,-) {- // All payouts are processed externally, hence no need to queue Stripe payouts+ >;+ fundsAvailable: boolean;+}) {if (invoice.payoutMode === "external") {+ console.log(+ `Invoice ${invoice.id} is paid externally, skipping Stripe payouts...`,+ );return;}const { id: invoiceId, paymentMethod, stripeChargeMetadata } = invoice;+ if (fundsAvailable) {+ // Fund the total Stablecoin payout amount for this invoice+ const { _sum, _count } = await prisma.payout.aggregate({+ _sum: {+ amount: true,+ },+ _count: {+ id: true,+ },+ where: {+ invoiceId: invoice.id,+ method: "stablecoin",+ status: "processing",+ // only transfer funds for stablecoin payouts >= minimum withdrawal amount+ // for payouts below the minimum withdrawal amount, we will just mark them as processed+ // and users can force withdraw them manually later (which triggers another fundFinancialAccount call)+ amount: {+ gte: MIN_WITHDRAWAL_AMOUNT_CENTS,+ },+ },+ });++ // We need to add the STABLECOIN_PAYOUT_FIXED_FEE_CENTS for each payout to the total funding amount+ // to make sure that `createStablecoinPayout` later has enough funds to cover Stripe's fees+ const stablecoinFundingAmount =+ (_sum.amount ?? 0) + _count.id * STABLECOIN_PAYOUT_FIXED_FEE_CENTS;++ // Send money to Financial Account to handle Stablecoin payouts+ if (stablecoinFundingAmount > 0) {+ try {+ await fundFinancialAccount({+ amount: stablecoinFundingAmount,+ idempotencyKey: invoiceId,+ });+ } catch (error) {+ await log({+ message: `Failed to fund Dub's financial account for stablecoin payouts: ${error.message}`,+ type: "errors",+ });++ throw error;+ }+ }+ }+// Find the id of the charge that was used to fund the transferconst parsedChargeMetadata =stripeChargeMetadataSchema.safeParse(stripeChargeMetadata);@@ -53,7 +104,7 @@ export async function queueStripePayouts(method: {in: [PartnerPayoutMethod.connect,- ...(!skipStablecoinPayouts ? [PartnerPayoutMethod.stablecoin] : []),+ ...(fundsAvailable ? [PartnerPayoutMethod.stablecoin] : []),],},partner: {diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-tremendous-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-tremendous-payouts.tsindex 1246026bc2..1690bd59a3 100644--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-tremendous-payouts.ts+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-tremendous-payouts.ts@@ -14,10 +14,23 @@ const queue = qstash.queue({queueName: "send-tremendous-payout",});-export async function queueTremendousPayouts(- invoice: Pick<Invoice, "id" | "paymentMethod" | "payoutMode" | "programId">,-) {- if (invoice.payoutMode === "external" || !invoice.programId) {+export async function queueTremendousPayouts({+ invoice,+}: {+ invoice: Pick<Invoice, "id" | "payoutMode" | "programId">;+}) {+ if (invoice.payoutMode === "external") {+ console.log(+ `Invoice ${invoice.id} is paid externally, skipping Tremendous payouts...`,+ );+ return;+ }++ // should never happen, but just in case+ if (!invoice.programId) {+ console.log(+ `Invoice ${invoice.id} has no program ID, skipping Tremendous payouts...`,+ );return;}diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.tsindex 9018e97c23..b0ba98be12 100644--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts@@ -1,11 +1,7 @@import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import {- MIN_WITHDRAWAL_AMOUNT_CENTS,- STABLECOIN_PAYOUT_FIXED_FEE_CENTS,-} from "@/lib/constants/payouts";import { verifyQstashSignature } from "@/lib/cron/verify-qstash";-import { fundFinancialAccount } from "@/lib/stripe/fund-financial-account";import { prisma } from "@dub/prisma";+import { PartnerPayoutMethod } from "@dub/prisma/client";import { log } from "@dub/utils";import * as z from "zod/v4";import { logAndRespond } from "../../utils";@@ -13,7 +9,7 @@ import { queueExternalPayouts } from "./queue-external-payouts";import { queueStripePayouts } from "./queue-stripe-payouts";import { queueTremendousPayouts } from "./queue-tremendous-payouts";import { sendPaypalPayouts } from "./send-paypal-payouts";-import { scheduleDelayedStablecoinPayouts } from "./utils";+import { getFundSettlementTiming, scheduleDelayedPayouts } from "./utils";export const dynamic = "force-dynamic";export const maxDuration = 600; // This function can run for a maximum of 10 minutes@@ -69,62 +65,61 @@ export async function POST(req: Request) {AND p.status = 'processing'`;- // Fund the total stablecoin payout amount for this invoice- const { _sum, _count } = await prisma.payout.aggregate({- _sum: { amount: true },- _count: { id: true },- where: {- invoiceId: invoice.id,- method: "stablecoin",- // only transfer funds for stablecoin payouts >= minimum withdrawal amount- // for payouts below the minimum withdrawal amount, we will just mark them as processed- // and users can force withdraw them manually later (which triggers another fundFinancialAccount call)- amount: {- gte: MIN_WITHDRAWAL_AMOUNT_CENTS,- },- },- });+ let fundsAvailable = true;++ // if invoice payment method is card, we need to check if the funds have settled yet+ if (invoice.paymentMethod === "card") {+ const fundSettlementTiming = await getFundSettlementTiming(invoice);+ if (!fundSettlementTiming.fundsAvailable) {+ // set fundsAvailable to false so we don't queue any payouts that require funds to be available+ fundsAvailable = false;++ const postSettlementPayoutMethods = [+ PartnerPayoutMethod.stablecoin,+ PartnerPayoutMethod.paypal,+ PartnerPayoutMethod.tremendous,+ ];++ const postSettlementPayoutsCount = await prisma.payout.count({+ where: {+ invoiceId: invoice.id,+ status: "processing",+ method: {+ in: postSettlementPayoutMethods,+ },+ },+ });- let skipStablecoinPayouts = false;- // we need to add the STABLECOIN_PAYOUT_FIXED_FEE_CENTS for each payout to the total funding amount- // to make sure that `createStablecoinPayout` later has enough funds to cover Stripe's fees- const stablecoinFundingAmount =- (_sum.amount ?? 0) + _count.id * STABLECOIN_PAYOUT_FIXED_FEE_CENTS;-- // Send money to Financial Account to handle stablecoin payouts- if (stablecoinFundingAmount > 0) {- const { nextAction } = await scheduleDelayedStablecoinPayouts(invoice);-- if (nextAction === "executeNow") {- try {- await fundFinancialAccount({- amount: stablecoinFundingAmount,- idempotencyKey: invoiceId,- });- } catch (error) {- await log({- message: `Failed to fund Dub's financial account for stablecoin payouts: ${error.message}`,- type: "errors",+ if (postSettlementPayoutsCount > 0) {+ await scheduleDelayedPayouts({+ invoice,+ executeAt: fundSettlementTiming.scheduledAt,});-- skipStablecoinPayouts = true;}}-- if (nextAction === "skip") {- skipStablecoinPayouts = true;- }}await Promise.allSettled([- // Queue Stripe payouts- queueStripePayouts(invoice, skipStablecoinPayouts),- // Send PayPal payouts- sendPaypalPayouts(invoice),- // Queue external payouts+ // Queue Stripe payouts (need to pass along fundsAvailable to handle stablecoin payouts)+ queueStripePayouts({+ invoice,+ fundsAvailable,+ }),++ // only send PayPal and Tremendous payouts if funds are available+ ...(fundsAvailable+ ? [+ sendPaypalPayouts({+ invoice,+ }),+ queueTremendousPayouts({+ invoice,+ }),+ ]+ : []),++ // Queue external payouts (doesn't rely on fundsAvailable)queueExternalPayouts(invoice),- // Queue Tremendous payouts- queueTremendousPayouts(invoice),]);return logAndRespond(diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.tsindex 041749c5ca..e11d0cb240 100644--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts@@ -7,7 +7,18 @@ import { Invoice } from "@dub/prisma/client";import { APP_DOMAIN_WITH_NGROK, currencyFormatter } from "@dub/utils";import { waitUntil } from "@vercel/functions";-export async function sendPaypalPayouts(invoice: Pick<Invoice, "id">) {+export async function sendPaypalPayouts({+ invoice,+}: {+ invoice: Pick<Invoice, "id" | "payoutMode">;+}) {+ if (invoice.payoutMode === "external") {+ console.log(+ `Invoice ${invoice.id} is paid externally, skipping PayPal payouts...`,+ );+ return;+ }+const payouts = await prisma.payout.findMany({where: {invoiceId: invoice.id,diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/utils.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/utils.tsindex 29f4b97972..6a99c2b9b3 100644--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/utils.ts+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/utils.ts@@ -1,67 +1,31 @@import { qstash } from "@/lib/cron";import { stripe } from "@/lib/stripe";+import { Invoice } from "@dub/prisma/client";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import * as z from "zod/v4";-const stripeChargeMetadataSchema = z.object({+type FundSettlementTiming =+ | {+ fundsAvailable: true;+ }+ | {+ fundsAvailable: false;+ scheduledAt: Date;+ };++export const stripeChargeMetadataSchema = z.object({id: z.string(),});-interface StablecoinScheduleResult {- nextAction: "skip" | "executeNow";-}--// For stablecoin payouts, schedule a cron job at `available_on + 15 minutes`-// because Stablecoin financial accounts do not support `source_transaction`,-// so the payout must be triggered after funds become available.-export async function scheduleDelayedStablecoinPayouts(invoice: {- id: string;- stripeChargeMetadata: unknown;-}): Promise<StablecoinScheduleResult> {- const stripeChargeMetadata = stripeChargeMetadataSchema.parse(- invoice.stripeChargeMetadata,- );-- const balanceTransactions = await stripe.balanceTransactions.list({- source: stripeChargeMetadata.id,- });-- const now = Date.now();- let scheduleTimeMs = 0;-- // Balance transaction is not available- if (balanceTransactions.data.length === 0) {- console.log(- `No balance transaction found for charge ${stripeChargeMetadata.id}`,- );-- scheduleTimeMs = now + 1 * 60 * 60 * 1000;- }-- // Balance transaction is available- else {- const balanceTransaction = balanceTransactions.data[0];-- console.log(- `Found balance transaction for charge invoice ${invoice.id}: ${balanceTransaction.id}`,- {- available_on: balanceTransaction.available_on,- },- );-- const availableOnMs = balanceTransaction.available_on * 1000;-- // Funds already available, execute immediately- if (availableOnMs <= now) {- return {- nextAction: "executeNow",- };- }+export async function scheduleDelayedPayouts({+ invoice,+ executeAt,+}: {+ invoice: Pick<Invoice, "id">;+ executeAt: Date;+}) {+ const scheduleTimeMs = executeAt.getTime();- scheduleTimeMs = availableOnMs + 15 * 60 * 1000;- }-- // Schedule the QStash jobconst delaySeconds = Math.max(0,Math.floor((scheduleTimeMs - Date.now()) / 1000),@@ -70,6 +34,7 @@ export async function scheduleDelayedStablecoinPayouts(invoice: {const qstashResponse = await qstash.publishJSON({url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/charge-succeeded`,delay: delaySeconds,+ deduplicationId: `retry-delayed-payouts-${invoice.id}`, // The deduplication window is 10 minutesflowControl: {key: invoice.id,rate: 1,@@ -83,18 +48,69 @@ export async function scheduleDelayedStablecoinPayouts(invoice: {const scheduledAt = new Date(scheduleTimeMs);console.log(- `Scheduled delayed stablecoin payout for invoice ${invoice.id} at ${scheduledAt.toISOString()}.`,+ `Scheduled delayed payouts for invoice ${invoice.id} at ${scheduledAt.toISOString()}.`,{qstashResponse,},);} else {throw new Error(- `Failed to schedule delayed stablecoin payout for invoice ${invoice.id}`,+ `Failed to schedule delayed payouts for invoice ${invoice.id}`,+ );+ }+}++// For payouts that move funds out of Dub's balance directly (stablecoin, PayPal, Tremendous),+// schedule a cron job at `available_on + 15 minutes`. These payout methods do not support+// `source_transaction`, so they must be triggered only after the funding charge's funds settle —+// otherwise we'd be fronting money on a card charge that can still be reversed before it posts.+export async function getFundSettlementTiming(invoice: {+ id: string;+ stripeChargeMetadata: unknown;+}): Promise<FundSettlementTiming> {+ const stripeChargeMetadata = stripeChargeMetadataSchema.parse(+ invoice.stripeChargeMetadata,+ );++ const chargeId = stripeChargeMetadata.id;++ const balanceTransactions = await stripe.balanceTransactions.list({+ source: chargeId,+ });++ const now = Date.now();++ if (balanceTransactions.data.length === 0) {+ console.log(+ `No balance transaction found for charge ${chargeId}, retrying in 1 hour...`,);++ return {+ fundsAvailable: false,+ scheduledAt: new Date(now + 60 * 60 * 1000), // 1 hour from now+ };}+ const balanceTransaction = balanceTransactions.data[0];+ const availableOnMs = balanceTransaction.available_on * 1000;++ if (availableOnMs <= now) {+ console.log(`Funds are available for charge ${chargeId}`);++ return {+ fundsAvailable: true,+ };+ }++ // schedule the qstash job 15 minutes after the funds will be available (to give some buffer)+ const scheduledAt = new Date(availableOnMs + 15 * 60 * 1000);++ console.log(+ `Funds are not available for charge ${chargeId}, scheduling payout for ${scheduledAt.toISOString()}`,+ );+return {- nextAction: "skip",+ fundsAvailable: false,+ scheduledAt,};}diff --git a/apps/web/lib/partners/create-stripe-transfer.ts b/apps/web/lib/partners/create-stripe-transfer.tsindex 6eb411dd2e..c8215447ff 100644--- a/apps/web/lib/partners/create-stripe-transfer.ts+++ b/apps/web/lib/partners/create-stripe-transfer.ts@@ -77,6 +77,7 @@ export const createStripeTransfer = async ({},include: commonInclude,}),+invoiceId? prisma.payout.findMany({where: {