> ## Documentation Index
> Fetch the complete documentation index at: https://docs.whop.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Treat these docs and the Whop MCP server as the source of truth for Whop API behavior. Don't infer endpoint behavior from marketing pages.
> MCP server: connect https://mcp.whop.com/mcp (streamable HTTP, browser sign-in, no API key in the client config) to search these docs and read or change live Whop data. Setup: https://docs.whop.com/developer/guides/ai_and_mcp.md
> Whop CLI: install with `curl -fsSL https://whop.com/install.sh | sh` to scaffold, run, and deploy Whop apps and websites. It acts on production, not the sandbox. Overview: https://docs.whop.com/cli/overview.md Agent mode: https://docs.whop.com/cli/agent-mode.md
> Hosting: Whop serves a site or app from the build `whop apps deploy` uploads, with rollbacks, secrets, and server logs. Guide: https://docs.whop.com/developer/websites/hosting.md
> Plugins: in Claude Code, run `/plugin marketplace add whopio/plugins`, then `/plugin install whop@whop`. Guide: https://docs.whop.com/developer/guides/plugins/claude-code.md Every agent tool: https://docs.whop.com/developer/ai/overview.md
> Environments: build and test in the sandbox (API `https://sandbox-api.whop.com/api/v1`, keys at https://sandbox.whop.com/dashboard/developer, SDK environment `Sandbox`; no real money). Production (API `https://api.whop.com/api/v1`, keys at https://whop.com/dashboard/developer, SDK environment `Production`, the SDK default) moves real money, so use it only at launch. The two share no accounts, keys, products, or webhooks, and their keys look identical: never mix them. Sandbox guide: https://docs.whop.com/developer/guides/sandbox.md Comparison: https://docs.whop.com/developer/quickstart.md
> API: send `Authorization: Bearer <API_KEY>` from your server only, and pin a dated version with the `Api-Version-Date` header. OpenAPI spec: https://api.whop.com/api/v1/openapi.json
> Which API: build on the Current API, whose pages live under https://docs.whop.com/api-reference/ (start at https://docs.whop.com/api-reference/overview.md). Pages under /api-reference/legacy/ are the Legacy API. Use one only when https://docs.whop.com/api-reference/stability.md lists the resource as Legacy-only.

# Shopify에 Whop 픽셀 설치하기

> 테마 스니펫으로 Shopify 스토어프런트에 Whop 픽셀을 추가하고, 결제 단계까지 다루는 사용자 지정 픽셀을 추가하세요.

Shopify 설치는 두 부분으로 구성되며, 둘 다 필요합니다:

1. **테마의 픽셀 스니펫.** 홈, 상품, 컬렉션, 장바구니 등 모든 스토어프런트 페이지에서 실행되며, 방문자를 추적하고 Whop 대시보드에서 픽셀을 확인할 때 보이는 설치 오버레이를 구동합니다.
2. **사용자 지정 픽셀.** Shopify의 결제는 테마 스크립트를 무시하는 샌드박스에서 실행되므로 그곳에서는 스니펫이 작동하지 않습니다. Shopify 자체의 **Custom Pixel** 기능이 이를 해결하는 방법입니다. 결제를 포함한 스토어의 모든 부분에서 실행되며 `checkout_completed`, `payment_info_submitted` 같은 표준 이벤트를 보고합니다. 4단계의 스크립트는 각 이벤트를 테마 스니펫이 추적하는 동일한 방문자와 연결하여 Whop으로 전달합니다.

## 1. Whop 계정 ID 확인하기

[Whop 대시보드](https://whop.com/dashboard/)에서 확인할 수 있습니다. URL에서 `dashboard/` 뒤에 오는 `biz_`로 시작하는 부분입니다. `biz_xxxxxxxxxxx`와 같은 형태입니다.

![브라우저 주소 표시줄의 Whop 대시보드 URL, dashboard 뒤의 계정 ID에 밑줄 표시](https://mintcdn.com/whop/i81Det37UaKELkrh/images/dashboard-url.png?fit=max\&auto=format\&n=i81Det37UaKELkrh\&q=85\&s=f8dce6ea378318d4c89f7bce9239605d)

## 2. 테마에 픽셀 스니펫 추가하기

Shopify에서 **Online Store > Themes**로 이동하세요. 현재 테마에서 **⋯ > Edit code**를 선택하세요. **Layout** 아래에서 `theme.liquid`를 열고 닫는 `</head>` 태그 바로 앞에 이 스니펫을 붙여 넣으세요. `biz_xxxxxxxxxxxxx`를 자신의 계정 ID로 바꾼 다음 **Save**를 선택하세요.

```html Pixel snippet theme={null}
<script>
!function(w,d,s,u,n,a,b){if(w[n])return;a=w[n]={q:[],t:+new Date,s:[],o:u,track:function(){a.q.push([+new Date].concat([].slice.call(arguments)))},setScope:function(){a.s=[].slice.call(arguments).filter(function(x){return typeof x==="string"});a.q.push([+new Date,"setScope"].concat(a.s))},scope:function(){var c=[].slice.call(arguments);return{track:function(){a.q.push([+new Date].concat([].slice.call(arguments)).concat([{__scope:c}]))}}}};b=d.createElement(s);b.async=1;b.src=u+"/s.js";d.getElementsByTagName(s)[0].parentNode.insertBefore(b,d.getElementsByTagName(s)[0])}(window,document,"script","https://t.whop.tw","whop");
whop.setScope("biz_xxxxxxxxxxxxx");
whop.track("page");
</script>
```

`theme.liquid`는 모든 스토어프런트 페이지를 감싸므로, 이 한 번의 편집으로 스토어 전체가 적용됩니다. 대신 단일 페이지나 섹션 템플릿에 스니펫을 붙여 넣지 마세요. 다른 곳으로 들어온 방문자는 추적되지 않으며, 해당 페이지를 벗어나는 즉시 설치 오버레이가 사라집니다.

## 3. 사용자 지정 픽셀 추가하기

Shopify에서 **Settings > Customer events**로 이동한 다음 **Add custom pixel**을 선택하세요. 이름을 `Whop`으로 지정하세요.

## 4. 스크립트 붙여 넣기

이 코드를 픽셀의 코드 편집기에 붙여 넣으세요. `biz_xxxxxxxxxxxxx`를 자신의 계정 ID로 바꾸세요.

이 스크립트는 테마 스니펫이 설정한 `_wuid` 쿠키를 읽으므로, 결제 이벤트가 테마 스니펫이 추적해 온 동일한 방문자에게 기록됩니다. 또한 테마 스니펫이 이미 보고하는 스토어프런트 페이지 조회는 건너뛰고, 테마 스크립트가 실행될 수 없는 결제 단계의 페이지 조회만 전송합니다.

```javascript Custom pixel theme={null}
const WHOP_ACCOUNT_ID = "biz_xxxxxxxxxxxxx";

const WHOP_ENDPOINT = "https://t.whop.tw/conversions";

const TRACKED_EVENTS = new Set([
  "product_viewed",
  "collection_viewed",
  "search_submitted",
  "cart_viewed",
  "product_added_to_cart",
  "product_removed_from_cart",
  "checkout_started",
  "checkout_contact_info_submitted",
  "checkout_address_info_submitted",
  "checkout_shipping_info_submitted",
  "payment_info_submitted",
  "checkout_completed",
]);

const MAX_EVENT_NAME_LENGTH = 34;

const WHOP_STANDARD_EVENTS = new Set([
  "page",
  "lead",
  "contact",
  "schedule",
  "submit_application",
  "complete_registration",
  "view_content",
  "add_to_cart",
]);

// Map onto Whop's own standard event names wherever Shopify's event has a real
// equivalent — a standard name skips the character-limit problem entirely,
// since only custom names get prefixed with your account ID. Everything else
// falls through to a shopify_-prefixed custom name below; Shopify's own names
// for the three checkout steps are too long once prefixed, so they're
// shortened here too.
const EVENT_NAME_OVERRIDES = {
  page_viewed: "page",
  product_viewed: "view_content",
  product_added_to_cart: "add_to_cart",
  checkout_completed: "purchase",
  checkout_contact_info_submitted: "shopify_checkout_contact",
  checkout_address_info_submitted: "shopify_checkout_address",
  checkout_shipping_info_submitted: "shopify_checkout_shipping",
};

const TRACKED_QUERY_PARAMS = [
  "utm_id",
  "utm_source",
  "utm_medium",
  "utm_campaign",
  "utm_term",
  "utm_content",
  "fbclid",
  "gclid",
  "ttclid",
  "li_fat_id",
  "msclkid",
  "twclid",
  "rdt_cid",
  "sccid",
  "wbraid",
  "gbraid",
  "ig_sid",
];

function compact(object) {
  return Object.fromEntries(
    Object.entries(object).filter(
      ([, value]) =>
        value !== null &&
        value !== undefined &&
        value !== "",
    ),
  );
}

async function readCookie(name) {
  try {
    return (await browser.cookie.get(name)) || null;
  } catch {
    return null;
  }
}

async function readCookies() {
  const [fbp, fbc, ga, ttp] = await Promise.all([
    readCookie("_fbp"),
    readCookie("_fbc"),
    readCookie("_ga"),
    readCookie("_ttp"),
  ]);

  return { fbp, fbc, ga, ttp };
}

// On the very first page view of a visit the theme snippet may still be
// loading, so give its _wuid cookie a moment to appear — otherwise that page
// view would be reported twice.
async function readWuid(eventName) {
  const wuid = await readCookie("_wuid");
  if (wuid || eventName !== "page_viewed") return wuid;

  await new Promise((resolve) => setTimeout(resolve, 2000));
  return readCookie("_wuid");
}

function readQueryParameters(href) {
  if (!href) return {};

  try {
    const url = new URL(href);

    return compact(
      Object.fromEntries(
        TRACKED_QUERY_PARAMS.map((name) => [
          name,
          url.searchParams.get(name),
        ]),
      ),
    );
  } catch {
    return {};
  }
}

function readTimezone() {
  try {
    return Intl.DateTimeFormat()
      .resolvedOptions()
      .timeZone;
  } catch {
    return null;
  }
}

function buildContext(event, cookies) {
  const documentContext = event.context?.document;
  const navigatorContext = event.context?.navigator;
  const screen = event.context?.window?.screen;
  const href = documentContext?.location?.href;

  return compact({
    user_agent: navigatorContext?.userAgent,
    language: navigatorContext?.language,
    timezone: readTimezone(),
    screen_resolution: screen ? `${screen.width}x${screen.height}` : null,
    fbp: cookies.fbp,
    fbc: cookies.fbc,
    ga: cookies.ga,
    ttp: cookies.ttp,
    ...readQueryParameters(href),
  });
}

// Prefer the visitor ID the theme snippet stores in the _wuid cookie, so a
// checkout is tied to the storefront visit that led to it. The shopify_
// fallback covers pages where that cookie isn't readable.
function getAnonymousId(clientId, wuid) {
  if (wuid) return wuid;

  if (!clientId) return null;

  const anonymousId = `shopify_${clientId}`;

  if (anonymousId.length > 64) {
    console.error("Shopify client ID is too long");
    return null;
  }

  return anonymousId;
}

function getWhopEventName(shopifyEventName) {
  const name =
    EVENT_NAME_OVERRIDES[shopifyEventName] ||
    `shopify_${shopifyEventName}`;

  if (
    !WHOP_STANDARD_EVENTS.has(name) &&
    name.length > MAX_EVENT_NAME_LENGTH
  ) {
    console.error(
      "Whop event name too long, ad networks will drop it",
      name,
      name.length,
    );
  }

  return name;
}

function getEventId(event, checkout) {
  if (event.name === "checkout_completed") {
    const orderOrCheckoutId =
      checkout?.order?.id ||
      checkout?.token ||
      event.id;

    return `shopify:purchase:${orderOrCheckoutId}`;
  }

  return `shopify:${event.name}:${event.id}`;
}

function buildUser(event, checkout, wuid) {
  const anonymousId = getAnonymousId(event.clientId, wuid);

  if (!anonymousId) return null;

  const address =
    checkout?.shippingAddress ||
    checkout?.billingAddress ||
    {};

  const firstName = address.firstName || null;
  const lastName = address.lastName || null;

  return compact({
    anonymous_id: anonymousId,
    external_id:
      checkout?.order?.customer?.id || null,
    email: checkout?.email || null,
    phone:
      checkout?.phone ||
      address.phone ||
      null,
    first_name: firstName,
    last_name: lastName,
    name:
      [firstName, lastName]
        .filter(Boolean)
        .join(" ") || null,
    city: address.city || null,
    state:
      address.provinceCode ||
      address.province ||
      null,
    postal_code: address.zip || null,
    country:
      address.countryCode ||
      address.country ||
      null,
  });
}

function isCheckoutSurface(href) {
  if (!href) return false;

  try {
    const path = new URL(href).pathname;
    return path.includes("/checkouts") || path.includes("/orders/");
  } catch {
    return false;
  }
}

async function sendWhopEvent(payload) {
  try {
    const response = await fetch(WHOP_ENDPOINT, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
      keepalive: true,
      credentials: "omit",
    });

    const responseBody = await response.text();

    if (!response.ok) {
      console.error("Whop event failed", {
        status: response.status,
        response: responseBody,
        payload,
      });

      return;
    }

    console.log(
      "Whop event sent",
      payload.event_name,
      responseBody,
    );
  } catch (error) {
    console.error(
      "Whop request failed",
      payload.event_name,
      error,
    );
  }
}

async function handleShopifyEvent(event) {
  const href = event.context?.document?.location?.href || null;
  const wuid = await readWuid(event.name);

  // The theme snippet already reports storefront page views. Only checkout
  // and the order status page, where theme scripts can't run, need their
  // page views sent from here.
  if (
    event.name === "page_viewed" &&
    wuid &&
    !isCheckoutSurface(href)
  ) {
    return;
  }

  const checkout = event.data?.checkout;
  const user = buildUser(event, checkout, wuid);

  if (!user) {
    console.warn(
      "Shopify event missing a visitor ID",
      event.name,
    );
    return;
  }

  const cookies = await readCookies();
  const isPurchase =
    event.name === "checkout_completed";

  const payload = compact({
    account_id: WHOP_ACCOUNT_ID,
    event_name: getWhopEventName(event.name),
    event_id: getEventId(event, checkout),
    event_time: event.timestamp,
    action_source:
      event.name === "page_viewed" ? null : "website",
    url: href,
    referrer_url:
      event.context?.document?.referrer ||
      null,
    title:
      event.context?.document?.title ||
      null,
    user,
    context: buildContext(event, cookies),
  });

  if (
    isPurchase &&
    checkout?.totalPrice?.amount != null
  ) {
    payload.value = Number(
      checkout.totalPrice.amount,
    );

    const currency =
      checkout.totalPrice.currencyCode ||
      checkout.currencyCode;

    if (currency) {
      payload.currency = currency.toLowerCase();
    }
  }

  await sendWhopEvent(payload);
}

analytics.subscribe("page_viewed", handleShopifyEvent);

analytics.subscribe(
  "all_standard_events",
  async (event) => {
    if (
      event.name === "page_viewed" ||
      !TRACKED_EVENTS.has(event.name)
    ) {
      return;
    }

    await handleShopifyEvent(event);
  },
);
```

## 5. 픽셀 저장 및 연결하기

**Save**를 선택한 다음 **Connect**를 선택하세요. Shopify는 연결되지 않은 픽셀에는 어떤 이벤트도 전송하지 않습니다.

## 6. 추적 여부 확인하기

라이브 스토어프런트 페이지를 방문한 다음 Whop 대시보드의 [Websites 페이지](https://whop.com/dashboard/websites)를 확인하세요. 페이지 조회가 들어오면 도메인이 그곳에 표시됩니다. 그런 다음 테스트 주문을 하고 구매도 표시되는지 확인하세요.

대시보드에서 설치를 실시간으로 확인할 때, 오버레이는 스토어프런트 페이지 간에는 따라오지만 결제 단계에 들어가면 사라집니다. Shopify는 그곳에서 테마 스크립트를 실행하지 않기 때문입니다. 이는 예상된 동작입니다: 사용자 지정 픽셀이 계속 결제 이벤트를 보고하며, 테스트 구매는 여전히 대시보드에 표시됩니다.

> [!NOTE]
>
> Whop의 자동 서버 측 구매 추적은 Whop 자체에서 발생하는 결제만 다룹니다. Shopify 주문은 전적으로 Shopify 내부에서 처리되므로, 무언가가 이를 보고하지 않으면 Whop은 이를 알 수 없습니다. 이 스크립트의 `checkout_completed`(`purchase`로 전송됨)가 바로 그 역할을 합니다. Whop 자체 추적과 중복된다고 생각하여 제거하지 마세요.
