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.

store the subscription info

Kiran Kcbf580bb9ce2
diff --git a/apps/web/app/api/campaigns/webhooks/stripe/checkout-session-completed.ts b/apps/web/app/api/campaigns/webhooks/stripe/checkout-session-completed.ts
index ff9dd0c33e..168eeae3cc 100644
--- a/apps/web/app/api/campaigns/webhooks/stripe/checkout-session-completed.ts
+++ b/apps/web/app/api/campaigns/webhooks/stripe/checkout-session-completed.ts
@@ -2,6 +2,7 @@ import { prisma } from "@/lib/prisma";
import { getLeadEvent, recordSale } from "@/lib/tinybird";
import { nanoid } from "@dub/utils";
import type Stripe from "stripe";
+import { retrieveSubscription } from "./subscription";
// Handle event "checkout.session.completed"
export async function checkoutSessionCompleted(event: Stripe.Event) {
@@ -9,6 +10,8 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
const externalId = charge.metadata?.dubCustomerId || null;
const stripeAccountId = event.account as string;
const stripeCustomerId = charge.customer as string;
+ const subscriptionId = charge.subscription as string;
+ const invoiceId = charge.invoice as string;
if (!externalId) {
return;
@@ -33,6 +36,9 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
return;
}
+ // Retrieve subscription if available
+ const subscription = await retrieveSubscription(subscriptionId);
+
// Record sale
await recordSale({
...leadEvent.data[0],
@@ -40,14 +46,12 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
payment_processor: "stripe",
amount: charge.amount_total!,
currency: charge.currency!,
+ invoice_id: invoiceId,
+ recurring: subscription?.recurring || 0,
+ product_id: subscription?.productId || "",
+ recurring_interval: subscription?.recurringInterval || "",
+ recurring_interval_count: subscription?.recurringIntervalCount || 0,
refunded: 0,
-
- // How do we get these?
- recurring: 0,
- product_id: "",
- recurring_interval: "month",
- recurring_interval_count: 1,
-
metadata: JSON.stringify({
charge,
}),
diff --git a/apps/web/app/api/campaigns/webhooks/stripe/invoice-paid.ts b/apps/web/app/api/campaigns/webhooks/stripe/invoice-paid.ts
index b2563cee16..5cadc06cee 100644
--- a/apps/web/app/api/campaigns/webhooks/stripe/invoice-paid.ts
+++ b/apps/web/app/api/campaigns/webhooks/stripe/invoice-paid.ts
@@ -2,12 +2,14 @@ import { prisma } from "@/lib/prisma";
import { getLeadEvent, recordSale } from "@/lib/tinybird";
import { nanoid } from "@dub/utils";
import type Stripe from "stripe";
+import { retrieveSubscription } from "./subscription";
// Handle event "invoice.paid"
export async function invoicePaid(event: Stripe.Event) {
const invoice = event.data.object as Stripe.Invoice;
const stripeAccountId = event.account as string;
const stripeCustomerId = invoice.customer as string;
+ const subscriptionId = invoice.subscription as string;
// Find customer
const customer = await prisma.customer.findFirst({
@@ -27,8 +29,8 @@ export async function invoicePaid(event: Stripe.Event) {
return;
}
- // Find the product from line items
- const stripeProductId = invoice.lines.data[0]?.plan?.product as string;
+ // Retrieve subscription if available
+ const subscription = await retrieveSubscription(subscriptionId);
// Record sale
await recordSale({
@@ -38,13 +40,11 @@ export async function invoicePaid(event: Stripe.Event) {
amount: invoice.amount_paid,
currency: invoice.currency,
refunded: 0,
-
- // How do we get these?
- recurring: 0,
- product_id: stripeProductId,
- recurring_interval: "month",
- recurring_interval_count: 1,
-
+ invoice_id: invoice.id,
+ recurring: subscription?.recurring || 0,
+ product_id: subscription?.productId || "",
+ recurring_interval: subscription?.recurringInterval || "",
+ recurring_interval_count: subscription?.recurringIntervalCount || 0,
metadata: JSON.stringify({
invoice,
}),
diff --git a/apps/web/app/api/campaigns/webhooks/stripe/subscription.ts b/apps/web/app/api/campaigns/webhooks/stripe/subscription.ts
new file mode 100644
index 0000000000..3584f0c324
--- /dev/null
+++ b/apps/web/app/api/campaigns/webhooks/stripe/subscription.ts
@@ -0,0 +1,21 @@
+import { stripe } from "@/lib/stripe";
+
+export const retrieveSubscription = async (subscriptionId: string) => {
+ try {
+ const subscription = await stripe.subscriptions.retrieve(subscriptionId);
+
+ // TODO:
+ // What if there are multiple items in the subscription?
+
+ const price = subscription.items.data[0].price;
+
+ return {
+ productId: price.product as string,
+ recurring: price.type === "recurring" ? 1 : 0,
+ recurringInterval: price.recurring?.interval as string,
+ recurringIntervalCount: price.recurring?.interval_count as number,
+ };
+ } catch (error) {
+ return null;
+ }
+};
diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.ts
index cfc059c4a0..38ddbd7320 100644
--- a/apps/web/app/api/track/sale/route.ts
+++ b/apps/web/app/api/track/sale/route.ts
@@ -1,7 +1,8 @@
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";
+import { prismaEdge } from "@/lib/prisma/edge";
import { getLeadEvent, recordSale } from "@/lib/tinybird";
-import { clickEventSchemaTB, trackSaleRequestSchema } from "@/lib/zod/schemas";
+import { trackSaleRequestSchema } from "@/lib/zod/schemas";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -10,9 +11,9 @@ export const runtime = "edge";
// POST /api/track/sale – Track a sale conversion event
export const POST = withWorkspaceEdge(
- async ({ req }) => {
+ async ({ req, workspace }) => {
const {
- customerId,
+ customerId: externalId,
paymentProcessor,
productId,
invoiceId,
@@ -27,23 +28,37 @@ export const POST = withWorkspaceEdge(
waitUntil(
(async () => {
- const leadEvent = await getLeadEvent({ customerId });
+ // Find customer
+ const customer = await prismaEdge.customer.findUnique({
+ where: {
+ projectId_externalId: {
+ projectId: workspace.id,
+ externalId,
+ },
+ },
+ });
+
+ if (!customer) {
+ console.log("No customer found for externalId:", externalId);
+ return;
+ }
+ // Find lead
+ const leadEvent = await getLeadEvent({ customerId: customer.id });
if (!leadEvent || leadEvent.data.length === 0) {
- console.log("No lead event found for customer_id:", customerId);
+ console.log("No lead event found for customerId:", customer.id);
return;
}
- const clickData = clickEventSchemaTB
- .omit({ timestamp: true })
- .parse(leadEvent.data[0]);
+ // const clickData = clickEventSchemaTB
+ // .omit({ timestamp: true })
+ // .parse(leadEvent.data[0]);
await recordSale({
- ...clickData,
- customer_id: customerId,
+ ...leadEvent.data[0],
event_id: nanoid(16),
payment_processor: paymentProcessor,
- product_id: productId,
+ product_id: productId || "",
invoice_id: invoiceId,
amount,
currency,
diff --git a/apps/web/lib/zod/schemas/sales.ts b/apps/web/lib/zod/schemas/sales.ts
index d837efdd9f..fcbc0330c6 100644
--- a/apps/web/lib/zod/schemas/sales.ts
+++ b/apps/web/lib/zod/schemas/sales.ts
@@ -4,7 +4,7 @@ import { clickEventSchemaTB } from "./clicks";
export const trackSaleRequestSchema = z.object({
customerId: z.string(),
paymentProcessor: z.enum(["stripe", "shopify", "paddle"]),
- productId: z.string(),
+ productId: z.string().nullable(),
invoiceId: z.string(),
amount: z.number().int().positive().default(0),
currency: z.string().default("usd"),
@@ -22,14 +22,14 @@ export const saleEventSchemaTB = clickEventSchemaTB
event_id: z.string(),
customer_id: z.string(),
payment_processor: z.string(),
- product_id: z.string().default(""),
- invoice_id: z.string().default(""),
- amount: z.number().int().positive(),
+ product_id: z.string(),
+ invoice_id: z.string(),
+ amount: z.number(),
currency: z.string(),
recurring: z.number(),
recurring_interval: z.string(),
- recurring_interval_count: z.number().int().positive(),
- refunded: z.number().default(0),
- metadata: z.string().default(""),
+ recurring_interval_count: z.number(),
+ refunded: z.number(),
+ metadata: z.string(),
}),
);
diff --git a/packages/tinybird/endpoints/get_lead_event.pipe b/packages/tinybird/endpoints/get_lead_event.pipe
index d04285c643..71518ac2a6 100644
--- a/packages/tinybird/endpoints/get_lead_event.pipe
+++ b/packages/tinybird/endpoints/get_lead_event.pipe
@@ -8,4 +8,6 @@ DESCRIPTION >
undefined
SQL >
- % SELECT * FROM dub_lead_events WHERE customer_id = {{ customer_id }} LIMIT 1
\ No newline at end of file
+ % SELECT * FROM dub_lead_events WHERE customer_id = {{ customerId }} LIMIT 1
+
+
\ No newline at end of file