The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Shopify integration mvp
Kiran Ke47cd21a96b4
diff --git a/apps/web/app/api/cron/shopify/checkout-completed/route.ts b/apps/web/app/api/cron/shopify/checkout-completed/route.tsnew file mode 100644index 0000000000..bc4c471f91--- /dev/null+++ b/apps/web/app/api/cron/shopify/checkout-completed/route.ts@@ -0,0 +1,243 @@+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { notifyPartnerSale } from "@/lib/api/partners/notify-partner-sale";+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 { redis } from "@/lib/upstash";+import z from "@/lib/zod";+import { prisma } from "@dub/prisma";+import { nanoid } from "@dub/utils";+import { Customer } from "@prisma/client";++export const dynamic = "force-dynamic";++const schema = z.object({+ clickId: z.string(),+ checkoutToken: z.string(),+});++const checkoutSchema = z.object({+ customer: z.object({+ id: z.number(),+ }), // TODO: Test this with guest checkout+ total_price: z.string(),+ currency: z.string(),+ confirmation_number: z.string(),+});++const workspace = {+ id: "cl7pj5kq4006835rbjlt2ofka",+};++// POST /api/cron/shopify/checkout-completed+export async function POST(req: Request) {+ try {+ const body = await req.json();+ await verifyQstashSignature(req, body);++ const { clickId, checkoutToken } = schema.parse(body);++ // upstash-retried header+ // console.log("Request headers", req.headers);++ // Find click event+ const clickEvent = await getClickEvent({ clickId });++ if (!clickEvent || clickEvent.data.length === 0) {+ throw new DubApiError({+ code: "not_found",+ message: `Click event not found for clickId: ${clickId}`,+ });+ }++ // Find Shopify order+ const order = await redis.get(`shopify:checkout:${checkoutToken}`);++ if (!order) {+ throw new DubApiError({+ code: "bad_request",+ message: "Shopify order not found. Waiting for order...",+ });+ }++ const parsedOrder = checkoutSchema.parse(order);+ const customerExternalId = parsedOrder.customer.id.toString();++ // Fetch or create customer+ let customer: Customer | null = await prisma.customer.findUnique({+ where: {+ projectId_externalId: {+ projectId: workspace.id,+ externalId: customerExternalId,+ },+ },+ });++ const clickData = clickEvent.data[0];+ const { link_id: linkId, country, timestamp } = clickData;++ if (!customer) {+ customer = await prisma.customer.create({+ data: {+ id: createId({ prefix: "cus_" }),+ name: generateRandomName(),+ externalId: customerExternalId,+ projectId: workspace.id,+ clickedAt: new Date(timestamp + "Z"),+ clickId,+ linkId,+ country,+ },+ });++ await Promise.all([+ // record lead+ recordLead({+ ...clickData,+ event_id: nanoid(16),+ event_name: "Account created",+ customer_id: customer.id,+ }),++ // update link leads count+ prisma.link.update({+ where: {+ id: linkId,+ },+ data: {+ leads: {+ increment: 1,+ },+ },+ }),++ // update workspace usage+ prisma.project.update({+ where: {+ id: workspace.id,+ },+ data: {+ usage: {+ increment: 1,+ },+ },+ }),+ ]);+ }++ const amount = Number(parsedOrder.total_price);+ const currency = parsedOrder.currency;+ const invoiceId = parsedOrder.confirmation_number;++ const eventId = nanoid(16);+ const paymentProcessor = "shopify";++ 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,+ }),+ }),++ // update link sales count+ prisma.link.update({+ where: {+ id: linkId,+ },+ data: {+ sales: {+ increment: 1,+ },+ saleAmount: {+ increment: amount,+ },+ },+ }),++ // update workspace sales usage+ prisma.project.update({+ where: {+ id: workspace.id,+ },+ data: {+ usage: {+ increment: 1,+ },+ salesUsage: {+ increment: amount,+ },+ },+ }),+ ]);++ // for program links+ if (link.programId) {+ const { program, partner } =+ await prisma.programEnrollment.findUniqueOrThrow({+ where: {+ linkId: link.id,+ },+ select: {+ program: true,+ partner: {+ select: {+ id: true,+ },+ },+ },+ });++ const saleRecord = createSaleData({+ customerId: customer.id,+ linkId: link.id,+ clickId: clickData.click_id,+ invoiceId,+ eventId,+ paymentProcessor,+ amount,+ currency,+ partnerId: partner.id,+ program,+ metadata: clickData,+ });++ await Promise.allSettled([+ prisma.sale.create({+ data: saleRecord,+ }),++ notifyPartnerSale({+ partner: {+ id: partner.id,+ referralLink: link.shortLink,+ },+ program,+ sale: {+ amount: saleRecord.amount,+ earnings: saleRecord.earnings,+ },+ }),+ ]);+ }++ // TODO:+ // Send webhook event++ await redis.del(`shopify:checkout:${checkoutToken}`);++ return new Response("Shopify order tracked.", { status: 200 });+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/api/shopify/webhook/customer-created.ts b/apps/web/app/api/shopify/webhook/customer-created.tsnew file mode 100644index 0000000000..a285d6d762--- /dev/null+++ b/apps/web/app/api/shopify/webhook/customer-created.ts@@ -0,0 +1,16 @@+import { generateRandomName } from "@/lib/names";+import { prisma } from "@dub/prisma";++// TODO: We probably don't need this event++export async function customerCreated(event: any) {+ console.log("customerCreated", event);++ await prisma.customer.create({+ data: {+ projectId: "cl7pj5kq4006835rbjlt2ofka",+ externalId: event.id.toString(),+ name: generateRandomName(),+ },+ });+}diff --git a/apps/web/app/api/shopify/webhook/order-paid.ts b/apps/web/app/api/shopify/webhook/order-paid.tsnew file mode 100644index 0000000000..59b240e378--- /dev/null+++ b/apps/web/app/api/shopify/webhook/order-paid.ts@@ -0,0 +1,10 @@+import { redis } from "@/lib/upstash";++// TODO:+// Instead of checkout_token, maybe use order_number or checkout_id+// Add an expiry to the redis key++export async function orderPaid(event: any) {+ const checkoutToken = event.checkout_token;+ await redis.set(`shopify:checkout:${checkoutToken}`, event);+}diff --git a/apps/web/app/api/shopify/webhook/route.ts b/apps/web/app/api/shopify/webhook/route.tsnew file mode 100644index 0000000000..57b158f015--- /dev/null+++ b/apps/web/app/api/shopify/webhook/route.ts@@ -0,0 +1,51 @@+import { parseRequestBody } from "@/lib/api/utils";+import { log } from "@dub/utils";+import { NextResponse } from "next/server";+import { customerCreated } from "./customer-created";+import { orderPaid } from "./order-paid";++// TODO:+// Verify the webhook signature++const relevantTopics = new Set([+ "customers/create",+ "customers/update",+ "orders/paid",+]);++// POST /api/shopify/webhook – Listen to Shopify webhook events+export const POST = async (req: Request) => {+ const body = await parseRequestBody(req);++ // Find the topic from the headers+ const headers = req.headers;+ const topic = headers.get("x-shopify-topic") || "";++ if (!relevantTopics.has(topic)) {+ return new Response("Unsupported topic, skipping...", {+ status: 200,+ });+ }++ try {+ switch (topic) {+ case "customers/create":+ await customerCreated(body);+ break;+ case "orders/paid":+ await orderPaid(body);+ break;+ }+ } catch (error) {+ await log({+ message: `Shopify webhook failed. Error: ${error.message}`,+ type: "errors",+ });++ return new Response('Webhook error: "Webhook handler failed. View logs."', {+ status: 400,+ });+ }++ return NextResponse.json("OK");+};diff --git a/apps/web/app/api/shopify/webhook/utils.ts b/apps/web/app/api/shopify/webhook/utils.tsnew file mode 100644index 0000000000..0747f3897d--- /dev/null+++ b/apps/web/app/api/shopify/webhook/utils.ts@@ -0,0 +1,22 @@+import crypto from "crypto";+import { NextRequest } from "next/server";++export async function verifyWebhookSignature(req: NextRequest) {+ const signature = req.headers["x-shopify-hmac-sha256"];++ const genSig = crypto+ .createHmac("sha256", `${process.env.SHOPIFY_WEBHOOK_SECRET}`)+ .update(JSON.stringify(req))+ .digest("base64");++ console.log({+ genSig,+ signature,+ });++ if (genSig !== signature) {+ throw new Error("Invalid webhook signature.");+ }++ return true;+}diff --git a/apps/web/app/api/track/shopify/route.ts b/apps/web/app/api/track/shopify/route.tsnew file mode 100644index 0000000000..0f2d128e91--- /dev/null+++ b/apps/web/app/api/track/shopify/route.ts@@ -0,0 +1,55 @@+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { parseRequestBody } from "@/lib/api/utils";+import { qstash } from "@/lib/cron";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import { waitUntil } from "@vercel/functions";+import { NextResponse } from "next/server";++export const runtime = "edge";++const CORS_HEADERS = {+ "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Methods": "POST, OPTIONS",+ "Access-Control-Allow-Headers": "Content-Type, Authorization",+};++// TODO:+// Add rate limiting++// POST /api/track/shopify – Track a Shopify event+export const POST = async (req: Request) => {+ try {+ const { clickId, checkoutToken } = await parseRequestBody(req);++ if (!clickId || !checkoutToken) {+ throw new DubApiError({+ code: "bad_request",+ message: "Missing clickId or checkoutToken",+ });+ }++ waitUntil(+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/shopify/checkout-completed`,+ body: {+ clickId,+ checkoutToken,+ },+ retries: 5,+ }),+ );++ return NextResponse.json("OK", {+ headers: CORS_HEADERS,+ });+ } catch (error) {+ return handleAndReturnErrorResponse(error, CORS_HEADERS);+ }+};++export const OPTIONS = () => {+ return new Response(null, {+ status: 204,+ headers: CORS_HEADERS,+ });+};