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.

Refactor Stripe integration to use StripeMode for environment handling. Updated webhook functions and utility methods to accept mode parameter, ensuring consistent behavior across test, sandbox, and live environments.

Kiran Ke94becb659db
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/charge-refunded.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/charge-refunded.ts
index 242c6ee316..44c6ed67b0 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/charge-refunded.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/charge-refunded.ts
@@ -1,15 +1,16 @@
import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
import { stripeAppClient } from "@/lib/stripe";
+import { StripeMode } from "@/lib/types";
import { prisma } from "@dub/prisma";
import type Stripe from "stripe";
// Handle event "charge.refunded"
-export async function chargeRefunded(event: Stripe.Event) {
+export async function chargeRefunded(event: Stripe.Event, mode: StripeMode) {
const charge = event.data.object as Stripe.Charge;
const stripeAccountId = event.account as string;
const stripe = stripeAppClient({
- livemode: event.livemode,
+ mode,
});
// Charge doesn't have invoice property, so we need to get the invoice from the payment intent
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts
index 61def17b1e..44d3ec32e5 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts
@@ -12,7 +12,12 @@ import {
recordSale,
} from "@/lib/tinybird";
import { recordFakeClick } from "@/lib/tinybird/record-fake-click";
-import { ClickEventTB, LeadEventTB, WebhookPartner } from "@/lib/types";
+import {
+ ClickEventTB,
+ LeadEventTB,
+ StripeMode,
+ WebhookPartner,
+} from "@/lib/types";
import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import {
@@ -30,7 +35,10 @@ import { getSubscriptionProductId } from "./utils/get-subscription-product-id";
import { updateCustomerWithStripeCustomerId } from "./utils/update-customer-with-stripe-customer-id";
// Handle event "checkout.session.completed"
-export async function checkoutSessionCompleted(event: Stripe.Event) {
+export async function checkoutSessionCompleted(
+ event: Stripe.Event,
+ mode: StripeMode,
+) {
let charge = event.data.object as Stripe.Checkout.Session;
let dubCustomerExternalId = charge.metadata?.dubCustomerId; // TODO: need to update to dubCustomerExternalId in the future for consistency
const clientReferenceId = charge.client_reference_id;
@@ -180,7 +188,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
const promoCodeResponse = await attributeViaPromoCode({
promotionCodeId,
stripeAccountId,
- livemode: event.livemode,
+ mode,
charge,
});
if (promoCodeResponse) {
@@ -207,7 +215,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
const connectedCustomer = await getConnectedCustomer({
stripeCustomerId,
stripeAccountId,
- livemode: event.livemode,
+ mode,
});
if (connectedCustomer?.metadata.dubCustomerId) {
@@ -224,7 +232,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
const promoCodeResponse = await attributeViaPromoCode({
promotionCodeId,
stripeAccountId,
- livemode: event.livemode,
+ mode,
charge,
});
if (promoCodeResponse) {
@@ -405,7 +413,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
const productId = await getSubscriptionProductId({
stripeSubscriptionId: charge.subscription as string,
stripeAccountId,
- livemode: event.livemode,
+ mode,
});
const createdCommission = await createPartnerCommission({
@@ -504,19 +512,19 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
async function attributeViaPromoCode({
promotionCodeId,
stripeAccountId,
- livemode,
+ mode,
charge,
}: {
promotionCodeId: string;
stripeAccountId: string;
- livemode: boolean;
+ mode: StripeMode;
charge: Stripe.Checkout.Session;
}) {
// Find the promotion code for the promotion code id
const promotionCode = await getPromotionCode({
promotionCodeId,
stripeAccountId,
- livemode,
+ mode,
});
if (!promotionCode) {
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
index 30dfab1362..72390555f8 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
@@ -4,7 +4,7 @@ import { includeTags } from "@/lib/api/links/include-tags";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
import { getLeadEvent, recordSale } from "@/lib/tinybird";
-import { WebhookPartner } from "@/lib/types";
+import { StripeMode, WebhookPartner } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformSaleEventData } from "@/lib/webhook/transform";
@@ -16,7 +16,7 @@ import type Stripe from "stripe";
import { getConnectedCustomer } from "./utils/get-connected-customer";
// Handle event "invoice.paid"
-export async function invoicePaid(event: Stripe.Event) {
+export async function invoicePaid(event: Stripe.Event, mode: StripeMode) {
const invoice = event.data.object as Stripe.Invoice;
const stripeAccountId = event.account as string;
const stripeCustomerId = invoice.customer as string;
@@ -34,7 +34,7 @@ export async function invoicePaid(event: Stripe.Event) {
const connectedCustomer = await getConnectedCustomer({
stripeCustomerId,
stripeAccountId,
- livemode: event.livemode,
+ mode,
});
const dubCustomerExternalId = connectedCustomer?.metadata.dubCustomerId; // TODO: need to update to dubCustomerExternalId in the future for consistency
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts
index 8f2d5f41be..190ea45bfa 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts
@@ -1,4 +1,5 @@
import { stripe } from "@/lib/stripe";
+import { StripeMode } from "@/lib/types";
import { logAndRespond } from "app/(ee)/api/cron/utils";
import { withAxiom } from "next-axiom";
import Stripe from "stripe";
@@ -25,15 +26,23 @@ const relevantEvents = new Set([
// POST /api/stripe/integration/webhook – listen to Stripe webhooks (for Stripe Integration)
export const POST = withAxiom(async (req: Request) => {
const pathname = new URL(req.url).pathname;
- const testConnectWebhook = pathname.endsWith("/test");
-
const buf = await req.text();
const sig = req.headers.get("Stripe-Signature");
// @see https://github.com/dubinc/dub/blob/main/apps/web/app/(ee)/api/stripe/integration/webhook/test/route.ts
- const webhookSecret = testConnectWebhook
- ? process.env.STRIPE_APP_WEBHOOK_SECRET_TEST
- : process.env.STRIPE_APP_WEBHOOK_SECRET;
+ let webhookSecret: string | undefined;
+ let mode: StripeMode;
+
+ if (pathname.endsWith("/test")) {
+ webhookSecret = process.env.STRIPE_APP_WEBHOOK_SECRET_TEST;
+ mode = "test";
+ } else if (pathname.endsWith("/sandbox")) {
+ webhookSecret = process.env.STRIPE_APP_WEBHOOK_SECRET_SANDBOX;
+ mode = "sandbox";
+ } else {
+ webhookSecret = process.env.STRIPE_APP_WEBHOOK_SECRET;
+ mode = "live";
+ }
if (!sig || !webhookSecret) {
return new Response("Invalid request", {
@@ -68,13 +77,13 @@ export const POST = withAxiom(async (req: Request) => {
response = await customerUpdated(event);
break;
case "checkout.session.completed":
- response = await checkoutSessionCompleted(event);
+ response = await checkoutSessionCompleted(event, mode);
break;
case "invoice.paid":
- response = await invoicePaid(event);
+ response = await invoicePaid(event, mode);
break;
case "charge.refunded":
- response = await chargeRefunded(event);
+ response = await chargeRefunded(event, mode);
break;
case "account.application.deauthorized":
response = await accountApplicationDeauthorized(event);
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-connected-customer.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-connected-customer.ts
index 45e4dded12..68877d490d 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-connected-customer.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-connected-customer.ts
@@ -1,13 +1,14 @@
import { stripeAppClient } from "@/lib/stripe";
+import { StripeMode } from "@/lib/types";
export async function getConnectedCustomer({
stripeCustomerId,
stripeAccountId,
- livemode = true,
+ mode,
}: {
stripeCustomerId?: string | null;
stripeAccountId?: string | null;
- livemode?: boolean;
+ mode: StripeMode;
}) {
// if stripeCustomerId or stripeAccountId is not provided, return null
if (!stripeCustomerId || !stripeAccountId) {
@@ -15,7 +16,7 @@ export async function getConnectedCustomer({
}
const connectedCustomer = await stripeAppClient({
- livemode,
+ mode,
}).customers.retrieve(stripeCustomerId, {
stripeAccount: stripeAccountId,
});
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-promotion-code.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-promotion-code.ts
index 4bd492b1f7..24c816cb94 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-promotion-code.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-promotion-code.ts
@@ -1,24 +1,26 @@
import { stripeAppClient } from "@/lib/stripe";
+import { StripeMode } from "@/lib/types";
export async function getPromotionCode({
promotionCodeId,
stripeAccountId,
- livemode = true,
+ mode,
}: {
promotionCodeId?: string | null;
stripeAccountId?: string | null;
- livemode?: boolean;
+ mode: StripeMode;
}) {
if (!stripeAccountId || !promotionCodeId) {
return null;
}
try {
- return await stripeAppClient({
- livemode,
- }).promotionCodes.retrieve(promotionCodeId, {
- stripeAccount: stripeAccountId,
- });
+ return await stripeAppClient({ mode }).promotionCodes.retrieve(
+ promotionCodeId,
+ {
+ stripeAccount: stripeAccountId,
+ },
+ );
} catch (error) {
console.log("Failed to get promotion code:", error);
return null;
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-subscription-product-id.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-subscription-product-id.ts
index 90bc607792..14eaf2b99b 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-subscription-product-id.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-subscription-product-id.ts
@@ -1,13 +1,14 @@
import { stripeAppClient } from "@/lib/stripe";
+import { StripeMode } from "@/lib/types";
export async function getSubscriptionProductId({
stripeSubscriptionId,
stripeAccountId,
- livemode = true,
+ mode,
}: {
stripeSubscriptionId?: string | null;
stripeAccountId?: string | null;
- livemode?: boolean;
+ mode: StripeMode;
}) {
if (!stripeAccountId || !stripeSubscriptionId) {
return null;
@@ -15,10 +16,11 @@ export async function getSubscriptionProductId({
try {
const subscription = await stripeAppClient({
- livemode,
+ mode,
}).subscriptions.retrieve(stripeSubscriptionId, {
stripeAccount: stripeAccountId,
});
+
return subscription.items.data[0].price.product as string;
} catch (error) {
console.log("Failed to get subscription price ID:", error);
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index f5758b867c..8b81c55b10 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -19,7 +19,7 @@ import { Stripe } from "stripe";
import { authActionClient } from "../safe-action";
const stripe = stripeAppClient({
- ...(process.env.VERCEL_ENV && { livemode: true }),
+ ...(process.env.VERCEL_ENV && { mode: "live" }),
});
export const createDiscountAction = authActionClient
diff --git a/apps/web/lib/firstpromoter/update-stripe-customers.ts b/apps/web/lib/firstpromoter/update-stripe-customers.ts
index 0d56fb5961..9655a44bcf 100644
--- a/apps/web/lib/firstpromoter/update-stripe-customers.ts
+++ b/apps/web/lib/firstpromoter/update-stripe-customers.ts
@@ -9,7 +9,7 @@ import { FirstPromoterImportPayload } from "./types";
const CUSTOMERS_PER_BATCH = 20;
const stripe = stripeAppClient({
- ...(process.env.VERCEL_ENV && { livemode: true }),
+ ...(process.env.VERCEL_ENV && { mode: "live" }),
});
// FirstPromoter API doesn't return the Stripe customer ID,
diff --git a/apps/web/lib/partnerstack/update-stripe-customers.ts b/apps/web/lib/partnerstack/update-stripe-customers.ts
index 9bb87e5c31..09d79e037e 100644
--- a/apps/web/lib/partnerstack/update-stripe-customers.ts
+++ b/apps/web/lib/partnerstack/update-stripe-customers.ts
@@ -11,7 +11,7 @@ import { PartnerStackImportPayload } from "./types";
const CUSTOMERS_PER_BATCH = 20;
const stripe = stripeAppClient({
- ...(process.env.VERCEL_ENV && { livemode: true }),
+ ...(process.env.VERCEL_ENV && { mode: "live" }),
});
// PartnerStack API doesn't return the Stripe customer ID,
diff --git a/apps/web/lib/stripe/create-stripe-discount-code.ts b/apps/web/lib/stripe/create-stripe-discount-code.ts
index da705cd26b..2af45cec94 100644
--- a/apps/web/lib/stripe/create-stripe-discount-code.ts
+++ b/apps/web/lib/stripe/create-stripe-discount-code.ts
@@ -3,7 +3,7 @@ import { stripeAppClient } from ".";
import { DiscountProps } from "../types";
const stripe = stripeAppClient({
- ...(process.env.VERCEL_ENV && { livemode: true }),
+ ...(process.env.VERCEL_ENV && { mode: "live" }),
});
const MAX_ATTEMPTS = 3;
diff --git a/apps/web/lib/stripe/disable-stripe-discount-code.ts b/apps/web/lib/stripe/disable-stripe-discount-code.ts
index 77cb27f56c..05eef06cd4 100644
--- a/apps/web/lib/stripe/disable-stripe-discount-code.ts
+++ b/apps/web/lib/stripe/disable-stripe-discount-code.ts
@@ -1,7 +1,7 @@
import { stripeAppClient } from ".";
const stripe = stripeAppClient({
- ...(process.env.VERCEL_ENV && { livemode: true }),
+ ...(process.env.VERCEL_ENV && { mode: "live" }),
});
export async function disableStripeDiscountCode({
diff --git a/apps/web/lib/stripe/index.ts b/apps/web/lib/stripe/index.ts
index 667e3dae41..4cddaaec9e 100644
--- a/apps/web/lib/stripe/index.ts
+++ b/apps/web/lib/stripe/index.ts
@@ -1,4 +1,5 @@
import Stripe from "stripe";
+import { StripeMode } from "../types";
export const stripe = new Stripe(`${process.env.STRIPE_SECRET_KEY}`, {
apiVersion: "2025-05-28.basil",
@@ -9,14 +10,26 @@ export const stripe = new Stripe(`${process.env.STRIPE_SECRET_KEY}`, {
});
// Stripe Integration App client
-export const stripeAppClient = ({ livemode }: { livemode?: boolean }) =>
- new Stripe(
- `${!livemode ? process.env.STRIPE_APP_SECRET_KEY_TEST : process.env.STRIPE_APP_SECRET_KEY}`,
- {
- apiVersion: "2025-05-28.basil",
- appInfo: {
- name: "Dub.co",
- version: "0.1.0",
- },
+export const stripeAppClient = ({ mode = "live" }: { mode?: StripeMode }) => {
+ let appSecretKey: string | undefined;
+
+ if (mode === "test") {
+ appSecretKey = process.env.STRIPE_APP_SECRET_KEY_TEST;
+ } else if (mode === "sandbox") {
+ appSecretKey = process.env.STRIPE_APP_SECRET_KEY_SANDBOX;
+ } else {
+ appSecretKey = process.env.STRIPE_APP_SECRET_KEY;
+ }
+
+ if (!appSecretKey) {
+ throw new Error("Stripe app secret key is not set.");
+ }
+
+ return new Stripe(appSecretKey, {
+ apiVersion: "2025-05-28.basil",
+ appInfo: {
+ name: "Dub.co",
+ version: "0.1.0",
},
- );
+ });
+};
diff --git a/apps/web/lib/tolt/update-stripe-customers.ts b/apps/web/lib/tolt/update-stripe-customers.ts
index 826e91a9cd..b831cffdef 100644
--- a/apps/web/lib/tolt/update-stripe-customers.ts
+++ b/apps/web/lib/tolt/update-stripe-customers.ts
@@ -9,7 +9,7 @@ import { ToltImportPayload } from "./types";
const CUSTOMERS_PER_BATCH = 20;
const stripe = stripeAppClient({
- ...(process.env.VERCEL_ENV && { livemode: true }),
+ ...(process.env.VERCEL_ENV && { mode: "live" }),
});
// Tolt API doesn't return the Stripe customer ID,
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index acaf4afc16..befaba189a 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -648,3 +648,5 @@ export type BountySubmissionsQueryFilters = z.infer<
>;
export type Message = z.infer<typeof MessageSchema>;
+
+export type StripeMode = "test" | "sandbox" | "live";