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.

Support charge.refunded webhook

Steven Tey93177a0c4a1e
diff --git a/apps/web/app/api/stripe/integration/webhook/charge-refunded.ts b/apps/web/app/api/stripe/integration/webhook/charge-refunded.ts
new file mode 100644
index 0000000000..1658485f80
--- /dev/null
+++ b/apps/web/app/api/stripe/integration/webhook/charge-refunded.ts
@@ -0,0 +1,49 @@
+import { prisma } from "@dub/prisma";
+import type Stripe from "stripe";
+
+// Handle event "charge.refunded"
+export async function chargeRefunded(event: Stripe.Event) {
+ const charge = event.data.object as Stripe.Charge;
+ const stripeAccountId = event.account as string;
+
+ if (!charge.invoice) {
+ return `Charge ${charge.id} has no invoice, skipping...`;
+ }
+
+ const workspace = await prisma.project.findUnique({
+ where: {
+ stripeConnectId: stripeAccountId,
+ },
+ select: {
+ id: true,
+ programs: true,
+ },
+ });
+
+ if (!workspace) {
+ return `Workspace not found for stripe account ${stripeAccountId}`;
+ }
+
+ if (!workspace.programs.length) {
+ return `Workspace ${workspace.id} for stripe account ${stripeAccountId} has no programs, skipping...`;
+ }
+
+ try {
+ const commission = await prisma.commission.update({
+ where: {
+ programId_invoiceId: {
+ programId: workspace.programs[0].id,
+ invoiceId: charge.invoice as string,
+ },
+ },
+ data: {
+ status: "refunded",
+ },
+ });
+
+ return `Commission ${commission.id} updated to status "refunded"`;
+ } catch (error) {
+ console.error(error);
+ return `Error updating commission ${charge.invoice} for workspace ${workspace.id}: ${error}`;
+ }
+}
diff --git a/apps/web/app/api/stripe/integration/webhook/route.ts b/apps/web/app/api/stripe/integration/webhook/route.ts
index 28b7f869ac..1b9476535b 100644
--- a/apps/web/app/api/stripe/integration/webhook/route.ts
+++ b/apps/web/app/api/stripe/integration/webhook/route.ts
@@ -2,6 +2,7 @@ import { stripe } from "@/lib/stripe";
import { withAxiom } from "next-axiom";
import Stripe from "stripe";
import { accountApplicationDeauthorized } from "./account-application-deauthorized";
+import { chargeRefunded } from "./charge-refunded";
import { checkoutSessionCompleted } from "./checkout-session-completed";
import { customerCreated } from "./customer-created";
import { invoicePaid } from "./invoice-paid";
@@ -10,6 +11,7 @@ const relevantEvents = new Set([
"customer.created",
"checkout.session.completed",
"invoice.paid",
+ "charge.refunded",
"account.application.deauthorized",
]);
@@ -59,6 +61,9 @@ export const POST = withAxiom(
case "invoice.paid":
response = await invoicePaid(event);
break;
+ case "charge.refunded":
+ response = await chargeRefunded(event);
+ break;
case "account.application.deauthorized":
response = await accountApplicationDeauthorized(event);
break;