The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Route Shopify checkout Redis access through a cache class.
Kiran K8236a2797ad9
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 f2dc899168..8f8c72646f 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,7 @@import { DubApiError } from "@/lib/api/errors";import { withCron } from "@/lib/cron/with-cron";-import { shopifyOrderSchema } from "@/lib/integrations/shopify/schema";+import { shopifyCheckoutCache } from "@/lib/integrations/shopify/checkout-cache";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";@@ -13,33 +12,27 @@ const schema = z.object({checkoutToken: z.string(),});-// Matches the old qstash.publishJSON({ retries: 5 }) for this route.const MAX_PIXEL_WAIT_RETRIES = 5;-// Cutover shim: drains in-flight QStash messages with the old-// { workspaceId, checkoutToken } body.-// POST /api/cron/shopify/order-paid+// Cutover shim for in-flight QStash messages with the old+// { workspaceId, checkoutToken } body. Remove after a week.export const POST = withCron(async ({ req, rawBody }) => {const { workspaceId, checkoutToken } = schema.parse(JSON.parse(rawBody));- // Find Shopify order- const event = await redis.hget(`shopify:checkout:${checkoutToken}`, "order");+ const checkout = await shopifyCheckoutCache.get(checkoutToken);- if (!event) {+ if (!checkout.order) {return logAndRespond(`[Shopify] Order with checkout token ${checkoutToken} not found. Skipping...`,);}- const clickId = await redis.hget<string>(- `shopify:checkout:${checkoutToken}`,- "clickId",- );+ const { clickId, order } = checkout;// clickId is empty, order is not from a Dub linkif (clickId === "") {- await redis.del(`shopify:checkout:${checkoutToken}`);+ await shopifyCheckoutCache.delete(checkoutToken);return logAndRespond(`[Shopify] Order is not from a Dub link. Skipping...`);}@@ -48,7 +41,7 @@ export const POST = withCron(async ({ req, rawBody }) => {await processShopifyOrderJob.execute({workspaceId,clickId,- order: shopifyOrderSchema.parse(event),+ order,});return logAndRespond("[Shopify] Order event processed successfully.");diff --git a/apps/web/app/(ee)/api/shopify/integration/webhook/orders-paid.ts b/apps/web/app/(ee)/api/shopify/integration/webhook/orders-paid.tsindex 5aa28359bb..1c16fce161 100644--- a/apps/web/app/(ee)/api/shopify/integration/webhook/orders-paid.ts+++ b/apps/web/app/(ee)/api/shopify/integration/webhook/orders-paid.ts@@ -1,6 +1,6 @@import {+ shopifyCheckoutCache,tryDispatchShopifyOrderJob,- writeShopifyCheckoutFields,} from "@/lib/integrations/shopify/checkout-cache";import { shopifyOrderSchema } from "@/lib/integrations/shopify/schema";import { processShopifyOrderJob } from "@/lib/jobs/handlers/process-shopify-order-job";@@ -88,7 +88,7 @@ export async function ordersPaid({// At this stage, we know the order has no customer or partner discount code// so we need to wait for the pixel event to arrive as this could be a new customer coming via a link- const checkout = await writeShopifyCheckoutFields({+ const checkout = await shopifyCheckoutCache.set({checkoutToken,fields: {order,@@ -101,9 +101,7 @@ export async function ordersPaid({checkout,});- if (dispatched) {- return `[Shopify] Click ID ${checkout.clickId} found. Order queued for processing.`;- }-- return "[Shopify] Waiting for pixel event to arrive...";+ return dispatched+ ? `[Shopify] Click ID ${checkout.clickId} found. Order queued for processing.`+ : "[Shopify] Waiting for pixel event to arrive...";}diff --git a/apps/web/app/(ee)/api/shopify/pixel/route.ts b/apps/web/app/(ee)/api/shopify/pixel/route.tsindex 11926b6e3b..1ff35bb775 100644--- a/apps/web/app/(ee)/api/shopify/pixel/route.ts+++ b/apps/web/app/(ee)/api/shopify/pixel/route.ts@@ -2,8 +2,8 @@ import { COMMON_CORS_HEADERS } from "@/lib/api/cors";import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { parseRequestBody } from "@/lib/api/utils";import {+ shopifyCheckoutCache,tryDispatchShopifyOrderJob,- writeShopifyCheckoutFields,} from "@/lib/integrations/shopify/checkout-cache";import { getClickEvent } from "@/lib/tinybird";import { ratelimit } from "@/lib/upstash";@@ -43,19 +43,21 @@ export const POST = async (req: Request) => {}}- waitUntil(- (async () => {- const checkout = await writeShopifyCheckoutFields({- checkoutToken,- fields: clickId ? { clickId } : {},- });+ if (clickId) {+ waitUntil(+ (async () => {+ const checkout = await shopifyCheckoutCache.set({+ checkoutToken,+ fields: { clickId },+ });- await tryDispatchShopifyOrderJob({- checkoutToken,- checkout,- });- })(),- );+ await tryDispatchShopifyOrderJob({+ checkoutToken,+ checkout,+ });+ })(),+ );+ }return NextResponse.json("OK", {headers: COMMON_CORS_HEADERS,diff --git a/apps/web/lib/integrations/shopify/checkout-cache.ts b/apps/web/lib/integrations/shopify/checkout-cache.tsindex 8df96adfc6..c8ef350f55 100644--- a/apps/web/lib/integrations/shopify/checkout-cache.ts+++ b/apps/web/lib/integrations/shopify/checkout-cache.ts@@ -3,7 +3,7 @@ import { redis } from "@/lib/upstash";import * as z from "zod/v4";import { shopifyOrderSchema } from "./schema";-const SHOPIFY_CHECKOUT_CACHE_TTL_SECONDS = 60 * 60 * 6; // 6 hours+const SHOPIFY_CHECKOUT_CACHE_TTL_SECONDS = 60 * 60; // 1 hoursconst SHOPIFY_CHECKOUT_CACHE_KEY_PREFIX = "shopify:checkout:";const shopifyCheckoutCacheSchema = z.object({@@ -16,38 +16,54 @@ const shopifyCheckoutCacheSchema = z.object({dispatched: z.boolean().optional(),});-type ShopifyCheckoutCache = z.infer<typeof shopifyCheckoutCacheSchema>;+type ShopifyCheckoutCacheItem = z.infer<typeof shopifyCheckoutCacheSchema>;-function shopifyCheckoutCacheKey(checkoutToken: string) {- return `${SHOPIFY_CHECKOUT_CACHE_KEY_PREFIX}${checkoutToken}`;-}+class ShopifyCheckoutCache {+ async get(checkoutToken: string): Promise<ShopifyCheckoutCacheItem> {+ const cache = await redis.hgetall(this.createKey(checkoutToken));+ return this.parse(cache);+ }-export async function writeShopifyCheckoutFields({- checkoutToken,- fields,-}: {- checkoutToken: string;- fields: Partial<ShopifyCheckoutCache>;-}): Promise<ShopifyCheckoutCache> {- const key = shopifyCheckoutCacheKey(checkoutToken);+ async set({+ checkoutToken,+ fields,+ }: {+ checkoutToken: string;+ fields: Partial<ShopifyCheckoutCacheItem>;+ }): Promise<ShopifyCheckoutCacheItem> {+ const key = this.createKey(checkoutToken);++ const pipeline = redis.pipeline();+ pipeline.hset(key, fields);+ pipeline.expire(key, SHOPIFY_CHECKOUT_CACHE_TTL_SECONDS);+ pipeline.hgetall(key);- const pipeline = redis.pipeline();- pipeline.hset(key, fields);- pipeline.expire(key, SHOPIFY_CHECKOUT_CACHE_TTL_SECONDS);- pipeline.hgetall(key);+ const results = await pipeline.exec();+ return this.parse(results[2]);+ }++ async delete(checkoutToken: string) {+ return await redis.del(this.createKey(checkoutToken));+ }- const results = await pipeline.exec();- const parsed = shopifyCheckoutCacheSchema.safeParse(results[2]);+ createKey(checkoutToken: string) {+ return `${SHOPIFY_CHECKOUT_CACHE_KEY_PREFIX}${checkoutToken}`;+ }- return parsed.success ? parsed.data : shopifyCheckoutCacheSchema.parse({});+ parse(cache: unknown): ShopifyCheckoutCacheItem {+ const parsed = shopifyCheckoutCacheSchema.safeParse(cache);+ return parsed.success ? parsed.data : shopifyCheckoutCacheSchema.parse({});+ }}+export const shopifyCheckoutCache = new ShopifyCheckoutCache();+export async function tryDispatchShopifyOrderJob({checkoutToken,checkout,}: {checkoutToken: string;- checkout: ShopifyCheckoutCache;+ checkout: ShopifyCheckoutCacheItem;}) {if (!checkout.order || !checkout.workspaceId || !checkout.clickId) {return false;@@ -58,7 +74,7 @@ export async function tryDispatchShopifyOrderJob({}// Claim the checkout- const key = shopifyCheckoutCacheKey(checkoutToken);+ const key = shopifyCheckoutCache.createKey(checkoutToken);const claim = await redis.hsetnx(key, "dispatched", true);const claimed = Boolean(claim);@@ -77,7 +93,7 @@ export async function tryDispatchShopifyOrderJob({},);- await redis.del(key);+ await shopifyCheckoutCache.delete(checkoutToken);return true;}diff --git a/apps/web/lib/integrations/shopify/create-sale.ts b/apps/web/lib/integrations/shopify/create-sale.tsindex 06874f7439..f8c71d923f 100644--- a/apps/web/lib/integrations/shopify/create-sale.ts+++ b/apps/web/lib/integrations/shopify/create-sale.ts@@ -12,6 +12,7 @@ import { sendWorkspaceWebhook } from "@/lib/webhook/publish";import { transformSaleEventData } from "@/lib/webhook/transform";import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";+import { shopifyCheckoutCache } from "./checkout-cache";import { ShopifyError } from "./error";import { ShopifyOrder } from "./schema";@@ -126,7 +127,7 @@ export async function createShopifySale({firstSaleAt: existingCustomer.firstSaleAt ? undefined : new Date(),},}),- redis.del(`shopify:checkout:${checkoutToken}`),+ shopifyCheckoutCache.delete(checkoutToken),]);// for program linksdiff --git a/apps/web/playwright/api/shopify/helpers.ts b/apps/web/playwright/api/shopify/helpers.tsindex 489b073b71..d84499da3f 100644--- a/apps/web/playwright/api/shopify/helpers.ts+++ b/apps/web/playwright/api/shopify/helpers.ts@@ -1,6 +1,6 @@import { createId } from "@/lib/api/create-id";+import { shopifyCheckoutCache } from "@/lib/integrations/shopify/checkout-cache";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";@@ -118,8 +118,10 @@ export async function waitForShopifyCheckoutClickId({}) {await expect.poll(- async () =>- redis.hget<string>(`shopify:checkout:${checkoutToken}`, "clickId"),+ async () => {+ const { clickId } = await shopifyCheckoutCache.get(checkoutToken);+ return clickId;+ },{ timeout: 5_000 },).toEqual(clickId);