Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Separate Charges and Transfers

Kiran K194e00c57e55
diff --git a/apps/web/app/api/cron/invoices/route.ts b/apps/web/app/api/cron/invoices/route.ts
index f53dc0dd9c..a11116759b 100644
--- a/apps/web/app/api/cron/invoices/route.ts
+++ b/apps/web/app/api/cron/invoices/route.ts
@@ -1,5 +1,4 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { NextResponse } from "next/server";
import { z } from "zod";
import { processInvoice } from "./utils";
@@ -10,10 +9,11 @@ const schema = z.object({
invoiceId: z.string(),
});
+// POST /api/cron/invoices
export async function POST(req: Request) {
try {
const body = await req.json();
- await verifyQstashSignature(req, body);
+ // await verifyQstashSignature(req, body);
const { invoiceId } = schema.parse(body);
diff --git a/apps/web/app/api/cron/invoices/utils.ts b/apps/web/app/api/cron/invoices/utils.ts
index 6318c9fd6e..e138b11c85 100644
--- a/apps/web/app/api/cron/invoices/utils.ts
+++ b/apps/web/app/api/cron/invoices/utils.ts
@@ -1,10 +1,28 @@
+import { stripe } from "@/lib/stripe";
import { prisma } from "@dub/prisma";
+// TODO:
+// Check current invoiceId is processing (Maybe store it in Redis)
+// Deduct the app fee from the invoice amount
+// Should we combine the multiple payouts for same partner?
+// Store the reason of failure in the payout table itself (internal purpose)?
+// We probably need to keep a status column
+
export const processInvoice = async ({ invoiceId }: { invoiceId: string }) => {
const invoice = await prisma.invoice.findUnique({
where: {
id: invoiceId,
},
+ select: {
+ id: true,
+ paymentMethodId: true,
+ total: true,
+ program: {
+ select: {
+ workspaceId: true,
+ },
+ },
+ },
});
if (!invoice) {
@@ -16,23 +34,82 @@ export const processInvoice = async ({ invoiceId }: { invoiceId: string }) => {
invoiceId,
status: "pending",
},
+ select: {
+ id: true,
+ amount: true,
+ partner: {
+ select: {
+ id: true,
+ email: true,
+ stripeConnectId: true,
+ },
+ },
+ },
});
if (payouts.length === 0) {
throw new Error(`No payouts found for invoice ${invoiceId}.`);
}
- // const result = await stripe.paymentIntents.create({
- // amount: payout.amount,
- // currency: payout.currency,
- // description: "Payout for affiliate from Dub Partners",
- // customer: partner.stripeCustomerId, // Partner's Stripe Customer ID
- // payment_method: "pm_1QV6ZKFacAXKeDpJQJa2tLc8", // Partner's Stripe Payment Method ID
- // confirm: true,
- // confirmation_method: "automatic",
- // transfer_data: {
- // destination: affiliate.connectedAccountId, // To where the payout is sent
- // },
- // application_fee_amount: 100, // 1% fee from Dub
- // });
+ const workspace = await prisma.project.findUniqueOrThrow({
+ where: {
+ id: invoice.program.workspaceId,
+ },
+ select: {
+ id: true,
+ stripeId: true,
+ },
+ });
+
+ if (!workspace.stripeId) {
+ throw new Error(`Workspace ${workspace.id} does not have a Stripe ID.`);
+ }
+
+ try {
+ const { latest_charge } = await stripe.paymentIntents.create({
+ amount: invoice.total,
+ customer: workspace.stripeId,
+ payment_method: invoice.paymentMethodId,
+ currency: "usd",
+ confirmation_method: "automatic",
+ confirm: true,
+ transfer_group: invoiceId,
+ statement_descriptor: "Dub Partners",
+ description: "Payout from Dub Partners",
+ });
+
+ // Create transfers for each partners
+ // TODO (Kiran): Need to optimize this when we have large number of payouts for an invoice.
+ for (const payout of payouts) {
+ if (!payout.partner.stripeConnectId) {
+ console.warn(
+ `Partner ${payout.partner.id} does not have a Stripe Connect ID. Skipping payout...`,
+ );
+ continue;
+ }
+
+ const transfer = await stripe.transfers.create({
+ amount: payout.amount,
+ currency: "usd",
+ destination: payout.partner.stripeConnectId,
+ source_transaction: latest_charge as string,
+ transfer_group: invoiceId,
+ description: "Stripe Payout",
+ });
+
+ await prisma.payout.update({
+ where: {
+ id: payout.id,
+ },
+ data: {
+ stripeTransferId: transfer.id,
+ status: "completed",
+ },
+ });
+ }
+ } catch (error) {
+ throw new Error(
+ `[Stripe Connect] Failed to create payment intent for invoice ${invoiceId}: ${error.message}`,
+ );
+ }
};
diff --git a/apps/web/lib/actions/partners/confirm-payouts.ts b/apps/web/lib/actions/partners/confirm-payouts.ts
index c954e89aad..d606be78da 100644
--- a/apps/web/lib/actions/partners/confirm-payouts.ts
+++ b/apps/web/lib/actions/partners/confirm-payouts.ts
@@ -60,7 +60,7 @@ export const confirmPayoutsAction = authActionClient
data: {
id: createId({ prefix: "inv_" }),
programId,
- paymentMethodId: "xxx",
+ paymentMethodId: "pm_1QVOigAlJJEpqkPV6Y3Jc1hs", // TODO: Fix this
amount,
fee,
total,
@@ -89,7 +89,7 @@ export const confirmPayoutsAction = authActionClient
// Process the payouts in the background
waitUntil(
qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/process-payouts`,
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/invoices`,
body: {
invoiceId: result.id,
},
diff --git a/apps/web/ui/partners/payout-invoice-sheet.tsx b/apps/web/ui/partners/payout-invoice-sheet.tsx
index 2b780867c9..fce7b0acdc 100644
--- a/apps/web/ui/partners/payout-invoice-sheet.tsx
+++ b/apps/web/ui/partners/payout-invoice-sheet.tsx
@@ -23,7 +23,6 @@ interface PayoutInvoiceSheetProps {
}
// TODO:
-// Handle case when there are 2 payouts for the same partner
// Fix the fee calculation
// Fix the table menus + View all
diff --git a/packages/prisma/schema/payout.prisma b/packages/prisma/schema/payout.prisma
index ea8b89b493..9cc2cc975b 100644
--- a/packages/prisma/schema/payout.prisma
+++ b/packages/prisma/schema/payout.prisma
@@ -1,6 +1,7 @@
enum PayoutStatus {
pending
completed
+ // processing
failed
}
@@ -12,23 +13,24 @@ enum PayoutType {
}
model Payout {
- id String @id @default(cuid())
- programId String
- partnerId String
- invoiceId String?
- amount Int @default(0)
- fee Int @default(0) // TODO: Remove this
- total Int @default(0) // TODO: Remove this
- currency String @default("USD")
- status PayoutStatus @default(pending)
- type PayoutType @default(sales)
- description String?
- periodStart DateTime?
- periodEnd DateTime?
- quantity Int? // Number of clicks/leads/sales in this payout
- dotsTransferId String? @unique
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ id String @id @default(cuid())
+ programId String
+ partnerId String
+ invoiceId String?
+ amount Int @default(0)
+ fee Int @default(0) // TODO: Remove this
+ total Int @default(0) // TODO: Remove this
+ currency String @default("USD")
+ status PayoutStatus @default(pending)
+ type PayoutType @default(sales)
+ description String?
+ periodStart DateTime?
+ periodEnd DateTime?
+ quantity Int? // Number of clicks/leads/sales in this payout
+ dotsTransferId String? @unique
+ stripeTransferId String? @unique
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
program Program @relation(fields: [programId], references: [id])
partner Partner @relation(fields: [partnerId], references: [id])