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.

handle charge.dispute.created event separately

Steven Tey877482923e7e
diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-dispute-created.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-dispute-created.ts
new file mode 100644
index 0000000000..a661fb6dad
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-dispute-created.ts
@@ -0,0 +1,76 @@
+import { disableWorkspaceLinks } from "@/lib/api/workspaces/disable-workspace-links";
+import { prisma } from "@/lib/prisma";
+import { stripe } from "@/lib/stripe";
+import { cancelSubscription } from "@/lib/stripe/cancel-subscription";
+import { LEGAL_USER_ID } from "@dub/utils";
+import Stripe from "stripe";
+import { addToStripeFraudValueLists } from "./utils/add-to-stripe-fraud-value-lists";
+
+export async function chargeDisputeCreated(
+ event: Stripe.ChargeDisputeCreatedEvent,
+) {
+ const dispute = event.data.object;
+ const chargeId =
+ typeof dispute.charge === "string" ? dispute.charge : dispute.charge.id;
+
+ const charge = await stripe.charges.retrieve(chargeId);
+
+ const { customer: customerId, payment_method_details } = charge;
+
+ const workspace = await prisma.project.findUnique({
+ where: {
+ stripeId: customerId as string,
+ },
+ });
+
+ // should never happen, but just in case
+ if (!workspace) {
+ return `Workspace with stripeId ${customerId} not found.`;
+ }
+
+ await disableWorkspaceLinks(workspace.id);
+
+ const updatedUsers = await prisma.projectUsers.updateMany({
+ where: {
+ projectId: workspace.id,
+ },
+ data: {
+ role: "viewer",
+ },
+ });
+
+ console.log(`Updated ${updatedUsers.count} users to viewer role`);
+
+ await prisma.projectUsers.create({
+ data: {
+ projectId: workspace.id,
+ userId: LEGAL_USER_ID,
+ role: "owner",
+ },
+ });
+ console.log(
+ `Added legal user ${LEGAL_USER_ID} as owner to workspace ${workspace.id}`,
+ );
+
+ // should always have stripeId, but just in case
+ if (workspace.stripeId) {
+ await cancelSubscription({
+ customerId: workspace.stripeId,
+ reason: "Workspace banned due to charge dispute",
+ });
+
+ const stripeCustomer = (await stripe.customers.retrieve(
+ workspace.stripeId,
+ )) as Stripe.Customer;
+
+ const cardFingerprint = payment_method_details?.card?.fingerprint;
+
+ await addToStripeFraudValueLists({
+ customerId: workspace.stripeId,
+ customerEmail: stripeCustomer.email,
+ cardFingerprint,
+ });
+ }
+
+ return `Workspace ${workspace.id} banned due to charge dispute`;
+}
diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
index 25824756b5..e874133b9b 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
@@ -1,6 +1,6 @@
import { prisma } from "@/lib/prisma";
import Stripe from "stripe";
-import { detectAndHandleFraudulentCharge } from "./utils/detect-and-handle-fraudulent-charge";
+import { detectAndHandleFraudulentFailedCharge } from "./utils/detect-and-handle-fraudulent-failed-charge";
import { processDomainRenewalFailure } from "./utils/process-domain-renewal-failure";
import { processPayoutInvoiceFailure } from "./utils/process-payout-invoice-failure";
@@ -10,7 +10,7 @@ export async function chargeFailed(event: Stripe.ChargeFailedEvent) {
const { transfer_group: invoiceId, failure_message: failedReason } = charge;
if (!invoiceId) {
- return detectAndHandleFraudulentCharge(event);
+ return detectAndHandleFraudulentFailedCharge(event);
}
let invoice = await prisma.invoice.findUnique({
diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/add-to-stripe-fraud-value-lists.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/add-to-stripe-fraud-value-lists.ts
new file mode 100644
index 0000000000..ff8e7df511
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/add-to-stripe-fraud-value-lists.ts
@@ -0,0 +1,47 @@
+import { stripe } from "@/lib/stripe";
+
+export const STRIPE_FRAUD_VALUE_LISTS = {
+ CUSTOMER_ID: "rsl_1LeVdvAlJJEpqkPVEcNgjxqq",
+ CUSTOMER_EMAIL: "rsl_1LeVdvAlJJEpqkPVhZw9Xvgw",
+ CARD_FINGERPRINT: "rsl_1LeVdvAlJJEpqkPVvUZUm9eC",
+};
+
+export async function addToStripeFraudValueLists({
+ customerId,
+ customerEmail,
+ cardFingerprint,
+}: {
+ customerId: string;
+ customerEmail?: string | null;
+ cardFingerprint?: string | null;
+}) {
+ // add to Stripe Fraud Value Lists
+ await Promise.allSettled([
+ stripe.radar.valueListItems.create({
+ value_list: STRIPE_FRAUD_VALUE_LISTS.CUSTOMER_ID,
+ value: customerId,
+ }),
+ customerEmail
+ ? stripe.radar.valueListItems.create({
+ value_list: STRIPE_FRAUD_VALUE_LISTS.CUSTOMER_EMAIL,
+ value: customerEmail,
+ })
+ : null,
+ cardFingerprint
+ ? stripe.radar.valueListItems.create({
+ value_list: STRIPE_FRAUD_VALUE_LISTS.CARD_FINGERPRINT,
+ value: cardFingerprint,
+ })
+ : null,
+ ]).then((results) => {
+ results.forEach((result, idx) => {
+ if (result.status === "fulfilled" && result.value) {
+ const listItem = [customerId, customerEmail, cardFingerprint][idx];
+ const listName = Object.entries(STRIPE_FRAUD_VALUE_LISTS)[idx][0];
+ console.log(
+ `Added ${listItem} to ${listName} Fraud Value List: ${JSON.stringify(result.value, null, 2)}`,
+ );
+ }
+ });
+ });
+}
diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/detect-and-handle-fraudulent-charge.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/detect-and-handle-fraudulent-failed-charge.ts
similarity index 52%
rename from apps/web/app/(ee)/api/stripe/webhook/utils/detect-and-handle-fraudulent-charge.ts
rename to apps/web/app/(ee)/api/stripe/webhook/utils/detect-and-handle-fraudulent-failed-charge.ts
index e13d683f64..f9b72f4841 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/utils/detect-and-handle-fraudulent-charge.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/detect-and-handle-fraudulent-failed-charge.ts
@@ -4,32 +4,16 @@ import { prisma } from "@/lib/prisma";
import { stripe } from "@/lib/stripe";
import { LEGAL_USER_ID, log } from "@dub/utils";
import Stripe from "stripe";
+import { addToStripeFraudValueLists } from "./add-to-stripe-fraud-value-lists";
-const STRIPE_FRAUD_VALUE_LISTS = {
- CUSTOMER_ID: "rsl_1LeVdvAlJJEpqkPVEcNgjxqq",
- CUSTOMER_EMAIL: "rsl_1LeVdvAlJJEpqkPVhZw9Xvgw",
- CARD_FINGERPRINT: "rsl_1LeVdvAlJJEpqkPVvUZUm9eC",
-};
-
-export async function detectAndHandleFraudulentCharge(
- event: Stripe.ChargeFailedEvent | Stripe.ChargeDisputeCreatedEvent,
+export async function detectAndHandleFraudulentFailedCharge(
+ event: Stripe.ChargeFailedEvent,
) {
- let charge: Stripe.Charge;
-
- if (event.type === "charge.dispute.created") {
- const dispute = event.data.object;
- const chargeId =
- typeof dispute.charge === "string" ? dispute.charge : dispute.charge.id;
- charge = await stripe.charges.retrieve(chargeId);
- } else {
- charge = event.data.object;
- }
-
- const { customer, outcome, payment_method_details } = charge;
+ const { customer, outcome, payment_method_details } = event.data.object;
// should never happen, but just in case
if (!customer || !outcome || !payment_method_details) {
- return `[detectAndHandleFraudulentCharge]: Invalid charge attributes: ${JSON.stringify({ customer, outcome })}`;
+ return `[detectAndHandleFraudulentFailedCharge]: Invalid charge attributes: ${JSON.stringify({ customer, outcome })}`;
}
const customerId = customer as string;
@@ -41,13 +25,13 @@ export async function detectAndHandleFraudulentCharge(
});
if (workspace) {
- return `[detectAndHandleFraudulentCharge]: Workspace with stripeId ${customer} already created, so this is most likely a failed subscription renewal payment, skipping...`;
+ return `[detectAndHandleFraudulentFailedCharge]: Workspace with stripeId ${customer} already created, so this is most likely a failed subscription renewal payment, skipping...`;
}
const { risk_level } = outcome;
if (risk_level !== "highest") {
- return `[detectAndHandleFraudulentCharge]: Risk level "${risk_level}" is not highest, skipping...`;
+ return `[detectAndHandleFraudulentFailedCharge]: Risk level "${risk_level}" is not highest, skipping...`;
}
const stripeCustomer = (await stripe.customers.retrieve(
@@ -56,36 +40,10 @@ export async function detectAndHandleFraudulentCharge(
const cardFingerprint = payment_method_details.card?.fingerprint;
- // add to Stripe Fraud Value Lists
- await Promise.allSettled([
- stripe.radar.valueListItems.create({
- value_list: STRIPE_FRAUD_VALUE_LISTS.CUSTOMER_ID,
- value: customerId,
- }),
- stripeCustomer.email
- ? stripe.radar.valueListItems.create({
- value_list: STRIPE_FRAUD_VALUE_LISTS.CUSTOMER_EMAIL,
- value: stripeCustomer.email!,
- })
- : null,
- cardFingerprint
- ? stripe.radar.valueListItems.create({
- value_list: STRIPE_FRAUD_VALUE_LISTS.CARD_FINGERPRINT,
- value: cardFingerprint,
- })
- : null,
- ]).then((results) => {
- results.forEach((result, idx) => {
- if (result.status === "fulfilled" && result.value) {
- const listItem = [customerId, stripeCustomer.email, cardFingerprint][
- idx
- ];
- const listName = Object.entries(STRIPE_FRAUD_VALUE_LISTS)[idx][0];
- console.log(
- `Added ${listItem} to ${listName} Fraud Value List: ${JSON.stringify(result.value, null, 2)}`,
- );
- }
- });
+ await addToStripeFraudValueLists({
+ customerId: customerId,
+ customerEmail: stripeCustomer.email,
+ cardFingerprint,
});
if (stripeCustomer.email) {
@@ -115,7 +73,7 @@ export async function detectAndHandleFraudulentCharge(
paidWorkspaces++;
await log({
type: "errors",
- message: `[detectAndHandleFraudulentCharge]: Workspace ${workspace.slug} for fraudulent user ${user.email} is not a free plan, skipping...`,
+ message: `[detectAndHandleFraudulentFailedCharge]: Workspace ${workspace.slug} for fraudulent user ${user.email} is not a free plan, skipping...`,
});
continue;
}
@@ -138,7 +96,7 @@ export async function detectAndHandleFraudulentCharge(
},
});
console.log(
- `[detectAndHandleFraudulentCharge]: Transferred ownership of workspace ${workspace.slug} to legal user ${LEGAL_USER_ID}`,
+ `[detectAndHandleFraudulentFailedCharge]: Transferred ownership of workspace ${workspace.slug} to legal user ${LEGAL_USER_ID}`,
);
// disable workspace links
await disableWorkspaceLinks(workspace.id);
@@ -150,13 +108,13 @@ export async function detectAndHandleFraudulentCharge(
},
});
console.log(
- `[detectAndHandleFraudulentCharge]: Deleted workspace ${workspace.slug} because it has no links`,
+ `[detectAndHandleFraudulentFailedCharge]: Deleted workspace ${workspace.slug} because it has no links`,
);
}
}
} else {
console.log(
- `[detectAndHandleFraudulentCharge]: User ${user.email} has no workspaces, skipping...`,
+ `[detectAndHandleFraudulentFailedCharge]: User ${user.email} has no workspaces, skipping...`,
);
}
@@ -182,10 +140,10 @@ export async function detectAndHandleFraudulentCharge(
});
} else {
console.log(
- `[detectAndHandleFraudulentCharge]: User with email ${stripeCustomer.email} not found, skipping...`,
+ `[detectAndHandleFraudulentFailedCharge]: User with email ${stripeCustomer.email} not found, skipping...`,
);
}
}
- return `[detectAndHandleFraudulentCharge]: Processed ${event.type} event for customer ${customerId} (${stripeCustomer.email}) and card fingerprint "${cardFingerprint}".`;
+ return `[detectAndHandleFraudulentFailedCharge]: Processed charge.failed event for customer ${customerId} (${stripeCustomer.email}) and card fingerprint "${cardFingerprint}".`;
}
diff --git a/apps/web/lib/api/workspaces/delete-workspace.ts b/apps/web/lib/api/workspaces/delete-workspace.ts
index 23e4b2da92..9dcbf4f133 100644
--- a/apps/web/lib/api/workspaces/delete-workspace.ts
+++ b/apps/web/lib/api/workspaces/delete-workspace.ts
@@ -48,7 +48,8 @@ export async function deleteWorkspace(
}),
// Cancel the workspace's Stripe subscription if exists
- workspace.stripeId && cancelSubscription(workspace.stripeId),
+ workspace.stripeId &&
+ cancelSubscription({ customerId: workspace.stripeId }),
// Delete workspace logo if it's a custom logo stored in R2
workspace.logo &&
@@ -120,7 +121,11 @@ export async function deleteWorkspaceAdmin(
storage.delete({ key: workspace.logo.replace(`${R2_URL}/`, "") }),
// if they have a Stripe subscription, cancel it
- workspace.stripeId && cancelSubscription(workspace.stripeId),
+ workspace.stripeId &&
+ cancelSubscription({
+ customerId: workspace.stripeId,
+ reason: "Customer was banned from Dub",
+ }),
// Queue the workspace for deletion
qstash.publishJSON({
diff --git a/apps/web/lib/stripe/cancel-subscription.ts b/apps/web/lib/stripe/cancel-subscription.ts
index 6fe0dbfeba..afb665beb2 100644
--- a/apps/web/lib/stripe/cancel-subscription.ts
+++ b/apps/web/lib/stripe/cancel-subscription.ts
@@ -1,19 +1,23 @@
import { stripe } from ".";
-export async function cancelSubscription(customer?: string) {
- if (!customer) return;
-
+export async function cancelSubscription({
+ customerId,
+ reason,
+}: {
+ customerId: string;
+ reason?: string;
+}) {
try {
const subscriptionId = await stripe.subscriptions
.list({
- customer,
+ customer: customerId,
})
.then((res) => res.data[0].id);
return await stripe.subscriptions.update(subscriptionId, {
cancel_at_period_end: true,
cancellation_details: {
- comment: "Customer deleted their Dub workspace.",
+ comment: reason || "Customer deleted their Dub workspace.",
},
});
} catch (error) {
diff --git a/apps/web/ui/workspaces/subscription-menu.tsx b/apps/web/ui/workspaces/subscription-menu.tsx
index 3afa4c3ff1..42aa22b66f 100644
--- a/apps/web/ui/workspaces/subscription-menu.tsx
+++ b/apps/web/ui/workspaces/subscription-menu.tsx
@@ -60,7 +60,7 @@ export default function SubscriptionMenu() {
});
};
- const cancelSubscription = async () => {
+ const handleCancellation = async () => {
setIsOpen(false);
setClicked(true);
return fetch(`/api/workspaces/${workspaceId}/billing/cancel`, {
@@ -96,7 +96,7 @@ export default function SubscriptionMenu() {
newPeriod: "monthly",
newTier: 1,
onConfirm: async () => {
- await cancelSubscription();
+ await handleCancellation();
setShowPlanChangeConfirmationModal(false);
},
});
@@ -126,11 +126,11 @@ export default function SubscriptionMenu() {
cancelText: "Not now",
confirmText: "Cancel subscription",
onConfirm: async () => {
- await cancelSubscription();
+ await handleCancellation();
},
});
- const handleCancelSubscription = () => {
+ const handlehandleCancellation = () => {
setIsOpen(false);
if (losesPartnerAccess) {
setShowPlanChangeConfirmationModal(true);
@@ -162,7 +162,7 @@ export default function SubscriptionMenu() {
<MenuItem
icon={SquareXmark}
label="Cancel subscription"
- onSelect={handleCancelSubscription}
+ onSelect={handlehandleCancellation}
disabledTooltip={
subscriptionCanceledAt
? "Your subscription has already been scheduled for cancellation."