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.

Stripe integration - account for multiple line items for a given invoice (#3824)

Kiran Kd7a34ee0452c
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 45a5221409..dfc8b54696 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
@@ -22,7 +22,7 @@ import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
import { attributeViaPromotionCodeId } from "./utils/attribute-via-promotion-code-id";
-import { getCheckoutSessionProductId } from "./utils/get-checkout-session-product-id";
+import { getCheckoutSessionProducts } from "./utils/get-checkout-session-products";
import { getConnectedCustomer } from "./utils/get-connected-customer";
import { incrementLinkLeads } from "./utils/increment-link-leads";
import { updateCustomerWithStripeCustomerId } from "./utils/update-customer-with-stripe-customer-id";
@@ -363,9 +363,10 @@ export async function checkoutSessionCompleted(
if (!ok) {
console.info(
- "[Stripe Webhook] Skipping already processed invoice.",
+ "[checkout.session.completed] Skipping already processed invoice.",
invoiceId,
);
+
return {
response: `Invoice with ID ${invoiceId} already processed, skipping...`,
workspaceId: workspace.id,
@@ -491,7 +492,7 @@ export async function checkoutSessionCompleted(
| undefined = undefined;
if (link && link.programId && link.partnerId) {
- const productId = await getCheckoutSessionProductId({
+ const products = await getCheckoutSessionProducts({
checkoutSessionId: charge.id,
stripeAccountId,
mode,
@@ -514,7 +515,7 @@ export async function checkoutSessionCompleted(
signupDate: customer.createdAt,
},
sale: {
- productId,
+ products,
amount: saleData.amount,
},
},
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 041ded72d3..9bb6f3d482 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
@@ -176,7 +176,7 @@ export async function invoicePaid(
if (!ok) {
console.info(
- "[Stripe Webhook] Skipping already processed invoice.",
+ "[invoice.paid] Skipping already processed invoice.",
invoiceId,
);
return {
@@ -315,6 +315,23 @@ export async function invoicePaid(
| undefined = undefined;
if (link.programId && link.partnerId) {
+ const products = invoice.lines.data
+ .map((line) => {
+ const productId = line.pricing?.price_details?.product;
+
+ if (!productId) return null;
+
+ return {
+ id: productId,
+ amount: line.amount,
+ quantity: line.quantity ?? 0,
+ };
+ })
+ .filter(
+ (p): p is { id: string; amount: number; quantity: number } =>
+ p !== null && p.quantity !== null,
+ );
+
result = await queuePartnerCommissionCreation({
event: "sale",
programId: link.programId,
@@ -332,7 +349,7 @@ export async function invoicePaid(
signupDate: customer.createdAt,
},
sale: {
- productId: invoice.lines.data[0]?.pricing?.price_details?.product,
+ products,
amount: saleData.amount,
},
},
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-checkout-session-product-id.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-checkout-session-product-id.ts
deleted file mode 100644
index 2191ecfee1..0000000000
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-checkout-session-product-id.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { stripeAppClient } from "@/lib/stripe";
-import { StripeMode } from "@/lib/types";
-import type Stripe from "stripe";
-
-function productIdFromLineItemPrice(
- price: Stripe.Price | string | null | undefined,
-): string | null {
- if (!price || typeof price === "string") {
- return null;
- }
-
- if (!price.product) {
- return null;
- }
-
- const product = price.product;
-
- if (typeof product === "string") {
- return product;
- }
-
- if ("deleted" in product && product.deleted) {
- return null;
- }
-
- return product.id;
-}
-
-export async function getCheckoutSessionProductId({
- checkoutSessionId,
- stripeAccountId,
- mode,
-}: {
- checkoutSessionId: string;
- stripeAccountId?: string | null;
- mode: StripeMode;
-}): Promise<string | null> {
- if (!stripeAccountId) {
- return null;
- }
-
- try {
- const lineItems = await stripeAppClient({
- mode,
- }).checkout.sessions.listLineItems(
- checkoutSessionId,
- {
- expand: ["data.price.product"],
- limit: 10,
- },
- {
- stripeAccount: stripeAccountId,
- },
- );
-
- for (const item of lineItems.data) {
- const productId = productIdFromLineItemPrice(item.price);
- if (productId) {
- return productId;
- }
- }
-
- return null;
- } catch (error) {
- console.log("Failed to get checkout session product ID:", error);
- return null;
- }
-}
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-checkout-session-products.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-checkout-session-products.ts
new file mode 100644
index 0000000000..04970ed9a1
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-checkout-session-products.ts
@@ -0,0 +1,97 @@
+import { stripeAppClient } from "@/lib/stripe";
+import { StripeMode } from "@/lib/types";
+import type Stripe from "stripe";
+
+export function productIdFromLineItemPrice(
+ price: Stripe.Price | string | null | undefined,
+): string | null {
+ if (!price || typeof price === "string") {
+ return null;
+ }
+
+ if (!price.product) {
+ return null;
+ }
+
+ const product = price.product;
+
+ if (typeof product === "string") {
+ return product;
+ }
+
+ if ("deleted" in product && product.deleted) {
+ return null;
+ }
+
+ return product.id;
+}
+
+export async function getCheckoutSessionProducts({
+ checkoutSessionId,
+ stripeAccountId,
+ mode,
+}: {
+ checkoutSessionId: string;
+ stripeAccountId?: string | null;
+ mode: StripeMode;
+}) {
+ if (!stripeAccountId) {
+ return [];
+ }
+
+ try {
+ const stripeApp = stripeAppClient({
+ mode,
+ });
+
+ const lineItems = await stripeApp.checkout.sessions.listLineItems(
+ checkoutSessionId,
+ {
+ expand: ["data.price.product"],
+ limit: 10,
+ },
+ {
+ stripeAccount: stripeAccountId,
+ },
+ );
+
+ if (lineItems.data.length === 0) {
+ console.log(
+ `[getCheckoutSessionProducts] No line items found for checkout session ${checkoutSessionId}.`,
+ );
+ return [];
+ }
+
+ const products = lineItems.data
+ .map((line) => {
+ const productId = productIdFromLineItemPrice(line.price);
+
+ if (!productId) return null;
+
+ return {
+ id: productId,
+ amount: line.amount_total,
+ quantity: line.quantity,
+ };
+ })
+ .filter(
+ (p): p is { id: string; amount: number; quantity: number } =>
+ p !== null && p.quantity !== null,
+ );
+
+ if (products.length === 0) {
+ console.log(
+ `[getCheckoutSessionProducts] No valid products found for checkout session ${checkoutSessionId}.`,
+ );
+ return [];
+ }
+
+ return products;
+ } catch (error) {
+ console.log(
+ "[getCheckoutSessionProducts] Failed to get checkout session products:",
+ error,
+ );
+ return [];
+ }
+}
diff --git a/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts b/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts
index a1deaae1d4..9b4e655c8a 100644
--- a/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts
+++ b/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts
@@ -8,7 +8,7 @@ import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { logger } from "@/lib/axiom/server";
import { getWorkflowConfig } from "@/lib/cron/qstash-workflow";
import { constructWebhookPartner } from "@/lib/partners/constuct-webhook-partner";
-import { determinePartnerReward } from "@/lib/partners/determine-partner-reward";
+import { determinePartnerRewards } from "@/lib/partners/determine-partner-reward";
import { getRewardAmount } from "@/lib/partners/get-reward-amount";
import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
import { RewardProps } from "@/lib/types";
@@ -233,12 +233,18 @@ async function stepCreateCommission(
};
}
- reward = determinePartnerReward({
+ const rewards = determinePartnerRewards({
event,
programEnrollment,
- ...(context ? { context } : {}),
+ context,
+ amount,
+ quantity,
});
+ if (rewards.length > 0) {
+ reward = rewards[0].reward;
+ }
+
// if there is no reward, skip commission creation
if (!reward) {
return logAndReturn({
@@ -247,7 +253,8 @@ async function stepCreateCommission(
});
}
- // for click events, it's super simple – just multiply the reward amount by the quantity
+ // Click commissions are created by /api/cron/aggregate-clicks, not this workflow.
+ // TODO: Confirm whether any caller still queues event === "click" here; if not, remove this branch.
if (event === "click") {
earnings = getRewardAmount(reward) * quantity;
@@ -332,15 +339,18 @@ async function stepCreateCommission(
// for lead events, we just multiply the reward amount by the quantity
if (event === "lead") {
earnings = getRewardAmount(reward) * quantity;
- // for sale events, we need to calculate the earnings based on the sale amount
- } else {
- earnings = calculateSaleEarnings({
- reward,
- sale: {
- quantity,
- amount,
- },
- });
+ }
+ // for sale events, we need to calculate the earnings based on the sale amount
+ else {
+ earnings = rewards.reduce(
+ (acc, { reward, sale }) =>
+ acc +
+ calculateSaleEarnings({
+ reward,
+ sale,
+ }),
+ 0,
+ );
}
}
}
diff --git a/apps/web/lib/partners/determine-partner-reward.ts b/apps/web/lib/partners/determine-partner-reward.ts
index c784201312..7870d130ef 100644
--- a/apps/web/lib/partners/determine-partner-reward.ts
+++ b/apps/web/lib/partners/determine-partner-reward.ts
@@ -1,7 +1,7 @@
import { EventType, Link, Prisma, Reward } from "@dub/prisma/client";
import { toCentsNumber } from "@dub/utils";
import { serializeReward } from "../api/partners/serialize-reward";
-import { RewardContext } from "../types";
+import { RewardContext, RewardProps } from "../types";
import {
rewardConditionsArraySchema,
RewardSchema,
@@ -25,6 +25,14 @@ interface ProgramEnrollmentWithReward {
saleReward?: Reward | null;
}
+interface ProductReward {
+ reward: RewardProps;
+ sale: {
+ amount: number;
+ quantity: number;
+ };
+}
+
export const determinePartnerReward = ({
event,
programEnrollment,
@@ -96,3 +104,80 @@ export const determinePartnerReward = ({
return RewardSchema.parse(partnerReward);
};
+
+export const determinePartnerRewards = ({
+ event,
+ programEnrollment,
+ context,
+ amount,
+ quantity,
+}: {
+ event: EventType;
+ programEnrollment: ProgramEnrollmentWithReward;
+ context?: RewardContext; // additional reward context (e.g. customer.country, sale.productId, etc.)
+ amount: number;
+ quantity: number;
+}): ProductReward[] => {
+ const rewards: ProductReward[] = [];
+ const products = context?.sale?.products ?? [];
+ const modifiers = rewardConditionsArraySchema.safeParse(
+ programEnrollment.saleReward?.modifiers,
+ );
+
+ const hasProductIdModifier = modifiers.success
+ ? modifiers.data.some((m) =>
+ m.conditions.some(
+ (c) => c.entity === "sale" && c.attribute === "productId",
+ ),
+ )
+ : false;
+
+ // If there are products and a productId modifier,
+ // we need to calculate the reward for each product (for Stripe integration only)
+ if (products.length > 0 && hasProductIdModifier) {
+ for (const product of products) {
+ const reward = determinePartnerReward({
+ event,
+ programEnrollment,
+ context: {
+ ...context,
+ sale: {
+ ...context?.sale,
+ productId: product.id,
+ amount: product.amount,
+ },
+ },
+ });
+
+ if (reward) {
+ rewards.push({
+ reward,
+ sale: {
+ amount: product.amount,
+ quantity: product.quantity,
+ },
+ });
+ }
+ }
+ } else {
+ const reward = determinePartnerReward({
+ event,
+ programEnrollment,
+ ...(context ? { context } : {}),
+ });
+
+ if (reward) {
+ rewards.push({
+ reward,
+ sale: {
+ amount,
+ quantity,
+ },
+ });
+ }
+ }
+
+ console.info("Resolved rewards", rewards);
+
+ return rewards;
+};
diff --git a/apps/web/lib/partners/evaluate-reward-conditions.ts b/apps/web/lib/partners/evaluate-reward-conditions.ts
index 6822736917..83fea66b1c 100644
--- a/apps/web/lib/partners/evaluate-reward-conditions.ts
+++ b/apps/web/lib/partners/evaluate-reward-conditions.ts
@@ -82,50 +82,75 @@ const evaluateCondition = ({
condition: RewardCondition;
fieldValue: string | number | string[] | number[];
}) => {
- switch (condition.operator) {
- case "equals_to":
- return fieldValue === condition.value;
- case "not_equals":
- return fieldValue !== condition.value;
- case "starts_with":
- if (
- typeof fieldValue === "string" &&
- typeof condition.value === "string"
- ) {
- return fieldValue.startsWith(condition.value);
- }
+ // Equals
+ if (condition.operator === "equals_to") {
+ return fieldValue === condition.value;
+ }
+
+ // Not equals
+ if (condition.operator === "not_equals") {
+ return fieldValue !== condition.value;
+ }
+
+ // Starts with
+ if (condition.operator === "starts_with") {
+ if (typeof fieldValue !== "string" || typeof condition.value !== "string") {
return false;
- case "ends_with":
- if (
- typeof fieldValue === "string" &&
- typeof condition.value === "string"
- ) {
- return fieldValue.endsWith(condition.value);
- }
+ }
+
+ return fieldValue.startsWith(condition.value);
+ }
+
+ // Ends with
+ if (condition.operator === "ends_with") {
+ if (typeof fieldValue !== "string" || typeof condition.value !== "string") {
return false;
- case "in":
- if (Array.isArray(condition.value)) {
- return (condition.value as (string | number)[]).includes(
- fieldValue as string | number,
- );
- }
+ }
+
+ return fieldValue.endsWith(condition.value);
+ }
+
+ // In
+ if (condition.operator === "in") {
+ if (!Array.isArray(condition.value)) {
return false;
- case "not_in":
- if (Array.isArray(condition.value)) {
- return !(condition.value as (string | number)[]).includes(
- fieldValue as string | number,
- );
- }
- return true;
- case "greater_than":
- return Number(fieldValue) > Number(condition.value);
- case "greater_than_or_equal":
- return Number(fieldValue) >= Number(condition.value);
- case "less_than":
- return Number(fieldValue) < Number(condition.value);
- case "less_than_or_equal":
- return Number(fieldValue) <= Number(condition.value);
- default:
+ }
+
+ return (condition.value as (string | number)[]).includes(
+ fieldValue as string | number,
+ );
+ }
+
+ // Not in
+ if (condition.operator === "not_in") {
+ if (!Array.isArray(condition.value)) {
return false;
+ }
+
+ return !(condition.value as (string | number)[]).includes(
+ fieldValue as string | number,
+ );
+ }
+
+ // Greater than
+ if (condition.operator === "greater_than") {
+ return Number(fieldValue) > Number(condition.value);
}
+
+ // Greater than or equal
+ if (condition.operator === "greater_than_or_equal") {
+ return Number(fieldValue) >= Number(condition.value);
+ }
+
+ // Less than
+ if (condition.operator === "less_than") {
+ return Number(fieldValue) < Number(condition.value);
+ }
+
+ // Less than or equal
+ if (condition.operator === "less_than_or_equal") {
+ return Number(fieldValue) <= Number(condition.value);
+ }
+
+ return false;
};
diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.ts
index 35fc88450e..5cec9a1350 100644
--- a/apps/web/lib/zod/schemas/rewards.ts
+++ b/apps/web/lib/zod/schemas/rewards.ts
@@ -422,6 +422,16 @@ export const rewardContextSchema = z.object({
productId: z.string().nullish(),
amount: z.number().nullish(),
type: z.enum(["new", "recurring"]).nullish(),
+ products: z
+ .array(
+ z.object({
+ id: z.string(),
+ amount: z.number(),
+ quantity: z.number(),
+ }),
+ )
+ .nullish()
+ .describe("Only used in Stripe integration."),
})
.optional(),
diff --git a/apps/web/scripts/dev/seed-integration.ts b/apps/web/scripts/dev/seed-integration.ts
new file mode 100644
index 0000000000..16150a7f10
--- /dev/null
+++ b/apps/web/scripts/dev/seed-integration.ts
@@ -0,0 +1,28 @@
+import { prisma } from "@dub/prisma";
+import { ACME_WORKSPACE_ID, STRIPE_INTEGRATION_ID } from "@dub/utils";
+import "dotenv-flow/config";
+
+async function main() {
+ await prisma.installedIntegration.upsert({
+ where: {
+ userId_integrationId_projectId: {
+ userId: "user_cludszk1h0000wmd2e0ea2b0p",
+ integrationId: STRIPE_INTEGRATION_ID,
+ projectId: ACME_WORKSPACE_ID,
+ },
+ },
+ create: {
+ userId: "user_cludszk1h0000wmd2e0ea2b0p",
+ integrationId: STRIPE_INTEGRATION_ID,
+ projectId: ACME_WORKSPACE_ID,
+ settings: {
+ stripeMode: "sandbox",
+ },
+ },
+ update: {
+ //
+ },
+ });
+}
+
+main();