The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Track Shopify orders via click, existing lead, or discount code
Kiran Kd5749015805a
diff --git a/apps/web/app/(ee)/api/cron/shopify/order-paid/route.ts b/apps/web/app/(ee)/api/cron/shopify/order-paid/route.tsindex b041889541..f2dc899168 100644--- a/apps/web/app/(ee)/api/cron/shopify/order-paid/route.ts+++ b/apps/web/app/(ee)/api/cron/shopify/order-paid/route.ts@@ -1,8 +1,10 @@-import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";-import { processOrder } from "@/lib/integrations/shopify/process-order";+import { DubApiError } from "@/lib/api/errors";+import { withCron } from "@/lib/cron/with-cron";+import { shopifyOrderSchema } from "@/lib/integrations/shopify/schema";+import { processShopifyOrderJob } from "@/lib/jobs/handlers/process-shopify-order-job";import { redis } from "@/lib/upstash";import * as z from "zod/v4";+import { logAndRespond } from "../../utils";export const dynamic = "force-dynamic";@@ -11,61 +13,60 @@ const schema = z.object({checkoutToken: z.string(),});-// POST /api/cron/shopify/order-paid-export async function POST(req: Request) {- try {- const rawBody = await req.text();- await verifyQstashSignature({ req, rawBody });+// Matches the old qstash.publishJSON({ retries: 5 }) for this route.+const MAX_PIXEL_WAIT_RETRIES = 5;- const { workspaceId, checkoutToken } = schema.parse(JSON.parse(rawBody));+// Cutover shim: drains in-flight QStash messages with the old+// { workspaceId, checkoutToken } body.- // Find Shopify order- const event = await redis.hget(- `shopify:checkout:${checkoutToken}`,- "order",- );+// POST /api/cron/shopify/order-paid+export const POST = withCron(async ({ req, rawBody }) => {+ const { workspaceId, checkoutToken } = schema.parse(JSON.parse(rawBody));- if (!event) {- return new Response(- `[Shopify] Order with checkout token ${checkoutToken} not found. Skipping...`,- );- }+ // Find Shopify order+ const event = await redis.hget(`shopify:checkout:${checkoutToken}`, "order");- const clickId = await redis.hget<string>(- `shopify:checkout:${checkoutToken}`,- "clickId",+ if (!event) {+ return logAndRespond(+ `[Shopify] Order with checkout token ${checkoutToken} not found. Skipping...`,);+ }++ const clickId = await redis.hget<string>(+ `shopify:checkout:${checkoutToken}`,+ "clickId",+ );- // clickId is empty, order is not from a Dub link- if (clickId === "") {- // set key to expire in 24 hours- await redis.expire(`shopify:checkout:${checkoutToken}`, 60 * 60 * 24);+ // clickId is empty, order is not from a Dub link+ if (clickId === "") {+ await redis.del(`shopify:checkout:${checkoutToken}`);+ return logAndRespond(`[Shopify] Order is not from a Dub link. Skipping...`);+ }- return new Response(- `[Shopify] Order is not from a Dub link. Skipping...`,- );- }+ // clickId is found, process the order for the new customer+ if (clickId) {+ await processShopifyOrderJob.execute({+ workspaceId,+ clickId,+ order: shopifyOrderSchema.parse(event),+ });- // clickId is found, process the order for the new customer- else if (clickId) {- await processOrder({- event,- workspaceId,- clickId,- });+ return logAndRespond("[Shopify] Order event processed successfully.");+ }- return new Response("[Shopify] Order event processed successfully.");- }+ const retried = Number(req.headers.get("Upstash-Retried") ?? "0");- // Wait for the click event to come from Shopify pixel- else {- throw new DubApiError({- code: "bad_request",- message:- "[Shopify] Click event not found. Waiting for Shopify pixel event...",- });- }- } catch (error) {- return handleAndReturnErrorResponse(error);+ // Give up waiting for the pixel after a few QStash attempts (2xx stops retries)+ if (retried >= MAX_PIXEL_WAIT_RETRIES) {+ return logAndRespond(+ `[Shopify] Click event not found after ${retried} retries for checkout ${checkoutToken}. Skipping...`,+ );}-}++ // Wait for the click event to come from Shopify pixel+ throw new DubApiError({+ code: "bad_request",+ message:+ "[Shopify] Click event not found. Waiting for Shopify pixel event...",+ });+});diff --git a/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts b/apps/web/app/(ee)/api/shopify/integration/webhook/route.tsindex 362ae75131..a9ad369d10 100644--- a/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts+++ b/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts@@ -132,14 +132,17 @@ export const POST = async (req: Request) => {return response;}- waitUntil(- captureWebhookLog({- ...requestLog,- statusCode: 200,- duration: Date.now() - startTime,- responseBody: response,- }),- );+ // orders/paid is logged by processShopifyOrderJob after the order is processed+ if (topic !== "orders/paid") {+ waitUntil(+ captureWebhookLog({+ ...requestLog,+ statusCode: 200,+ duration: Date.now() - startTime,+ responseBody: response,+ }),+ );+ }return new Response(response);};diff --git a/apps/web/app/(ee)/api/shopify/pixel/route.ts b/apps/web/app/(ee)/api/shopify/pixel/route.tsindex b69053866a..11926b6e3b 100644--- a/apps/web/app/(ee)/api/shopify/pixel/route.ts+++ b/apps/web/app/(ee)/api/shopify/pixel/route.ts@@ -39,7 +39,7 @@ export const POST = async (req: Request) => {const clickEvent = await getClickEvent({ clickId });if (!clickEvent) {- clickId = null;+ clickId = undefined;}}@@ -47,9 +47,7 @@ export const POST = async (req: Request) => {(async () => {const checkout = await writeShopifyCheckoutFields({checkoutToken,- fields: {- clickId,- },+ fields: clickId ? { clickId } : {},});await tryDispatchShopifyOrderJob({diff --git a/apps/web/lib/integrations/shopify/attribute-via-discount-code.ts b/apps/web/lib/integrations/shopify/attribute-via-discount-code.tsnew file mode 100644index 0000000000..fe07a4f1f4--- /dev/null+++ b/apps/web/lib/integrations/shopify/attribute-via-discount-code.ts@@ -0,0 +1,171 @@+import { createId } from "@/lib/api/create-id";+import { includeTags } from "@/lib/api/links/include-tags";+import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";+import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";+import { generateRandomName } from "@/lib/names";+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";+import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";+import { prisma } from "@/lib/prisma";+import { recordLead } from "@/lib/tinybird";+import { recordFakeClick } from "@/lib/tinybird/record-fake-click";+import { WorkspaceProps } from "@/lib/types";+import { sendWorkspaceWebhook } from "@/lib/webhook/publish";+import { transformLeadEventData } from "@/lib/webhook/transform";+import { COUNTRIES_TO_CONTINENTS, nanoid } from "@dub/utils";+import { Link } from "@prisma/client";+import { ShopifyOrder } from "./schema";++export async function attributeViaDiscountCode({+ order,+ workspace,+ link,+}: {+ order: ShopifyOrder;+ workspace: Pick<WorkspaceProps, "id" | "defaultProgramId" | "webhookEnabled">;+ link: Link;+}) {+ const { customer: orderCustomer, billing_address: billingAddress } = order;++ const billingAddressCountry = billingAddress?.country_code?.toUpperCase();++ const customerId = createId({ prefix: "cus_" });+ const clickId = nanoid(16);++ // Create the customer before recording the fake click so a P2002 on+ // projectId_externalId never leaves an orphaned Tinybird click behind.+ const customer = await prisma.customer.create({+ data: {+ id: customerId,+ name: orderCustomer+ ? `${orderCustomer.first_name} ${orderCustomer.last_name}`.trim()+ : generateRandomName(),+ email: orderCustomer?.email,+ externalId: orderCustomer?.id?.toString() || customerId,+ linkId: link.id,+ clickId,+ clickedAt: new Date(),+ country: billingAddress?.country_code,+ projectId: workspace.id,+ programId: link.programId,+ partnerId: link.partnerId,+ },+ });++ // Record a fake click for this event+ const clickEvent = await recordFakeClick({+ link,+ clickId,+ customer: {+ continent: billingAddressCountry+ ? COUNTRIES_TO_CONTINENTS[billingAddressCountry] ?? "Unknown"+ : "Unknown",+ country: billingAddressCountry ?? "Unknown",+ region: billingAddress?.province ?? "Unknown",+ },+ });++ // Prepare the payload for the lead event+ const { timestamp, ...rest } = clickEvent;++ const leadEvent = {+ ...rest,+ workspace_id: clickEvent.workspace_id || customer.projectId, // in case for some reason the click event doesn't have workspace_id+ event_id: nanoid(16),+ event_name: "Checkout with discount code",+ customer_id: customer.id,+ metadata: "",+ };++ await recordLead(leadEvent);++ const linkUpdated = await prisma.link.update({+ where: {+ id: link.id,+ },+ data: {+ leads: {+ increment: 1,+ },+ lastLeadAt: new Date(),+ },+ include: includeTags,+ });++ let result:+ | Awaited<ReturnType<typeof queuePartnerCommissionCreation>>+ | undefined = undefined;++ if (link.programId && link.partnerId) {+ result = await queuePartnerCommissionCreation({+ event: "lead",+ programId: link.programId,+ partnerId: link.partnerId,+ linkId: link.id,+ eventId: leadEvent.event_id,+ customerId: customer.id,+ quantity: 1,+ context: {+ customer: {+ country: customer.country,+ },+ },+ });++ await Promise.allSettled([+ executeWorkflows({+ event: "leadRecorded",+ identity: {+ workspaceId: workspace.id,+ programId: link.programId,+ partnerId: link.partnerId,+ },+ metrics: {+ current: {+ leads: 1,+ },+ },+ }),++ syncPartnerLinksStats({+ partnerId: link.partnerId,+ programId: link.programId,+ eventType: "lead",+ }),+ ]);+ }++ await Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "lead.created",+ workspace,+ data: transformLeadEventData({+ ...clickEvent,+ eventName: "Checkout with discount code",+ link: linkUpdated,+ customer,+ partner: result?.webhookPartner,+ metadata: null,+ }),+ }),++ ...(link.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "lead.created",+ data: {+ ...leadEvent,+ eventName: "Checkout with discount code",+ link: linkUpdated,+ customer,+ },+ }),+ ]+ : []),+ ]);++ return {+ customer,+ leadEvent,+ };+}diff --git a/apps/web/lib/integrations/shopify/checkout-cache.ts b/apps/web/lib/integrations/shopify/checkout-cache.tsindex e8772fc8cb..66c0143327 100644--- a/apps/web/lib/integrations/shopify/checkout-cache.ts+++ b/apps/web/lib/integrations/shopify/checkout-cache.ts@@ -7,7 +7,10 @@ const SHOPIFY_CHECKOUT_CACHE_TTL_SECONDS = 60 * 60 * 24; // 24 hoursconst SHOPIFY_CHECKOUT_CACHE_KEY_PREFIX = "shopify:checkout:";const shopifyCheckoutCacheSchema = z.object({- clickId: z.string().optional(),+ clickId: z+ .string()+ .nullish()+ .transform((value) => value ?? undefined),workspaceId: z.string().optional(),order: shopifyOrderSchema.optional(),dispatched: z.boolean().optional(),@@ -24,19 +27,19 @@ export async function writeShopifyCheckoutFields({fields,}: {checkoutToken: string;- fields: Record<string, unknown>;+ fields: Partial<ShopifyCheckoutCache>;}) {const key = shopifyCheckoutCacheKey(checkoutToken);const pipeline = redis.pipeline();pipeline.hset(key, fields);pipeline.expire(key, SHOPIFY_CHECKOUT_CACHE_TTL_SECONDS);- pipeline.hgetall<ShopifyCheckoutCache>(key);+ pipeline.hgetall(key);const results = await pipeline.exec();- const cache = results[2] as ShopifyCheckoutCache | null;+ const parsed = shopifyCheckoutCacheSchema.safeParse(results[2]);- return cache ?? {};+ return parsed.success ? parsed.data : {};}export async function tryDispatchShopifyOrderJob({diff --git a/apps/web/lib/integrations/shopify/create-lead.ts b/apps/web/lib/integrations/shopify/create-lead.tsindex 84886ffd94..ddee4b1a47 100644--- a/apps/web/lib/integrations/shopify/create-lead.ts+++ b/apps/web/lib/integrations/shopify/create-lead.ts@@ -1,5 +1,4 @@import { createId } from "@/lib/api/create-id";-import { DubApiError } from "@/lib/api/errors";import { includeTags } from "@/lib/api/links/include-tags";import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";import { generateRandomName } from "@/lib/names";@@ -13,18 +12,19 @@ import { nanoid } from "@dub/utils";import { EventType } from "@prisma/client";import { waitUntil } from "@vercel/functions";import { queueGoogleAdsConversionUpload } from "../google-ads/upload-conversion";-import { shopifyOrderSchema } from "./schema";+import { ShopifyError } from "./error";+import { ShopifyOrder } from "./schema";export async function createShopifyLead({+ order,clickId,workspaceId,- event,}: {+ order: ShopifyOrder;clickId: string;workspaceId: string;- event: any;}) {- const { customer: orderCustomer } = shopifyOrderSchema.parse(event);+ const { customer: orderCustomer } = order;const customerId = createId({ prefix: "cus_" });/*@@ -42,10 +42,7 @@ export async function createShopifyLead({const clickData = await getClickEvent({ clickId });if (!clickData) {- throw new DubApiError({- code: "not_found",- message: `Click event not found for clickId: ${clickId}`,- });+ throw new ShopifyError("Click event not found. Skipping the order...");}const { link_id: linkId, country, timestamp } = clickData;@@ -58,14 +55,18 @@ export async function createShopifyLead({id: true,programId: true,partnerId: true,+ disabledAt: true,},});if (!partnerLink) {- throw new DubApiError({- code: "not_found",- message: `Link not found for linkId: ${linkId}`,- });+ throw new ShopifyError(+ "Link not found in your workspace. Skipping the order...",+ );+ }++ if (partnerLink.disabledAt) {+ throw new ShopifyError("Link is disabled. Skipping the order...");}// create customer@@ -85,13 +86,16 @@ export async function createShopifyLead({},});- const eventName = "Account created";+ const leadEvent = {+ id: nanoid(16),+ name: "Account created",+ };const leadData = leadEventSchemaTB.parse({...clickData,workspace_id: clickData.workspace_id || customer.projectId, // in case for some reason the click event doesn't have workspace_id- event_id: nanoid(16),- event_name: eventName,+ event_id: leadEvent.id,+ event_name: leadEvent.name,customer_id: customer.id,});@@ -133,7 +137,7 @@ export async function createShopifyLead({workspace,data: transformLeadEventData({...clickData,- eventName,+ eventName: leadEvent.name,link,customer,metadata: null,@@ -160,7 +164,7 @@ export async function createShopifyLead({event: "lead.created",data: {...clickData,- eventName,+ eventName: leadEvent.name,link,customer,},@@ -189,5 +193,7 @@ export async function createShopifyLead({]),);- return leadData;+ return {+ leadData,+ };}diff --git a/apps/web/lib/integrations/shopify/create-sale.ts b/apps/web/lib/integrations/shopify/create-sale.tsindex d9f901eff5..06874f7439 100644--- a/apps/web/lib/integrations/shopify/create-sale.ts+++ b/apps/web/lib/integrations/shopify/create-sale.ts@@ -12,21 +12,20 @@ import { sendWorkspaceWebhook } from "@/lib/webhook/publish";import { transformSaleEventData } from "@/lib/webhook/transform";import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";-import { shopifyOrderSchema } from "./schema";+import { ShopifyError } from "./error";+import { ShopifyOrder } from "./schema";export async function createShopifySale({- event,+ order,customerId,workspaceId,leadData,}: {- event: any;+ order: ShopifyOrder;customerId: string;workspaceId: string;leadData: LeadEventTB;}) {- const order = shopifyOrderSchema.parse(event);-const {checkout_token: checkoutToken,confirmation_number: invoiceId,@@ -48,14 +47,14 @@ export async function createShopifySale({);if (!ok) {- return new Response(- `[Shopify] Order has been processed already. Skipping...`,+ throw new ShopifyError(+ "Sale event for this order has been processed already. Skipping the order...",);}const saleData = {...leadData,- workspace_id: leadData.workspace_id || workspaceId, // in case for some reason the lead event doesn't have workspace_id+ workspace_id: workspaceId,event_id: nanoid(16),event_name: "Purchase",payment_processor: "shopify",@@ -222,4 +221,8 @@ export async function createShopifySale({: []),]),);++ return {+ saleData,+ };}diff --git a/apps/web/lib/integrations/shopify/error.ts b/apps/web/lib/integrations/shopify/error.tsnew file mode 100644index 0000000000..8db81b1f4d--- /dev/null+++ b/apps/web/lib/integrations/shopify/error.ts@@ -0,0 +1,14 @@+export class ShopifyError extends Error {+ readonly data: Record<string, string> | null;++ constructor(message: string, data: Record<string, string> | null = null) {+ super(message);+ this.name = "ShopifyError";+ this.data = data;+ Object.setPrototypeOf(this, new.target.prototype);+ }+}++export function isShopifyError(error: unknown): error is ShopifyError {+ return error instanceof ShopifyError;+}diff --git a/apps/web/lib/integrations/shopify/process-order.ts b/apps/web/lib/integrations/shopify/process-order.tsindex 7cea0eb838..a8455d81fc 100644--- a/apps/web/lib/integrations/shopify/process-order.ts+++ b/apps/web/lib/integrations/shopify/process-order.ts@@ -1,246 +1,140 @@-import { createId } from "@/lib/api/create-id";-import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { includeTags } from "@/lib/api/links/include-tags";-import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";-import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";-import { generateRandomName } from "@/lib/names";-import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";-import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";import { prisma } from "@/lib/prisma";-import { getLeadEvent, recordLead } from "@/lib/tinybird";-import { recordFakeClick } from "@/lib/tinybird/record-fake-click";+import { getLeadEvent } from "@/lib/tinybird";import { WorkspaceProps } from "@/lib/types";-import { sendWorkspaceWebhook } from "@/lib/webhook/publish";-import { transformLeadEventData } from "@/lib/webhook/transform";-import { COUNTRIES_TO_CONTINENTS, nanoid } from "@dub/utils";-import { EventType, Link } from "@prisma/client";-import { waitUntil } from "@vercel/functions";-import { queueGoogleAdsConversionUpload } from "../google-ads/upload-conversion";+import { attributeViaDiscountCode } from "./attribute-via-discount-code";import { createShopifyLead } from "./create-lead";import { createShopifySale } from "./create-sale";-import { orderSchema, ShopifyOrder } from "./schema";+import { ShopifyOrder } from "./schema";// Process the order from Shopify webhook-export async function processOrder({- event,- workspaceId,- customerId,+export async function processShopifyOrder({+ order,+ workspace,clickId,}: {- event: ShopifyOrder;- workspaceId: string;- customerId?: string; // ID of the customer in Dub- clickId?: string; // ID of the click event from Shopify pixel+ order: ShopifyOrder;+ workspace: Pick<WorkspaceProps, "id" | "defaultProgramId" | "webhookEnabled">;+ clickId: string | null; // ID of the click event from Shopify pixel}) {- try {- // for existing customer- if (customerId) {- const leadEvent = await getLeadEvent({ customerId });+ const { customer: orderCustomer, discount_codes: discountCodes } = order;+ const sharedData = {+ checkoutToken: order.checkout_token,+ shopifyCustomerId: orderCustomer?.id,+ };- if (!leadEvent) {- return new Response(- `[Shopify] Lead event with customer ID ${customerId} not found, skipping...`,- );- }+ // Check customer exists in the workspace+ if (orderCustomer) {+ const externalId = orderCustomer.id?.toString();- await createShopifySale({- leadData: leadEvent,- event,- workspaceId,- customerId,- });-- return;- }+ const customer = await prisma.customer.findUnique({+ where: {+ projectId_externalId: {+ projectId: workspace.id,+ externalId,+ },+ },+ });- // for new customer- if (clickId) {- const leadData = await createShopifyLead({- clickId,- workspaceId,- event,+ // Existing customer found+ if (customer) {+ const leadData = await getLeadEvent({+ customerId: customer.id,});- const { customer_id: customerId } = leadData;+ if (!leadData) {+ // Not a skip — we cannot tell "no lead" from "Tinybird unavailable".+ // Throw so the job retries rather than creating a duplicate customer.+ throw new Error(+ `Lead event not found for customer ${customer.id}; refusing to re-attribute.`,+ );+ }- await createShopifySale({+ const { saleData } = await createShopifySale({leadData,- event,- workspaceId,- customerId,+ order,+ workspaceId: workspace.id,+ customerId: customer.id,});- return;+ return {+ message: "Sale has been tracked for this order.",+ data: {+ ...sharedData,+ eventId: saleData.event_id,+ customerId: customer.id,+ attribution: "existing_lead",+ },+ };}- } catch (error) {- return handleAndReturnErrorResponse(error);}-}--export async function attributeViaDiscountCode({- event,- workspace,- link,-}: {- event: unknown;- workspace: Pick<WorkspaceProps, "id" | "defaultProgramId" | "webhookEnabled">;- link: Link;-}) {- const { customer: orderCustomer, billing_address: billingAddress } =- orderSchema.parse(event);-- const billingAddressCountry = billingAddress?.country_code?.toUpperCase();- // Record a fake click for this event- const clickEvent = await recordFakeClick({- link,- customer: {- continent: billingAddressCountry- ? COUNTRIES_TO_CONTINENTS[billingAddressCountry] ?? "Unknown"- : "Unknown",- country: billingAddressCountry ?? "Unknown",- region: billingAddress?.province ?? "Unknown",- },- });-- const customerId = createId({ prefix: "cus_" });- const customer = await prisma.customer.create({- data: {- id: customerId,- name: orderCustomer- ? `${orderCustomer.first_name} ${orderCustomer.last_name}`.trim()- : generateRandomName(),- email: orderCustomer?.email,- externalId: orderCustomer?.id?.toString() || customerId,- linkId: clickEvent.link_id,- clickId: clickEvent.click_id,- clickedAt: new Date(clickEvent.timestamp + "Z"),- country: billingAddress?.country_code,- projectId: workspace.id,- programId: link.programId,- partnerId: link.partnerId,- },- });-- // Prepare the payload for the lead event- const { timestamp, ...rest } = clickEvent;-- const leadEvent = {- ...rest,- workspace_id: clickEvent.workspace_id || customer.projectId, // in case for some reason the click event doesn't have workspace_id- event_id: nanoid(16),- event_name: "Checkout with discount code",- customer_id: customer.id,- metadata: "",- };-- await recordLead(leadEvent);+ // New customer+ if (clickId) {+ const { leadData } = await createShopifyLead({+ order,+ clickId,+ workspaceId: workspace.id,+ });++ const { saleData } = await createShopifySale({+ leadData,+ order,+ workspaceId: workspace.id,+ customerId: leadData.customer_id,+ });++ return {+ message: "Sale has been tracked for this order.",+ data: {+ ...sharedData,+ eventId: saleData.event_id,+ customerId: leadData.customer_id,+ attribution: "click",+ },+ };+ }- waitUntil(- (async () => {- const linkUpdated = await prisma.link.update({- where: {- id: link.id,+ // Check if the order has created using a program discount code+ if (discountCodes && discountCodes.length > 0 && workspace.defaultProgramId) {+ const programDiscountCodes = await prisma.discountCode.findMany({+ where: {+ programId: workspace.defaultProgramId,+ code: {+ in: discountCodes.map(({ code }) => code),},- data: {- leads: {- increment: 1,- },- lastLeadAt: new Date(),- },- include: includeTags,+ },+ include: {+ link: true,+ },+ orderBy: {+ createdAt: "desc",+ },+ });++ if (programDiscountCodes.length > 0) {+ const { leadEvent: leadData } = await attributeViaDiscountCode({+ order,+ workspace,+ link: programDiscountCodes[0].link,});- let result:- | Awaited<ReturnType<typeof queuePartnerCommissionCreation>>- | undefined = undefined;-- if (link.programId && link.partnerId) {- result = await queuePartnerCommissionCreation({- event: "lead",- programId: link.programId,- partnerId: link.partnerId,- linkId: link.id,- eventId: leadEvent.event_id,- customerId: customer.id,- quantity: 1,- context: {- customer: {- country: customer.country,- },- },- });-- await Promise.allSettled([- executeWorkflows({- event: "leadRecorded",- identity: {- workspaceId: workspace.id,- programId: link.programId,- partnerId: link.partnerId,- },- metrics: {- current: {- leads: 1,- },- },- }),-- syncPartnerLinksStats({- partnerId: link.partnerId,- programId: link.programId,- eventType: "lead",- }),- ]);- }-- await Promise.allSettled([- sendWorkspaceWebhook({- trigger: "lead.created",- workspace,- data: transformLeadEventData({- ...clickEvent,- eventName: "Checkout with discount code",- link: linkUpdated,- customer,- partner: result?.webhookPartner,- metadata: null,- }),- }),-- queueGoogleAdsConversionUpload({- workspaceId: workspace.id,- eventType: EventType.lead,- eventId: leadEvent.event_id,- eventName: leadEvent.event_name,- conversionDateTime: new Date().toISOString(),- conversionCount: 1,- click: {- id: leadEvent.click_id,- url: leadEvent.url,- },- }),-- ...(link.partnerId- ? [- sendPartnerPostback({- partnerId: link.partnerId,- event: "lead.created",- data: {- ...leadEvent,- eventName: "Checkout with discount code",- link: linkUpdated,- customer,- },- }),- ]- : []),- ]);- })(),- );+ const { saleData } = await createShopifySale({+ leadData,+ order,+ workspaceId: workspace.id,+ customerId: leadData.customer_id,+ });- return {- customer,- leadEvent,- };+ return {+ message: "Sale has been tracked for this order.",+ data: {+ ...sharedData,+ eventId: saleData.event_id,+ customerId: leadData.customer_id,+ discountCode: programDiscountCodes[0].code,+ attribution: "discount_code",+ },+ };+ }+ }}diff --git a/apps/web/lib/integrations/shopify/schema.ts b/apps/web/lib/integrations/shopify/schema.tsindex 726cec6b4b..7990b9a612 100644--- a/apps/web/lib/integrations/shopify/schema.ts+++ b/apps/web/lib/integrations/shopify/schema.ts@@ -5,7 +5,7 @@ export const shopifyOrderSchema = z.object({checkout_token: z.string(),customer: z.object({- id: z.number(),+ id: z.union([z.number(), z.string()]),email: z.string().nullish(),first_name: z.string().nullish(),last_name: z.string().nullish(),diff --git a/apps/web/lib/jobs/handlers/process-shopify-order-job.ts b/apps/web/lib/jobs/handlers/process-shopify-order-job.tsindex bac56dfade..16f9a7827d 100644--- a/apps/web/lib/jobs/handlers/process-shopify-order-job.ts+++ b/apps/web/lib/jobs/handlers/process-shopify-order-job.ts@@ -1,9 +1,14 @@-import { orderSchema } from "@/lib/integrations/shopify/schema";+import { captureWebhookLog } from "@/lib/api-logs/capture-webhook-log";+import { processShopifyOrder } from "@/lib/integrations/shopify/process-order";+import { shopifyOrderSchema } from "@/lib/integrations/shopify/schema";+import { prisma } from "@/lib/prisma";+import { serializeError } from "@dub/utils";+import { waitUntil } from "@vercel/functions";import * as z from "zod/v4";import { defineJob } from "../index";const inputSchema = z.object({- order: orderSchema,+ order: shopifyOrderSchema,clickId: z.string().nullable(),workspaceId: z.string(),});@@ -12,7 +17,52 @@ const inputSchema = z.object({export const processShopifyOrderJob = defineJob({name: "process-shopify-order-job",schema: inputSchema,- async handle(input) {- const { workspaceId, clickId, order } = input;+ async handle({ workspaceId, clickId, order }) {+ const startTime = Date.now();++ const workspace = await prisma.project.findUniqueOrThrow({+ where: {+ id: workspaceId,+ },+ select: {+ id: true,+ defaultProgramId: true,+ webhookEnabled: true,+ },+ });++ const requestLog = {+ workspaceId: workspace.id,+ method: "POST",+ path: "/shopify/integration/webhook" as const,+ requestBody: order,+ userAgent: "Shopify Order Job",+ };++ try {+ const result = await processShopifyOrder({+ order,+ workspace,+ clickId,+ });++ waitUntil(+ captureWebhookLog({+ ...requestLog,+ statusCode: 200,+ duration: Date.now() - startTime,+ responseBody: result,+ }),+ );+ } catch (error) {+ waitUntil(+ captureWebhookLog({+ ...requestLog,+ statusCode: 400,+ duration: Date.now() - startTime,+ responseBody: serializeError(error),+ }),+ );+ }},});diff --git a/apps/web/lib/tinybird/record-fake-click.ts b/apps/web/lib/tinybird/record-fake-click.tsindex 76464382dd..30994d55e3 100644--- a/apps/web/lib/tinybird/record-fake-click.ts+++ b/apps/web/lib/tinybird/record-fake-click.ts@@ -25,6 +25,7 @@ export async function recordFakeClick({link,customer,timestamp,+ clickId,}: {link: Pick<Link, "id" | "url" | "domain" | "key" | "projectId">;customer?: {@@ -33,6 +34,7 @@ export async function recordFakeClick({continent?: string | null;};timestamp?: string | number;+ clickId?: string;}) {const dummyRequest = new Request(link.url, {headers: new Headers({@@ -46,7 +48,7 @@ export async function recordFakeClick({const clickData = await recordClick({req: dummyRequest,- clickId: nanoid(16),+ clickId: clickId ?? nanoid(16),workspaceId: link.projectId!,linkId: link.id,domain: link.domain,diff --git a/apps/web/playwright/api/shopify/helpers.ts b/apps/web/playwright/api/shopify/helpers.tsindex 9c1abb2402..489b073b71 100644--- a/apps/web/playwright/api/shopify/helpers.ts+++ b/apps/web/playwright/api/shopify/helpers.ts@@ -1,33 +1,37 @@+import { createId } from "@/lib/api/create-id";+import { prisma } from "@/lib/prisma";+import { redis } from "@/lib/upstash";import { nanoid } from "@dub/utils";+import { expect } from "@playwright/test";+import { DiscountProvider, EventType, RewardStructure } from "@prisma/client";import { createHmac } from "crypto";+import { randomName, randomPartnerEmail } from "../../utils";import { PLAYWRIGHT_API_BASE } from "../constants";+import type { ApiClient } from "../fixtures";+import { deletePartner } from "../partners/helpers";import { TEST_WORKSPACE } from "../setup-test-workspace";-export function shopifyCheckoutToken() {- return `pw_checkout_${nanoid(24)}`;-}--export function shopifyClickId() {- return `pw_click_${nanoid(16)}`;-}+export const SHOPIFY_ORDER_AMOUNT_CENTS = 2250; // $22.50+export const SHOPIFY_SALE_REWARD_PERCENT = 10;export function shopifyOrderPayload({checkoutToken,+ ...overrides}: {checkoutToken: string;-}) {+} & Record<string, unknown>) {return {confirmation_number: nanoid(10).toUpperCase(),checkout_token: checkoutToken,customer: {- id: Math.floor(Math.random() * 1_000_000_000),+ id: randomName("pw_cus", 16),first_name: "Playwright",last_name: "Shopify",email: `pw.shopify.${nanoid(8)}@dub-internal-test.com`,},current_subtotal_price_set: {shop_money: {- amount: "22.50",+ amount: (SHOPIFY_ORDER_AMOUNT_CENTS / 100).toFixed(2),currency_code: "USD",},},@@ -36,6 +40,7 @@ export function shopifyOrderPayload({province: "California",country_code: "US",},+ ...overrides,};}@@ -74,10 +79,11 @@ export async function postShopifyPixel({export async function postShopifyOrdersPaidWebhook({checkoutToken,+ ...orderOverrides}: {checkoutToken: string;-}) {- const payload = shopifyOrderPayload({ checkoutToken });+} & Record<string, unknown>) {+ const payload = shopifyOrderPayload({ checkoutToken, ...orderOverrides });const body = JSON.stringify(payload);const signature = shopifyWebhookSignature(body);@@ -98,5 +104,330 @@ export async function postShopifyOrdersPaidWebhook({return {status: response.status,data: await response.text(),+ payload,+ };+}++/** Pixel writes clickId via waitUntil — wait until Redis has it before the webhook. */+export async function waitForShopifyCheckoutClickId({+ checkoutToken,+ clickId,+}: {+ checkoutToken: string;+ clickId: string;+}) {+ await expect+ .poll(+ async () =>+ redis.hget<string>(`shopify:checkout:${checkoutToken}`, "clickId"),+ { timeout: 5_000 },+ )+ .toEqual(clickId);+}++export async function seedShopifyPartner({+ workspaceId,+ programId,+ groupId,+ withDiscountCode = false,+}: {+ workspaceId: string;+ programId: string;+ groupId: string;+ withDiscountCode?: boolean;+}) {+ const partnerId = createId({ prefix: "pn_" });+ const linkId = createId({ prefix: "link_" });+ const saleRewardId = createId({ prefix: "rw_" });+ const discountId = withDiscountCode+ ? createId({ prefix: "disc_" })+ : undefined;+ const code = withDiscountCode ? `PW${nanoid(8).toUpperCase()}` : undefined;+ const key = randomName("pw", 8);++ await prisma.partner.create({+ data: {+ id: partnerId,+ name: randomName("pw-shopify"),+ email: randomPartnerEmail(),+ username: randomName("pw", 12),+ },+ });++ await prisma.reward.create({+ data: {+ id: saleRewardId,+ programId,+ event: EventType.sale,+ type: RewardStructure.percentage,+ amountInPercentage: SHOPIFY_SALE_REWARD_PERCENT,+ maxDuration: 0,+ },+ });++ if (discountId) {+ await prisma.discount.create({+ data: {+ id: discountId,+ programId,+ amount: 10,+ type: RewardStructure.percentage,+ maxDuration: null,+ provider: DiscountProvider.custom,+ },+ });+ }++ await prisma.programEnrollment.create({+ data: {+ id: createId({ prefix: "pge_" }),+ partnerId,+ programId,+ groupId,+ status: "approved",+ saleRewardId,+ discountId,+ },+ });++ await prisma.link.create({+ data: {+ id: linkId,+ domain: TEST_WORKSPACE.program.domain,+ key,+ url: TEST_WORKSPACE.program.url,+ shortLink: `https://${TEST_WORKSPACE.program.domain}/${key}`,+ projectId: workspaceId,+ programId,+ partnerId,+ trackConversion: true,+ },+ });++ if (discountId && code) {+ await prisma.discountCode.create({+ data: {+ id: createId({ prefix: "dcode_" }),+ code,+ programId,+ partnerId,+ linkId,+ discountId,+ },+ });+ }++ return {+ partnerId,+ linkId,+ saleRewardId,+ discountId,+ code,+ domain: TEST_WORKSPACE.program.domain,+ key,};}++export type SeededShopifyPartner = Awaited<+ ReturnType<typeof seedShopifyPartner>+>;++export async function cleanupShopifyPartner({+ partnerId,+ saleRewardId,+ discountId,+}: {+ partnerId: string | undefined;+ saleRewardId: string | undefined;+ discountId?: string | undefined;+}) {+ if (partnerId) {+ await prisma.customer.deleteMany({ where: { partnerId } });+ }++ await deletePartner(partnerId);++ if (discountId) {+ await prisma.discount.delete({ where: { id: discountId } }).catch(() => {});+ }++ if (saleRewardId) {+ await prisma.reward.delete({ where: { id: saleRewardId } }).catch(() => {});+ }+}++/** Seeds a Shopify partner and always cleans up, even when the test body throws. */+export async function withShopifyPartner<T>(+ {+ workspaceId,+ programId,+ groupId,+ withDiscountCode = false,+ }: {+ workspaceId: string;+ programId: string;+ groupId: string;+ withDiscountCode?: boolean;+ },+ run: (seeded: SeededShopifyPartner) => Promise<T>,+): Promise<T> {+ const seeded = await seedShopifyPartner({+ workspaceId,+ programId,+ groupId,+ withDiscountCode,+ });++ try {+ return await run(seeded);+ } finally {+ await cleanupShopifyPartner(seeded);+ }+}++export async function waitForShopifyCustomerSale({+ workspaceId,+ externalId,+ amount = SHOPIFY_ORDER_AMOUNT_CENTS,+}: {+ workspaceId: string;+ externalId: string;+ amount?: number;+}) {+ await expect+ .poll(+ async () => {+ const customer = await prisma.customer.findUnique({+ where: {+ projectId_externalId: {+ projectId: workspaceId,+ externalId,+ },+ },+ });++ if (!customer) {+ return null;+ }++ return {+ id: customer.id,+ sales: customer.sales,+ saleAmount: Number(customer.saleAmount),+ };+ },+ { timeout: 30_000 },+ )+ .toEqual({+ id: expect.any(String),+ sales: 1,+ saleAmount: amount,+ });++ return prisma.customer.findUniqueOrThrow({+ where: {+ projectId_externalId: {+ projectId: workspaceId,+ externalId,+ },+ },+ });+}++export async function waitForShopifySaleCommission({+ partnerId,+ customerId,+ amount = SHOPIFY_ORDER_AMOUNT_CENTS,+ earnings = Math.round(+ (SHOPIFY_ORDER_AMOUNT_CENTS * SHOPIFY_SALE_REWARD_PERCENT) / 100,+ ),+}: {+ partnerId: string;+ customerId: string;+ amount?: number;+ earnings?: number;+}) {+ await expect+ .poll(+ async () => {+ const commission = await prisma.commission.findFirst({+ where: {+ partnerId,+ customerId,+ type: "sale",+ },+ });++ if (!commission) {+ return null;+ }++ return {+ amount: commission.amount,+ earnings: commission.earnings,+ type: commission.type,+ invoiceId: commission.invoiceId,+ };+ },+ { timeout: 30_000 },+ )+ .toEqual({+ amount,+ earnings,+ type: "sale",+ invoiceId: expect.any(String),+ });+}++export async function waitForShopifySaleEvent({+ api,+ customerId,+ amount = SHOPIFY_ORDER_AMOUNT_CENTS,+}: {+ api: ApiClient;+ customerId: string;+ amount?: number;+}) {+ await expect+ .poll(+ async () => {+ const { status, data } = await api.get<+ {+ event: string;+ eventName: string;+ sale: { amount: number; paymentProcessor: string };+ customer: { id: string };+ }[]+ >(+ `/api/events?${new URLSearchParams({+ event: "sales",+ interval: "24h",+ customerId,+ })}`,+ );++ if (status !== 200 || !Array.isArray(data) || data.length === 0) {+ return null;+ }++ const sale = data.find((event) => event.customer?.id === customerId);+ if (!sale) {+ return null;+ }++ return {+ event: sale.event,+ eventName: sale.eventName,+ amount: sale.sale.amount,+ paymentProcessor: sale.sale.paymentProcessor,+ };+ },+ { timeout: 30_000 },+ )+ .toEqual({+ event: "sale",+ eventName: "Purchase",+ amount,+ paymentProcessor: "shopify",+ });+}diff --git a/apps/web/playwright/api/shopify/orders.spec.ts b/apps/web/playwright/api/shopify/orders.spec.tsnew file mode 100644index 0000000000..e0f140970a--- /dev/null+++ b/apps/web/playwright/api/shopify/orders.spec.ts@@ -0,0 +1,292 @@+import { prisma } from "@/lib/prisma";+import { expect } from "@playwright/test";+import { randomName } from "../../utils";+import { trackClick, trackLead } from "../conversions/helpers";+import { test } from "../fixtures";+import {+ postShopifyOrdersPaidWebhook,+ postShopifyPixel,+ waitForShopifyCheckoutClickId,+ waitForShopifyCustomerSale,+ waitForShopifySaleCommission,+ waitForShopifySaleEvent,+ withShopifyPartner,+} from "./helpers";++test.describe("Shopify orders/paid attribution", () => {+ test.describe.configure({ timeout: 90_000 });++ test("existing customer – records sale event and commission", async ({+ api,+ workspace,+ program,+ }) => {+ await withShopifyPartner(+ {+ workspaceId: workspace.id,+ programId: program.id,+ groupId: program.defaultGroupId,+ },+ async (seeded) => {+ const { clickId } = await trackClick({+ domain: seeded.domain,+ key: seeded.key,+ });++ const externalId = randomName("pw_cus", 16);+ await trackLead({+ clickId,+ customerExternalId: externalId,+ });++ const checkoutToken = randomName("pw_checkout", 24);+ const { status, data } = await postShopifyOrdersPaidWebhook({+ checkoutToken,+ customer: {+ id: externalId,+ first_name: "Playwright",+ last_name: "Shopify",+ email: `pw.shopify.${externalId}@dub-internal-test.com`,+ },+ });++ expect(status).toEqual(200);+ expect(data).toMatch(/Existing customer .+ found\. Order queued/);++ const customer = await waitForShopifyCustomerSale({+ workspaceId: workspace.id,+ externalId,+ });++ await waitForShopifySaleEvent({ api, customerId: customer.id });+ await waitForShopifySaleCommission({+ partnerId: seeded.partnerId,+ customerId: customer.id,+ });+ },+ );+ });++ test("partner discount code – records sale event and commission", async ({+ api,+ workspace,+ program,+ }) => {+ await withShopifyPartner(+ {+ workspaceId: workspace.id,+ programId: program.id,+ groupId: program.defaultGroupId,+ withDiscountCode: true,+ },+ async (seeded) => {+ const externalId = randomName("pw_cus", 16);+ const checkoutToken = randomName("pw_checkout", 24);+ const { status, data } = await postShopifyOrdersPaidWebhook({+ checkoutToken,+ customer: {+ id: externalId,+ first_name: "Playwright",+ last_name: "Shopify",+ email: `pw.shopify.${externalId}@dub-internal-test.com`,+ },+ discount_codes: [{ code: seeded.code }],+ });++ expect(status).toEqual(200);+ expect(data).toEqual(+ `[Shopify] Partner discount code ${seeded.code} found. Order queued for processing.`,+ );++ const customer = await waitForShopifyCustomerSale({+ workspaceId: workspace.id,+ externalId,+ });++ await waitForShopifySaleEvent({ api, customerId: customer.id });+ await waitForShopifySaleCommission({+ partnerId: seeded.partnerId,+ customerId: customer.id,+ });+ },+ );+ });++ test("new customer – webhook waits for pixel", async () => {+ const checkoutToken = randomName("pw_checkout", 24);+ const { status, data } = await postShopifyOrdersPaidWebhook({+ checkoutToken,+ });++ expect(status).toEqual(200);+ expect(data).toEqual("[Shopify] Waiting for pixel event to arrive...");+ });++ test("pixel first, then webhook – records sale event and commission", async ({+ api,+ workspace,+ program,+ }) => {+ await withShopifyPartner(+ {+ workspaceId: workspace.id,+ programId: program.id,+ groupId: program.defaultGroupId,+ },+ async (seeded) => {+ const { clickId } = await trackClick({+ domain: seeded.domain,+ key: seeded.key,+ });++ const checkoutToken = randomName("pw_checkout", 24);+ const externalId = randomName("pw_cus", 16);++ const pixel = await postShopifyPixel({ clickId, checkoutToken });+ expect(pixel).toEqual({ status: 200, data: "OK" });++ await waitForShopifyCheckoutClickId({ checkoutToken, clickId });++ const { status, data } = await postShopifyOrdersPaidWebhook({+ checkoutToken,+ customer: {+ id: externalId,+ first_name: "Playwright",+ last_name: "Shopify",+ email: `pw.shopify.${externalId}@dub-internal-test.com`,+ },+ });++ expect(status).toEqual(200);+ expect(data).toEqual(+ `[Shopify] Click ID ${clickId} found. Order queued for processing.`,+ );++ const customer = await waitForShopifyCustomerSale({+ workspaceId: workspace.id,+ externalId,+ });++ await waitForShopifySaleEvent({ api, customerId: customer.id });+ await waitForShopifySaleCommission({+ partnerId: seeded.partnerId,+ customerId: customer.id,+ });+ },+ );+ });++ test("webhook first, then pixel – records sale event and commission", async ({+ api,+ workspace,+ program,+ }) => {+ await withShopifyPartner(+ {+ workspaceId: workspace.id,+ programId: program.id,+ groupId: program.defaultGroupId,+ },+ async (seeded) => {+ const { clickId } = await trackClick({+ domain: seeded.domain,+ key: seeded.key,+ });++ const checkoutToken = randomName("pw_checkout", 24);+ const externalId = randomName("pw_cus", 16);++ const webhook = await postShopifyOrdersPaidWebhook({+ checkoutToken,+ customer: {+ id: externalId,+ first_name: "Playwright",+ last_name: "Shopify",+ email: `pw.shopify.${externalId}@dub-internal-test.com`,+ },+ });+ expect(webhook.status).toEqual(200);+ expect(webhook.data).toEqual(+ "[Shopify] Waiting for pixel event to arrive...",+ );++ const pixel = await postShopifyPixel({ clickId, checkoutToken });+ expect(pixel).toEqual({ status: 200, data: "OK" });++ const customer = await waitForShopifyCustomerSale({+ workspaceId: workspace.id,+ externalId,+ });++ await waitForShopifySaleEvent({ api, customerId: customer.id });+ await waitForShopifySaleCommission({+ partnerId: seeded.partnerId,+ customerId: customer.id,+ });+ },+ );+ });++ test("pixel and webhook arrive at the same time – records one sale and commission", async ({+ api,+ workspace,+ program,+ }) => {+ await withShopifyPartner(+ {+ workspaceId: workspace.id,+ programId: program.id,+ groupId: program.defaultGroupId,+ },+ async (seeded) => {+ const { clickId } = await trackClick({+ domain: seeded.domain,+ key: seeded.key,+ });++ const checkoutToken = randomName("pw_checkout", 24);+ const externalId = randomName("pw_cus", 16);+ const customer = {+ id: externalId,+ first_name: "Playwright",+ last_name: "Shopify",+ email: `pw.shopify.${externalId}@dub-internal-test.com`,+ };++ const [pixel, webhook] = await Promise.all([+ postShopifyPixel({ clickId, checkoutToken }),+ postShopifyOrdersPaidWebhook({ checkoutToken, customer }),+ ]);++ expect(pixel).toEqual({ status: 200, data: "OK" });+ expect(webhook.status).toEqual(200);+ expect([+ `[Shopify] Click ID ${clickId} found. Order queued for processing.`,+ "[Shopify] Waiting for pixel event to arrive...",+ ]).toContain(webhook.data);++ const createdCustomer = await waitForShopifyCustomerSale({+ workspaceId: workspace.id,+ externalId,+ });++ await waitForShopifySaleEvent({ api, customerId: createdCustomer.id });+ await waitForShopifySaleCommission({+ partnerId: seeded.partnerId,+ customerId: createdCustomer.id,+ });++ // Rendezvous claim + sale idempotency: exactly one sale for this checkout.+ expect(createdCustomer.sales).toEqual(1);+ const commissions = await prisma.commission.count({+ where: {+ partnerId: seeded.partnerId,+ customerId: createdCustomer.id,+ type: "sale",+ },+ });+ expect(commissions).toEqual(1);+ },+ );+ });+});