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.

Add Playwright coverage for Shopify orders/paid attribution.

Kiran K26f9511d7341
diff --git a/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts b/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts
index 362ae75131..027756c1df 100644
--- a/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts
+++ b/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts
@@ -1,8 +1,6 @@
-import { captureWebhookLog } from "@/lib/api-logs/capture-webhook-log";
import { isLocalDev } from "@/lib/api/environment";
import { prisma } from "@/lib/prisma";
import { log } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
import crypto from "crypto";
import { appUninstalled } from "./app-uninstalled";
import { customersDataRequest } from "./customers-data-request";
@@ -22,7 +20,6 @@ const relevantTopics = new Set([
// POST /api/shopify/integration/webhook – Listen to Shopify webhook events
export const POST = async (req: Request) => {
- const startTime = Date.now();
const data = await req.text();
const headers = req.headers;
const topic = headers.get("x-shopify-topic") || "";
@@ -68,14 +65,6 @@ export const POST = async (req: Request) => {
);
}
- const requestLog = {
- workspaceId: workspace.id,
- method: req.method,
- path: "/shopify/integration/webhook" as const,
- requestBody: event,
- userAgent: req.headers.get("user-agent"),
- };
-
let response = "OK";
try {
@@ -116,30 +105,8 @@ export const POST = async (req: Request) => {
type: "errors",
});
- const response = new Response(
- `[Shopify] Webhook handler failed. View logs`,
- );
-
- waitUntil(
- captureWebhookLog({
- ...requestLog,
- statusCode: 500,
- duration: Date.now() - startTime,
- responseBody: response,
- }),
- );
-
- return response;
+ return new Response(`[Shopify] Webhook handler failed. View logs`);
}
- waitUntil(
- captureWebhookLog({
- ...requestLog,
- statusCode: 200,
- duration: Date.now() - startTime,
- responseBody: response,
- }),
- );
-
return new Response(response);
};
diff --git a/apps/web/playwright/api/shopify/helpers.ts b/apps/web/playwright/api/shopify/helpers.ts
new file mode 100644
index 0000000000..ba564e05c4
--- /dev/null
+++ b/apps/web/playwright/api/shopify/helpers.ts
@@ -0,0 +1,168 @@
+import { createId } from "@/lib/api/create-id";
+import { prisma } from "@/lib/prisma";
+import type { Customer, EnrolledPartnerProps } from "@/lib/types";
+import { nanoid } from "@dub/utils";
+import { createHmac } from "crypto";
+import { PLAYWRIGHT_API_BASE } from "../constants";
+import type { ApiClient } from "../fixtures";
+import { TEST_WORKSPACE } from "../setup-test-workspace";
+
+export function shopifyOrderPayload({
+ checkoutToken,
+ amount = (Math.random() * 100).toFixed(2),
+ ...overrides
+}: {
+ checkoutToken: string;
+ amount?: string | number;
+} & Record<string, unknown>) {
+ return {
+ confirmation_number: nanoid(10),
+ checkout_token: checkoutToken,
+ customer: {
+ id: nanoid(10),
+ first_name: "John",
+ last_name: "Doe",
+ email: `john.doe.${nanoid(5)}@example.com`,
+ },
+ current_subtotal_price_set: {
+ shop_money: {
+ amount: String(amount),
+ currency_code: "USD",
+ },
+ },
+ discount_codes: [],
+ billing_address: {
+ province: "California",
+ country_code: "US",
+ },
+ ...overrides,
+ };
+}
+
+function shopifyWebhookSignature(body: string) {
+ return createHmac("sha256", `${process.env.SHOPIFY_WEBHOOK_SECRET}`)
+ .update(body, "utf8")
+ .digest("base64");
+}
+
+export async function postShopifyPixel({
+ clickId,
+ checkoutToken,
+}: {
+ clickId?: string | null;
+ checkoutToken?: string;
+}) {
+ const response = await fetch(`${PLAYWRIGHT_API_BASE}/api/shopify/pixel`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ clickId,
+ checkoutToken,
+ }),
+ });
+
+ return {
+ status: response.status,
+ data: await response.json(),
+ };
+}
+
+export async function postShopifyOrdersPaidWebhook({
+ checkoutToken,
+ storeId = TEST_WORKSPACE.shopify.storeId,
+ existingCustomerId,
+ discountCode,
+ amount,
+ ...orderOverrides
+}: {
+ checkoutToken: string;
+ storeId?: string;
+ existingCustomerId?: string | null;
+ discountCode?: string | null;
+ amount?: string | number;
+} & Record<string, unknown>) {
+ const payload = shopifyOrderPayload({
+ checkoutToken,
+ amount,
+ ...(existingCustomerId && {
+ customer: { id: existingCustomerId },
+ }),
+ ...(discountCode && {
+ discount_codes: [{ code: discountCode }],
+ }),
+ ...orderOverrides,
+ });
+ const body = JSON.stringify(payload);
+ const signature = shopifyWebhookSignature(body);
+
+ const response = await fetch(
+ `${PLAYWRIGHT_API_BASE}/api/shopify/integration/webhook`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "x-shopify-topic": "orders/paid",
+ "x-shopify-shop-domain": storeId,
+ "x-shopify-hmac-sha256": signature,
+ },
+ body,
+ },
+ );
+
+ return {
+ status: response.status,
+ data: await response.text(),
+ payload,
+ };
+}
+
+export function partnerDefaultLink(partner: EnrolledPartnerProps) {
+ const link = partner.links?.[0];
+
+ if (!link?.id || !link.domain || !link.key) {
+ throw new Error("Partner was created without a default link.");
+ }
+
+ return link;
+}
+
+export async function createPartnerDiscountCode({
+ programId,
+ partnerId,
+ linkId,
+}: {
+ programId: string;
+ partnerId: string;
+ linkId: string;
+}) {
+ const code = `PW${nanoid(8).toUpperCase()}`;
+
+ await prisma.discountCode.create({
+ data: {
+ id: createId({ prefix: "dcode_" }),
+ code,
+ programId,
+ partnerId,
+ linkId,
+ },
+ });
+
+ return code;
+}
+
+export async function getCustomerByExternalId(
+ api: ApiClient,
+ externalId: string,
+) {
+ const { status, data } = await api.get<Customer[]>(
+ `/api/customers?externalId=${encodeURIComponent(externalId)}`,
+ );
+
+ if (status !== 200 || !Array.isArray(data) || data.length === 0) {
+ return undefined;
+ }
+
+ return data[0];
+}
diff --git a/apps/web/playwright/api/shopify/orders.spec.ts b/apps/web/playwright/api/shopify/orders.spec.ts
new file mode 100644
index 0000000000..f37db3c08b
--- /dev/null
+++ b/apps/web/playwright/api/shopify/orders.spec.ts
@@ -0,0 +1,140 @@
+import { nanoid } from "@dub/utils";
+import { expect } from "@playwright/test";
+import { apiError, randomName } from "../../utils";
+import { trackClick, trackLead } from "../conversions/helpers";
+import { test } from "../fixtures";
+import { createPartner, deletePartner } from "../partners/helpers";
+import {
+ createPartnerDiscountCode,
+ getCustomerByExternalId,
+ partnerDefaultLink,
+ postShopifyOrdersPaidWebhook,
+ postShopifyPixel,
+} from "./helpers";
+
+test("POST /shopify/pixel – missing checkoutToken", async ({ api }) => {
+ expect(await api.post("/api/shopify/pixel", { clickId: nanoid(16) })).toEqual(
+ apiError({
+ code: "bad_request",
+ message: "checkoutToken is required.",
+ }),
+ );
+});
+
+test("POST /shopify/integration/webhook – unknown shop", async () => {
+ const { status, data } = await postShopifyOrdersPaidWebhook({
+ checkoutToken: nanoid(10),
+ storeId: `${randomName("pw-shopify")}.myshopify.com`,
+ });
+
+ expect(status).toEqual(200);
+ expect(data).toMatch(/Workspace not found for shop: .+\. Skipping\.\.\./);
+});
+
+test("orders/paid – waits for pixel when there is no click, customer, or discount", async () => {
+ const { status, data } = await postShopifyOrdersPaidWebhook({
+ checkoutToken: nanoid(10),
+ });
+
+ expect(status).toEqual(200);
+ expect(data).toEqual("[Shopify] Waiting for pixel event to arrive...");
+});
+
+test.describe("Shopify orders/paid", () => {
+ test.describe.configure({ mode: "serial" });
+
+ let partnerId: string | undefined;
+ let clickId: string;
+ let discountCode: string;
+
+ test.beforeAll(async ({ api, program }) => {
+ const { data: partner } = await createPartner(api);
+ partnerId = partner.id;
+ const link = partnerDefaultLink(partner);
+
+ ({ clickId } = await trackClick({
+ domain: link.domain,
+ key: link.key,
+ }));
+
+ discountCode = await createPartnerDiscountCode({
+ programId: program.id,
+ partnerId: partner.id,
+ linkId: link.id,
+ });
+ });
+
+ test.afterAll(async () => {
+ await deletePartner(partnerId);
+ });
+
+ test("click first, then webhook", async () => {
+ const checkoutToken = nanoid(10);
+
+ const pixel = await postShopifyPixel({ clickId, checkoutToken });
+ expect(pixel).toEqual({ status: 200, data: "OK" });
+
+ const webhook = await postShopifyOrdersPaidWebhook({ checkoutToken });
+ expect(webhook.status).toEqual(200);
+ expect(webhook.data).toEqual(
+ `[Shopify] Click ID ${clickId} found. Order queued for processing.`,
+ );
+ });
+
+ test("webhook first, then click", async () => {
+ const checkoutToken = nanoid(10);
+
+ const webhook = await postShopifyOrdersPaidWebhook({ checkoutToken });
+ 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" });
+ });
+
+ test("click and webhook in parallel", async () => {
+ const checkoutToken = nanoid(10);
+
+ const [pixel, webhook] = await Promise.all([
+ postShopifyPixel({ clickId, checkoutToken }),
+ postShopifyOrdersPaidWebhook({ checkoutToken }),
+ ]);
+
+ 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);
+ });
+
+ test("orders/paid – existing customer", async ({ api }) => {
+ const { customer } = await trackLead({ clickId });
+ const created = await getCustomerByExternalId(api, customer.externalId);
+ expect(created?.id).toEqual(expect.any(String));
+
+ const { status, data } = await postShopifyOrdersPaidWebhook({
+ checkoutToken: nanoid(10),
+ existingCustomerId: customer.externalId,
+ });
+
+ expect(status).toEqual(200);
+ expect(data).toEqual(
+ `[Shopify] Existing customer ${created!.id} found. Order queued for processing.`,
+ );
+ });
+
+ test("orders/paid – partner discount code", async () => {
+ const { status, data } = await postShopifyOrdersPaidWebhook({
+ checkoutToken: nanoid(10),
+ discountCode,
+ });
+
+ expect(status).toEqual(200);
+ expect(data).toEqual(
+ `[Shopify] Partner discount code ${discountCode} found. Order queued for processing.`,
+ );
+ });
+});