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.

use charge.succeeded webhook

Steven Tey34f8d3ab33a3
diff --git a/apps/web/app/api/cron/invoices/route.ts b/apps/web/app/api/cron/invoices/route.ts
deleted file mode 100644
index ab1f4c255c..0000000000
--- a/apps/web/app/api/cron/invoices/route.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-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";
-
-export const dynamic = "force-dynamic";
-
-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);
-
- const { invoiceId } = schema.parse(body);
-
- await processInvoice({ invoiceId });
-
- return NextResponse.json({ message: `Invoice ${invoiceId} processed.` });
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
-}
diff --git a/apps/web/app/api/cron/invoices/utils.ts b/apps/web/app/api/cron/invoices/utils.ts
index 2c885e906a..b0d7948a23 100644
--- a/apps/web/app/api/cron/invoices/utils.ts
+++ b/apps/web/app/api/cron/invoices/utils.ts
@@ -37,7 +37,6 @@ export const processInvoice = async ({ invoiceId }: { invoiceId: string }) => {
const payouts = await prisma.payout.findMany({
where: {
invoiceId,
- status: "processing",
},
select: {
id: true,
@@ -67,6 +66,7 @@ export const processInvoice = async ({ invoiceId }: { invoiceId: string }) => {
amount: invoice.total,
customer: workspace.stripeId,
payment_method: invoice.paymentMethodId,
+ payment_method_types: ["card", "us_bank_account"],
currency: "usd",
confirmation_method: "automatic",
confirm: true,
diff --git a/apps/web/app/api/stripe/webhook/charge-succeeded.ts b/apps/web/app/api/stripe/webhook/charge-succeeded.ts
new file mode 100644
index 0000000000..c093003b6f
--- /dev/null
+++ b/apps/web/app/api/stripe/webhook/charge-succeeded.ts
@@ -0,0 +1,70 @@
+import { stripe } from "@/lib/stripe";
+import { prisma } from "@dub/prisma";
+import Stripe from "stripe";
+
+export async function chargeSucceeded(event: Stripe.Event) {
+ const charge = event.data.object as Stripe.Charge;
+
+ const { id: chargeId, payment_intent: paymentIntentId } = charge;
+
+ if (typeof paymentIntentId !== "string") {
+ throw new Error("Invalid payment intent ID.");
+ }
+
+ console.log({ chargeId, paymentIntentId });
+
+ const invoice = await prisma.invoice.findUnique({
+ where: {
+ paymentIntentId,
+ },
+ include: {
+ payouts: {
+ include: {
+ partner: true,
+ },
+ },
+ },
+ });
+
+ if (!invoice) {
+ throw new Error(
+ `Invoice with payment intent ${paymentIntentId} not found.`,
+ );
+ }
+
+ console.log("Invoice found", invoice);
+
+ for (const payout of invoice.payouts) {
+ const transfer = await stripe.transfers.create({
+ amount: payout.amount,
+ currency: "usd",
+ destination: payout.partner.stripeConnectId!,
+ source_transaction: chargeId,
+ transfer_group: invoice.id,
+ description: "Dub Partners Payout",
+ });
+
+ console.log("Transfer created", transfer);
+
+ await prisma.$transaction(async (tx) => {
+ await tx.payout.update({
+ where: {
+ id: payout.id,
+ },
+ data: {
+ stripeTransferId: transfer.id,
+ status: "completed",
+ },
+ });
+
+ await tx.sale.updateMany({
+ where: {
+ payoutId: payout.id,
+ },
+ data: {
+ status: "paid",
+ },
+ });
+ });
+ }
+}
diff --git a/apps/web/app/api/stripe/webhook/route.ts b/apps/web/app/api/stripe/webhook/route.ts
index 91f590a554..17e44d2bb0 100644
--- a/apps/web/app/api/stripe/webhook/route.ts
+++ b/apps/web/app/api/stripe/webhook/route.ts
@@ -3,6 +3,7 @@ import { log } from "@dub/utils";
import { NextResponse } from "next/server";
import Stripe from "stripe";
import { accountUpdated } from "./account-updated";
+import { chargeSucceeded } from "./charge-succeeded";
import { checkoutSessionCompleted } from "./checkout-session-completed";
import { customerSubscriptionDeleted } from "./customer-subscription-deleted";
import { customerSubscriptionUpdated } from "./customer-subscription-updated";
@@ -10,6 +11,7 @@ import { invoicePaymentFailed } from "./invoice-payment-failed";
const relevantEvents = new Set([
"account.updated",
+ "charge.succeeded",
"checkout.session.completed",
"customer.subscription.updated",
"customer.subscription.deleted",
@@ -43,6 +45,9 @@ export const POST = async (req: Request) => {
case "account.updated":
await accountUpdated(event);
break;
+ case "charge.succeeded":
+ await chargeSucceeded(event);
+ break;
case "checkout.session.completed":
await checkoutSessionCompleted(event);
break;
diff --git a/apps/web/lib/actions/partners/confirm-payouts.ts b/apps/web/lib/actions/partners/confirm-payouts.ts
index e7f353f781..34e0480277 100644
--- a/apps/web/lib/actions/partners/confirm-payouts.ts
+++ b/apps/web/lib/actions/partners/confirm-payouts.ts
@@ -2,12 +2,9 @@
import { getProgramOrThrow } from "@/lib/api/programs/get-program";
import { createId } from "@/lib/api/utils";
-import { qstash } from "@/lib/cron";
import { MIN_PAYOUT_AMOUNT } from "@/lib/partners/constants";
import { stripe } from "@/lib/stripe";
import { prisma } from "@dub/prisma";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
import Stripe from "stripe";
import z from "zod";
import { authActionClient } from "../safe-action";
@@ -33,6 +30,10 @@ export const confirmPayoutsAction = authActionClient
programId,
});
+ if (!workspace.stripeId) {
+ throw new Error("Workspace does not have a valid Stripe ID.");
+ }
+
// Doing some check to make sure the payment method is valid
const paymentMethod = await stripe.paymentMethods.retrieve(
paymentMethodId,
@@ -45,58 +46,68 @@ export const confirmPayoutsAction = authActionClient
throw new Error("The payment method is not valid for this workspace.");
}
- const result = await prisma.$transaction(async (tx) => {
- // Find the pending payouts for the program
- const payouts = await tx.payout.findMany({
- where: {
- programId,
- status: "pending",
- invoiceId: null, // just to be extra safe
- partner: {
- stripeConnectId: {
- not: null,
- },
- payoutsEnabled: true,
- },
- amount: {
- gte: MIN_PAYOUT_AMOUNT,
+ const payouts = await prisma.payout.findMany({
+ where: {
+ programId,
+ status: "pending",
+ invoiceId: null, // just to be extra safe
+ partner: {
+ stripeConnectId: {
+ not: null,
},
+ payoutsEnabled: true,
},
- select: {
- id: true,
- amount: true,
+ amount: {
+ gte: MIN_PAYOUT_AMOUNT,
},
- });
+ },
+ select: {
+ id: true,
+ amount: true,
+ },
+ });
- if (!payouts.length) {
- throw new Error("No pending payouts found.");
- }
+ if (!payouts.length) {
+ throw new Error("No pending payouts found.");
+ }
- // Create the invoice for the payouts
- const amount = payouts.reduce(
- (total, payout) => total + payout.amount,
- 0,
- );
- const fee = amount * 0.02;
- const total = amount + fee;
+ // Create the invoice for the payouts
+ const amount = payouts.reduce((total, payout) => total + payout.amount, 0);
+ const fee = amount * 0.02;
+ const total = amount + fee;
+
+ const invoice = await prisma.invoice.create({
+ data: {
+ id: createId({ prefix: "inv_" }),
+ programId,
+ paymentMethodId,
+ amount,
+ fee,
+ total,
+ },
+ });
- const invoice = await tx.invoice.create({
- data: {
- id: createId({ prefix: "inv_" }),
- programId,
- paymentMethodId,
- amount,
- fee,
- total,
- },
- });
+ if (!invoice) {
+ throw new Error("Failed to create payout invoice.");
+ }
- if (!invoice) {
- throw new Error("Failed to create payout invoice.");
- }
+ const { id: paymentIntentId } = await stripe.paymentIntents.create({
+ amount: invoice.total,
+ customer: workspace.stripeId,
+ payment_method: invoice.paymentMethodId,
+ payment_method_types: ["card", "us_bank_account"],
+ currency: "usd",
+ confirmation_method: "automatic",
+ confirm: true,
+ transfer_group: invoice.id,
+ statement_descriptor: "Dub Partners",
+ description: "Dub Partners payout invoice",
+ });
+
+ console.log("Payment intent created", paymentIntentId);
- // Update the payouts with the invoice id
- await tx.payout.updateMany({
+ await Promise.all([
+ prisma.payout.updateMany({
where: {
id: {
in: payouts.map((p) => p.id),
@@ -106,22 +117,18 @@ export const confirmPayoutsAction = authActionClient
invoiceId: invoice.id,
status: "processing",
},
- });
-
- return invoice;
- });
-
- // Process the payouts in the background
- waitUntil(
- qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/invoices`,
- body: {
- invoiceId: result.id,
+ }),
+ prisma.invoice.update({
+ where: {
+ id: invoice.id,
+ },
+ data: {
+ paymentIntentId,
},
}),
- );
+ ]);
return {
- invoice: result,
+ invoice,
};
});
diff --git a/packages/prisma/schema/invoice.prisma b/packages/prisma/schema/invoice.prisma
index 3c9dbb7d2b..40bb3db58f 100644
--- a/packages/prisma/schema/invoice.prisma
+++ b/packages/prisma/schema/invoice.prisma
@@ -1,7 +1,8 @@
model Invoice {
id String @id @default(cuid())
programId String
- paymentMethodId String // Stripe payment method ID
+ paymentMethodId String // Stripe payment method ID
+ paymentIntentId String? @unique // Stripe payment intent ID
amount Int @default(0)
fee Int @default(0)
total Int @default(0)