The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
wip
Kiran Kb552cff68eca
diff --git a/apps/web/app/api/cron/shopify/checkout-completed/route.ts b/apps/web/app/api/cron/shopify/checkout-completed/route.tsindex 9d0ed9649d..2b0409f6da 100644--- a/apps/web/app/api/cron/shopify/checkout-completed/route.ts+++ b/apps/web/app/api/cron/shopify/checkout-completed/route.ts@@ -4,7 +4,12 @@ import { createSaleData } from "@/lib/api/sales/sale";import { createId } from "@/lib/api/utils";import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import { generateRandomName } from "@/lib/names";-import { getClickEvent, recordLead, recordSale } from "@/lib/tinybird";+import {+ getClickEvent,+ getLeadEvent,+ recordLead,+ recordSale,+} from "@/lib/tinybird";import { redis } from "@/lib/upstash";import z from "@/lib/zod";import { prisma } from "@dub/prisma";@@ -19,18 +24,15 @@ const schema = z.object({});const checkoutSchema = z.object({- customer: z.object({- id: z.number(),- }), // TODO: Test this with guest checkouttotal_price: z.string(),currency: z.string(),confirmation_number: z.string(),+ workspaceId: z.string(),+ customer: z.object({+ id: z.number(),+ }),});-const workspace = {- id: "cl7pj5kq4006835rbjlt2ofka",-};-// POST /api/cron/shopify/checkout-completedexport async function POST(req: Request) {try {@@ -39,17 +41,13 @@ export async function POST(req: Request) {const { clickId, checkoutToken } = schema.parse(body);- // upstash-retried header- // console.log("Request headers", req.headers);-// Find click eventconst clickEvent = await getClickEvent({ clickId });if (!clickEvent || clickEvent.data.length === 0) {- throw new DubApiError({- code: "not_found",- message: `Click event not found for clickId: ${clickId}`,- });+ return new Response(+ `[Shopify] Click event not found for clickId: ${clickId}`,+ );}// Find Shopify order@@ -58,18 +56,21 @@ export async function POST(req: Request) {if (!order) {throw new DubApiError({code: "bad_request",- message: "Shopify order not found. Waiting for order...",+ message: "Shopify order not found. Waiting for order...", // This will be retried by Qstash});}const parsedOrder = checkoutSchema.parse(order);+ const workspaceId = parsedOrder.workspaceId;const customerExternalId = parsedOrder.customer.id.toString();- // Fetch or create customer+ console.log("parsedOrder", parsedOrder);++ // Fetch customerlet customer: Customer | null = await prisma.customer.findUnique({where: {projectId_externalId: {- projectId: workspace.id,+ projectId: workspaceId,externalId: customerExternalId,},},@@ -78,13 +79,17 @@ export async function POST(req: Request) {const clickData = clickEvent.data[0];const { link_id: linkId, country, timestamp } = clickData;+ // Handle the leadif (!customer) {+ // TODO:+ // Fetch customer from Shopify and use their email & name+customer = await prisma.customer.create({data: {id: createId({ prefix: "cus_" }),name: generateRandomName(),externalId: customerExternalId,- projectId: workspace.id,+ projectId: workspaceId,clickedAt: new Date(timestamp + "Z"),clickId,linkId,@@ -116,7 +121,7 @@ export async function POST(req: Request) {// update workspace usageprisma.project.update({where: {- id: workspace.id,+ id: workspaceId,},data: {usage: {@@ -127,27 +132,33 @@ export async function POST(req: Request) {]);}+ // Find lead+ const leadEvent = await getLeadEvent({ customerId: customer.id });+ if (!leadEvent || leadEvent.data.length === 0) {+ return `[Shopify] Lead event with customer ID ${customer.id} not found, skipping...`;+ }++ // Handle the saleconst eventId = nanoid(16);const amount = Number(parsedOrder.total_price) * 100;const currency = parsedOrder.currency;const invoiceId = parsedOrder.confirmation_number;const paymentProcessor = "shopify";+ const saleData = {+ ...leadEvent.data[0],+ event_id: nanoid(16),+ event_name: "Purchase",+ payment_processor: "shopify",+ amount,+ currency,+ invoice_id: invoiceId,+ metadata: JSON.stringify(parsedOrder),+ };const [_sale, link, _project] = await Promise.all([// record sale- recordSale({- ...clickData,- event_id: eventId,- event_name: "Purchase",- customer_id: customer.id,- payment_processor: paymentProcessor,- amount,- currency,- invoice_id: invoiceId,- metadata: JSON.stringify(parsedOrder),-- }),+ recordSale(saleData),// update link sales countprisma.link.update({@@ -167,7 +178,7 @@ export async function POST(req: Request) {// update workspace sales usageprisma.project.update({where: {- id: workspace.id,+ id: workspaceId,},data: {usage: {@@ -185,7 +196,7 @@ export async function POST(req: Request) {const { program, partner } =await prisma.programEnrollment.findUniqueOrThrow({where: {- linkId: link.id,+ linkId,},select: {program: true,@@ -199,8 +210,8 @@ export async function POST(req: Request) {const saleRecord = createSaleData({customerId: customer.id,- linkId: link.id,- clickId: clickData.click_id,+ linkId,+ clickId,invoiceId,eventId,paymentProcessor,@@ -235,7 +246,7 @@ export async function POST(req: Request) {await redis.del(`shopify:checkout:${checkoutToken}`);- return new Response("Shopify order tracked.", { status: 200 });+ return new Response("[Shopify] Order event processed successfully.");} catch (error) {return handleAndReturnErrorResponse(error);}diff --git a/apps/web/app/api/shopify/integration/webhook/order-paid.ts b/apps/web/app/api/shopify/integration/webhook/order-paid.tsindex 59b240e378..ff8360bae2 100644--- a/apps/web/app/api/shopify/integration/webhook/order-paid.ts+++ b/apps/web/app/api/shopify/integration/webhook/order-paid.ts@@ -4,7 +4,17 @@ import { redis } from "@/lib/upstash";// Instead of checkout_token, maybe use order_number or checkout_id// Add an expiry to the redis key-export async function orderPaid(event: any) {+export async function orderPaid({+ event,+ workspaceId,+}: {+ event: any;+ workspaceId: string;+}) {const checkoutToken = event.checkout_token;- await redis.set(`shopify:checkout:${checkoutToken}`, event);++ await redis.set(`shopify:checkout:${checkoutToken}`, {+ ...event,+ workspaceId,+ });}diff --git a/apps/web/app/api/shopify/integration/webhook/route.ts b/apps/web/app/api/shopify/integration/webhook/route.tsindex 1f8ce4c4b8..2d8c825999 100644--- a/apps/web/app/api/shopify/integration/webhook/route.ts+++ b/apps/web/app/api/shopify/integration/webhook/route.ts@@ -1,3 +1,4 @@+import { prisma } from "@dub/prisma";import { log } from "@dub/utils";import { NextResponse } from "next/server";import { orderPaid } from "./order-paid";@@ -8,24 +9,39 @@ const relevantTopics = new Set(["orders/paid"]);// POST /api/shopify/integration/webhook – Listen to Shopify webhook eventsexport const POST = async (req: Request) => {const body = await req.json();-- // Find the topic from the headersconst headers = req.headers;const topic = headers.get("x-shopify-topic") || "";const signature = headers.get("x-shopify-hmac-sha256") || "";+ const shop = headers.get("x-shopify-shop-domain") || "";await verifyShopifySignature({ body, signature });if (!relevantTopics.has(topic)) {- return new Response("Unsupported topic, skipping...", {- status: 200,- });+ return new Response(`[Shopify] Unsupported topic: ${topic}. Skipping...`);+ }++ const workspace = await prisma.project.findUnique({+ where: {+ shopifyStoreId: shop,+ },+ select: {+ id: true,+ },+ });++ if (!workspace) {+ return new Response(+ `[Shopify] Workspace not found for shop: ${shop}. Skipping...`,+ );}try {switch (topic) {case "orders/paid":- await orderPaid(body);+ await orderPaid({+ event: body,+ workspaceId: workspace.id,+ });break;}} catch (error) {@@ -34,9 +50,9 @@ export const POST = async (req: Request) => {type: "errors",});- return new Response('Webhook error: "Webhook handler failed. View logs."', {- status: 400,- });+ return new Response(+ `[Shopify] Webhook error: "Webhook handler failed. View logs."`,+ );}return NextResponse.json("OK");diff --git a/apps/web/app/api/track/shopify/route.ts b/apps/web/app/api/track/shopify/route.tsindex 0f2d128e91..3388727a1d 100644--- a/apps/web/app/api/track/shopify/route.ts+++ b/apps/web/app/api/track/shopify/route.ts@@ -15,8 +15,9 @@ const CORS_HEADERS = {// TODO:// Add rate limiting+// Finalize the endpoint (Maybe move to /api/shopify/track)-// POST /api/track/shopify – Track a Shopify event+// POST /api/track/shopify – Handle the Shopify Pixel eventsexport const POST = async (req: Request) => {try {const { clickId, checkoutToken } = await parseRequestBody(req);