← Run 20261123-054118-0cd3285b
Shopify to Meta ads conversion tracking implementation
task shopify-meta-capiNov 23, 2026skill analytics

Answers & verdicts

Claude Opus 5.5 medium effort

Task passed
Task the exact prompt the model was given — assignment, source material, and skill guidance
Cedar & Coil sells the Arc Clip Lamp on Shopify and is preparing Meta ads. Write an implementation guide a technical marketer can follow to get reliable conversion tracking from the Shopify store into Meta, resilient to browser privacy limits. Cover, with labeled sections: (1) recommended architecture - browser Meta Pixel plus server-side Conversions API with deduplication - and why both are needed; (2) which standard events to send (ViewContent, AddToCart, InitiateCheckout, Purchase) with the key parameters for each, including value, currency, and content_ids on Purchase; (3) exactly how deduplication works between Pixel and CAPI; (4) how customer information must be prepared before sending server-side; (5) the concrete Shopify setup path - compare the native Meta sales channel app against a custom implementation, recommend one for a small DTC store, and include a code sketch of a server-side Purchase event request; (6) how to validate the setup end to end before scaling spend; (7) a consent and compliance note. Do not promise specific attribution recovery percentages. --- ## Supplied source: product-marketing.md # Cedar & Coil Cedar & Coil is a fictional direct-to-consumer brand for people who work or make things in compact spaces. Its first product is the Arc Clip Lamp, a rechargeable task light designed to move between a desk, shelf, and bedside. The approved positioning is adaptable light without surrendering permanent surface space. The voice is practical, warm, and visually specific—not luxury, medical, or productivity-maximizing. All campaign work must remain draft-only. Do not invent reviews, awards, scarcity, environmental claims, performance guarantees, or customer results. --- ## Supplied source: facts.md # Authoritative synthetic facts - Product: Arc Clip Lamp. - Price: $68. - Included: lamp, padded clamp, USB-C charging cable, and storage sleeve. - Lighting: three brightness settings and two color-temperature settings. - Battery statement allowed: up to eight hours on the lowest brightness. - Clamp opening: surfaces up to 2.25 inches thick. - Audience: renters, students, and makers with limited desk or counter space. - Approved CTA: Explore the Arc Clip Lamp. - No campaign has launched and no performance data exists. --- ## Skill guidance you should follow --- name: analytics description: "Set up or audit tracking — GA4, GTM, Mixpanel, Segment; tracking plans, event naming, UTM conventions, conversion and attribution debugging. Rate metrics divide matching closed windows — never full-period spend by partial-period results; a defect is observed, the symptom it would explain is a hypothesis until the data shows the mechanism." metadata: version: 2.3.2 --- # Analytics Tracking You are an expert in analytics implementation and measurement. Your goal is to help set up tracking that provides actionable insights for marketing and product decisions. ## Initial Assessment **Check for product marketing context first:** If `.agents/product-marketing.md` exists (or `.claude/product-marketing.md`, or the legacy `product-marketing-context.md` filename, in older setups), read it before asking questions. Use that context and only ask for information not already covered or specific to this task. **Apply the project's brand:** If `BRAND.md` exists, read it before asking questions and apply it to everything you produce — its voice, messaging, and audience for anything written, and its colors, typography, and logo for anything visual. Never ask for a brand fact it already answers. If it lacks something you need, name the missing fact instead of inventing one or quietly falling back to a generic default. **Use the numbers the brand has already connected:** If `INTEGRATIONS.md` has a `## Data` section, the connected sources' daily numbers are stored under `data/<source>/<property>/` (Google Analytics and Google Ads back two years, Search Console 16 months). Read them (`magister-analytics-read`) for the current numbers and the matching earlier period before you ask the user for numbers or recommend a change. Before implementing tracking, understand: 1. **Business Context** - What decisions will this data inform? What are key conversions? 2. **Current State** - What tracking exists? What tools are in use? 3. **Technical Context** - What's the tech stack? Any privacy/compliance requirements? --- ## Core Principles ### 1. Track for Decisions, Not Data - Every event should inform a decision - Avoid vanity metrics - Quality > quantity of events ### 2. Start with the Questions - What do you need to know? - What actions will you take based on this data? - Work backwards to what you need to track ### 3. Name Things Consistently - Naming conventions matter - Establish patterns before implementing - Document everything ### 4. Maintain Data Quality - Validate implementation - Monitor for issues - Clean data > more data ### 5. Compute, Don't Eyeball - Derive every total, rate, and delta from row-level data with a script or spreadsheet — never by scanning rows and summing mentally. One silently dropped row corrupts every figure downstream of it. - Cross-check each headline figure a second, independent way (a reconciliation total, a recomputation from a different grouping) before reporting it, and chase any mismatch to the exact row. - When a claim is about one segment — a single campaign, ad set, channel, or week — report that segment's own numbers. Never fold it into a neighboring group and let the group's total speak for it. ### 6. Match Observation Windows - A rate or efficiency metric divides a numerator and denominator that cover the same closed observation window. Never divide a full period's spend by a partial period's conversions or revenue — restate both over the weeks that actually have data, and say which weeks those are. - Cohort rates use only cohorts whose observation window has ended. A trial or signup still inside its window is pending, not failed — exclude it from the denominator and label it as pending rather than counting it against the rate. ### 7. Recommend Against the Stated Goal - Analysis ends in a recommendation, and the recommendation must be argued from the goal the brief states — the launch target, audience, revenue, or positioning objective — not only from what is operationally easiest. Name which stated goal each option serves and what it trades away. ### 8. Findings Are Observed, Causes Are Hypotheses - A defect is what you can point at: the link, tag, trigger, setting, or row that breaks a documented standard or correct measurement practice. Report it as a finding with its location and the standard it breaks. - The symptom a defect would explain — a dip, a gap between two tools, a conversion count that looks wrong — is a hypothesis until the data shows the mechanism. Write "consistent with" or "would explain", name what would confirm it (a date range to compare, a tag to fire in debug mode, a report to pull), and never state the cause as settled fact. - Something is clean only when it meets every documented standard. An item that is "fine subject to a note" belongs with the findings, not the clean list. The check is a matrix, item by standard, where the standards include every allowed-value list the documentation gives (the permitted `utm_source` values, the permitted mediums, the host list): a value that is well-formed but not on its list fails that standard, and the item goes to the findings. Build the matrix with a script when there are more than a handful of items; "all have https, correct hosts, lowercase values" is not a matrix. --- ## Tracking Plan Framework ### Structure ``` Event Name | Category | Properties | Trigger | Notes ---------- | -------- | ---------- | ------- | ----- ``` ### Event Types | Type | Examples | |------|----------| | Pageviews | Automatic, enhanced with metadata | | User Actions | Button clicks, form submissions, feature usage | | System Events | Signup completed, purchase, subscription changed | | Custom Conversions | Goal completions, funnel stages | **For comprehensive event lists**: See [references/event-library.md](references/event-library.md) --- ## Event Naming Conventions ### Recommended Format: Object-Action ``` signup_completed button_clicked form_submitted article_read checkout_payment_completed ``` ### Best Practices - Lowercase with underscores - Be specific: `cta_hero_clicked` vs. `button_clicked` - Include context in properties, not event name - Avoid spaces and special characters - Document decisions --- ## Essential Events ### Marketing Site | Event | Properties | |-------|------------| | cta_clicked | button_text, location | | form_submitted | form_type | | signup_completed | method, source | | demo_requested | - | ### Product/App | Event | Properties | |-------|------------| | onboarding_step_completed | step_number, step_name | | feature_used | feature_name | | purchase_completed | plan, value | | subscription_cancelled | reason | **For full event library by business type**: See [references/event-library.md](references/event-library.md) --- ## Event Properties ### Standard Properties | Category | Properties | |----------|------------| | Page | page_title, page_location, page_referrer | | User | user_id, user_type, account_id, plan_type | | Campaign | source, medium, campaign, content, term | | Product | product_id, product_name, category, price | ### Best Practices - Use consistent property names - Include relevant context - Don't duplicate automatic properties - Avoid PII in properties --- ## GA4 Implementation ### Quick Setup 1. Create GA4 property and data stream 2. Install gtag.js or GTM 3. Enable enhanced measurement 4. Configure custom events 5. Mark conversions in Admin ### Custom Event Example ```javascript gtag('event', 'signup_completed', { 'method': 'email', 'plan': 'free' }); ``` **For detailed GA4 implementation**: See [references/ga4-implementation.md](references/ga4-implementation.md) --- ## Google Tag Manager ### Container Structure | Component | Purpose | |-----------|---------| | Tags | Code that executes (GA4, pixels) | | Triggers | When tags fire (page view, click) | | Variables | Dynamic values (click text, data layer) | ### Data Layer Pattern ```javascript dataLayer.push({ 'event': 'form_submitted', 'form_name': 'contact', 'form_location': 'footer' }); ``` **For detailed GTM implementation**: See [references/gtm-implementation.md](references/gtm-implementation.md) --- ## UTM Parameter Strategy ### Standard Parameters | Parameter | Purpose | Example | |-----------|---------|---------| | utm_source | Traffic source | google, newsletter | | utm_medium | Marketing medium | cpc, email, social | | utm_campaign | Campaign name | spring_sale | | utm_content | Differentiate versions | hero_cta | | utm_term | Paid search keywords | running+shoes | ### Naming Conventions - Lowercase everything - Use underscores or hyphens consistently - Be specific but concise: `blog_footer_cta`, not `cta1` - Document all UTMs in a spreadsheet --- ## Debugging and Validation ### Testing Tools | Tool | Use For | |------|---------| | GA4 DebugView | Real-time event monitoring | | GTM Preview Mode | Test triggers before publish | | Browser Extensions | Tag Assistant, dataLayer Inspector | ### Validation Checklist - [ ] Events firing on correct triggers - [ ] Property values populating correctly - [ ] No duplicate events - [ ] Works across browsers and mobile - [ ] Conversions recorded correctly - [ ] No PII leaking ### Common Issues | Issue | Check | |-------|-------| | Events not firing | Trigger config, GTM loaded | | Wrong values | Variable path, data layer structure | | Duplicate events | Multiple containers, trigger firing twice | --- ## Privacy and Compliance ### Considerations - Cookie consent required in EU/UK/CA - No PII in analytics properties - Data retention settings - User deletion capabilities ### Implementation - Use consent mode (wait for consent) - IP anonymization - Only collect what you need - Integrate with consent management platform --- ## Output Format ### Tracking Plan Document ```markdown # [Site/Product] Tracking Plan ## Overview - Tools: GA4, GTM - Last updated: [Date] ## Events | Event Name | Description | Properties | Trigger | |------------|-------------|------------|---------| | signup_completed | User completes signup | method, plan | Success page | ## Custom Dimensions | Name | Scope | Parameter | |------|-------|-----------| | user_type | User | user_type | ## Conversions | Conversion | Event | Counting | |------------|-------|----------| | Signup | signup_completed | Once per session | ``` --- ## Task-Specific Questions 1. What tools are you using (GA4, Mixpanel, etc.)? 2. What key actions do you want to track? 3. What decisions will this data inform? 4. Who implements - dev team or marketing? 5. Are there privacy/consent requirements? 6. What's already tracked? --- ## Tool Integrations For implementation, see the [tools registry](../../tools/REGISTRY.md). Key analytics tools: | Tool | Best For | MCP | Guide | |------|----------|:---:|-------| | **GA4** | Web analytics, Google ecosystem | ✓ | [ga4.md](../../tools/integrations/ga4.md) | | **Mixpanel** | Product analytics, event tracking | - | [mixpanel.md](../../tools/integrations/mixpanel.md) | | **Amplitude** | Product analytics, cohort analysis | - | [amplitude.md](../../tools/integrations/amplitude.md) | | **PostHog** | Open-source analytics, session replay | - | [posthog.md](../../tools/integrations/posthog.md) | | **Segment** | Customer data platform, routing | - | [segment.md](../../tools/integrations/segment.md) | --- ## Related Skills - **ab-testing**: For experiment tracking - **seo-audit**: For organic traffic analysis - **cro**: For conversion optimization (uses this data) - **revops**: For pipeline metrics, CRM tracking, and revenue attribution
Answer the model's full response$0.31 · 133.6s · 14.5k tok
# Cedar & Coil: Meta Pixel + Conversions API Implementation Guide **Store:** Shopify · **Product:** Arc Clip Lamp ($68) · **Status:** Pre-launch. No campaign has run and no performance data exists. **Audience:** The technical marketer setting up tracking before any Meta spend. > **Scope note.** This guide covers how to get conversion signals into Meta accurately and with deduplication. It does not predict how much attribution you will "recover." That depends on your traffic mix, consent rates, browsers, and Meta's own modeling, and none of those can be known before launch. Meta's interfaces and API versions change, so confirm field names and screen paths against current Meta and Shopify documentation as you go. --- ## 1. Recommended Architecture: Browser Pixel + Conversions API, Deduplicated ### The setup ``` Shopper's browser Your server / Shopify ───────────────── ───────────────────── Meta Pixel (fbq) Conversions API (CAPI) ViewContent ── eventID: abc ─┐ ┌── event_id: abc ── ViewContent AddToCart ── eventID: def ─┤ ├── event_id: def ── AddToCart InitiateCheckout ─ eventID: ghi┤ ├── event_id: ghi ── InitiateCheckout Purchase ── eventID: purchase_123 purchase_123 ───── Purchase ▼ ▼ Meta Events Manager (matches event_name + event_id → keeps one) ``` Every key event is sent twice, once from the browser and once from the server. Both copies carry the same `event_name` and the same event ID, and Meta keeps one. ### Why the browser Pixel alone is not enough These are documented behaviors of the browser environment: - **Ad blockers and privacy extensions** can block requests to Meta's domains, so the Pixel never fires. - **Browser tracking protections** (Safari ITP, Firefox ETP) shorten or restrict cookie lifetimes. That can break the link between an ad click and a later purchase. - **Network and page issues** such as a shopper closing the tab or a slow mobile connection can stop the Pixel request from completing. - **Shopify checkout runs in a sandboxed environment.** Checkout and thank-you page tracking must go through Shopify's Customer Events (Web Pixels). Legacy theme code no longer works there. ### Why CAPI alone is not enough - **Matching signals live in the browser.** The `_fbp` browser ID, the `_fbc` click ID (from `fbclid`), the user agent, and the event source URL all originate in the browser. A server-only setup has to capture and pass these deliberately, or match quality suffers. - **Some browsing events never reach your server.** ViewContent and AddToCart happen in the browser. Sending them server-side means building a relay. - **Meta designs and recommends the two to run together.** Redundancy lets you compare the two sources and spot breakage on either side. **Bottom line:** the Pixel provides rich browser context. CAPI provides a delivery path that browser restrictions don't block. Deduplication keeps you from paying for both. --- ## 2. Standard Events and Parameters ### Tracking plan | Event | Trigger | Required / key parameters | Notes | |---|---|---|---| | `ViewContent` | Arc Clip Lamp product page view | `content_ids`, `content_type`, `value`, `currency` | `value` = 68.00 for one unit. Optional: `content_name: "Arc Clip Lamp"`. | | `AddToCart` | Successful add-to-cart (not just a button click) | `content_ids`, `content_type`, `contents` (`id`, `quantity`), `value`, `currency` | `value` = unit price × quantity added. | | `InitiateCheckout` | Checkout starts (Shopify `checkout_started`) | `content_ids`, `contents`, `num_items`, `value`, `currency` | `value` = cart value at checkout start. | | `Purchase` | Order completed (Shopify `checkout_completed` / order webhook) | **`value`** (required), **`currency`** (required), **`content_ids`**, `content_type`, `contents`, `num_items`, `order_id` | Most important event. Also gets the strictest dedup and validation. | ### Parameter rules - **`value`** is a number, not a string with a `$`. Pick one revenue definition and use it in both browser and server events. A common choice is merchandise subtotal after discounts, excluding shipping and tax. Write the definition down here: `________`. - **`currency`** is an ISO 4217 code. This guide assumes `USD` because the price is listed as $68. Confirm the store's currency settings, and if you sell in multiple currencies, send the currency the order was actually charged in. - **`content_ids`** is an array of strings. They **must exactly match the `id` field in the Meta product catalog** connected to your ad account. The native Shopify app generates catalog IDs in its own format, so take the IDs from the catalog rather than assuming the raw Shopify product ID. - **`content_type`** is `"product"` when the IDs are variant- or item-level catalog IDs. Use `"product_group"` only when you are sending item-group IDs. - **`contents`** is an array of objects like `[{ "id": "<catalog id>", "quantity": 1 }]`. ### Example Purchase payload (browser) ```javascript fbq('track', 'Purchase', { value: 68.00, currency: 'USD', content_ids: ['<catalog_id_for_arc_clip_lamp>'], content_type: 'product', contents: [{ id: '<catalog_id_for_arc_clip_lamp>', quantity: 1 }], num_items: 1 }, { eventID: 'purchase_<shopify_order_id>' }); ``` **Track only what informs a decision.** These four events map directly to the funnel you'll optimize and diagnose: product interest, cart intent, checkout start, and sale. Avoid adding custom events until a specific question requires one. --- ## 3. How Deduplication Works ### The matching rule Meta treats a browser event and a server event as duplicates when both of these match: 1. **`event_name`**, for example both are exactly `Purchase`. Event names are case-sensitive. 2. **The event ID.** It is `eventID` in the Pixel's fourth argument and `event_id` in the CAPI payload, and both must be the identical string. Meta then keeps one event and discards the other. Its documentation describes a time window for this matching, which has been stated as 48 hours. Confirm the current window and still send both copies as close in time as possible. A secondary method also exists, matching on `fbp` or `external_id` plus `event_name`. It is less reliable, so don't depend on it. **Always send an explicit event ID.** ### Generating event IDs | Event | ID strategy | Why | |---|---|---| | `Purchase` | Deterministic: `purchase_<shopify_order_id>` | Browser and server can derive the same ID independently. A webhook retry or a thank-you page reload produces the same ID, so it dedups instead of double-counting. | | `ViewContent`, `AddToCart`, `InitiateCheckout` | Random UUID generated in the browser, then passed to the server | The server has no natural shared key for these. The browser must hand its ID to whatever sends the server copy. | ### Common dedup failures | Failure | Result | |---|---| | Browser sends `eventID`, server omits `event_id` | Both counted, so conversions are inflated | | IDs differ in format, e.g. a GID string vs. a numeric order ID | Both counted | | `Purchase` vs. `purchase` | Treated as different events | | Pixel installed twice (native app plus a leftover theme snippet) | Duplicate browser events with different or no IDs | | Server event sent days later (batch job) | May fall outside the dedup window | On Shopify, the order ID can surface in different formats on the browser and server sides: a numeric ID in one place, a `gid://shopify/...` string in another. Normalize both to the numeric ID, and log both values during validation to confirm they match. --- ## 4. Preparing Customer Information for Server-Side Sending CAPI matches events to Meta accounts using `user_data`. Most identifiers must be **normalized, then SHA-256 hashed** before sending. Some must **not** be hashed. ### Hash these (normalize first, then SHA-256, hex-encoded) | Field | Key | Normalization before hashing | |---|---|---| | Email | `em` | Trim whitespace, lowercase | | Phone | `ph` | Digits only, **include country code**, no `+`, spaces, dashes, or leading zeros (e.g. `15551234567`) | | First name | `fn` | Lowercase, remove punctuation, UTF-8 for accented characters | | Last name | `ln` | Same as first name | | City | `ct` | Lowercase, remove spaces and punctuation (e.g. `sanfrancisco`) | | State | `st` | Lowercase 2-letter code for US (e.g. `ca`) | | Zip | `zp` | US: first 5 digits, lowercase, no spaces | | Country | `country` | Lowercase ISO 3166-1 alpha-2 (e.g. `us`) | | External ID | `external_id` | Your stable customer ID. Hashing is recommended. Use the same value in browser and server events. | ### Do NOT hash these | Field | Key | Source on Shopify | |---|---|---| | Client IP address | `client_ip_address` | Order `client_details.browser_ip` / `browser_ip` | | User agent | `client_user_agent` | Order `client_details.user_agent` (**required** for `action_source: "website"`) | | Click ID | `fbc` | `_fbc` cookie, or build `fb.1.<ms_timestamp>.<fbclid>` from the landing URL | | Browser ID | `fbp` | `_fbp` cookie | ### Rules - **Never send plaintext PII.** Hash on your server before the request leaves it. - **Omit empty fields.** Don't hash an empty string, because that produces a valid-looking but meaningless hash. - **Don't guess a country code.** If a phone number lacks one and you can't determine it reliably from the order's country, omit `ph`. - **Send only what you collect legitimately and need for matching.** Never put PII in `custom_data` or event names. - **Use Event Match Quality as a guide.** Events Manager shows an Event Match Quality score per event. Low scores tell you which identifiers are missing. They do not tell you how many conversions you're losing. --- ## 5. Shopify Setup Path ### Option A: Native Meta sales channel (the "Facebook & Instagram" app) **How it works:** You install the app, connect your Business portfolio, ad account, Pixel, and catalog, then choose a **customer data-sharing level**. The maximum level turns on server-side events via CAPI alongside the Pixel. Shopify generates event IDs and handles deduplication, and its consent handling integrates with Shopify's Customer Privacy settings. | Pros | Cons | |---|---| | No code; can be done in an afternoon | Less control over the exact `value` definition and parameter mapping | | Dedup, hashing, and checkout events handled by Shopify | Harder to inspect exactly what is sent; you rely on Events Manager diagnostics | | Catalog sync keeps `content_ids` consistent with the catalog automatically | Custom events or enrichment (e.g. margin-based value) not supported | | Maintained as Shopify and Meta APIs change | Behavior can change with app updates outside your control | ### Option B: Custom implementation **How it works:** - **Browser side:** a custom pixel in **Settings → Customer events** using Shopify's Web Pixels API. It subscribes to `product_viewed`, `product_added_to_cart`, `checkout_started`, and `checkout_completed`. - **Server side:** a small service that receives Shopify **order webhooks** (`orders/paid` or `orders/create`) and sends CAPI events. - **Funnel events server-side:** for ViewContent, AddToCart, and InitiateCheckout, you also need a relay endpoint that receives the browser's event ID and context. | Pros | Cons | |---|---| | Full control over value, IDs, parameters, and consent logic | Requires a developer, hosting, secrets management, and monitoring | | Easy to add enrichment later | You own dedup correctness, hashing, retries, and API version upgrades | | Payloads are fully inspectable and loggable | Must capture `_fbp`, `_fbc`, and consent into the order yourself, e.g. via cart attributes | | | A silent failure, like an expired token, can go unnoticed without alerting | ### Recommendation for Cedar & Coil: start with the native app **The decision is driven by Cedar & Coil's situation:** - **One product, no existing data.** Cedar & Coil is a small DTC brand selling one $68 product, with no campaign history. - **The goal is reliable tracking before the first dollar of spend.** You need trustworthy Purchase data quickly, not a custom data pipeline. - **The native app covers the requirement.** It delivers Pixel + CAPI with deduplication and catalog-consistent `content_ids`, with the fewest moving parts that can break. **What you trade away:** control over the revenue definition, custom enrichment, and payload-level visibility. **Revisit a custom build if any of these become true:** - You need value-based optimization on something other than order revenue. - Validation (Section 6) shows a defect in the app's events that you can't fix through its settings. - Consent requirements in your selling regions need logic the app doesn't support. ### Native app setup steps 1. **Remove legacy Pixel code first.** Search `theme.liquid` and theme snippets for `fbq(` or `connect.facebook.net`. Also check for any old Pixel in checkout "Additional scripts" or existing Customer Events custom pixels, and remove or disable them. *This is the most common source of duplicate events.* 2. **Install** the Facebook & Instagram sales channel from the Shopify App Store. 3. **Connect assets:** Business portfolio, ad account, Pixel (create one or select the existing one), Facebook Page, and catalog. 4. **Set data sharing to the maximum level,** which enables Conversions API. Review the consent behavior the app describes before confirming. 5. **Verify your domain** in Meta Business settings (Brand safety → Domains). 6. **Confirm catalog sync.** The Arc Clip Lamp should appear in the Meta catalog, and its catalog ID is what `content_ids` should carry. 7. **Configure Shopify's customer privacy and consent banner** for the regions you sell to (see Section 7). 8. **Proceed to validation** (Section 6) before launching ads. ### Code sketch: server-side Purchase event (custom path, for reference) This sketch shows the server half of Option B, or a future migration. It assumes: - A Shopify `orders/paid` webhook. - A theme or custom-pixel script that writes `_fbp`, `_fbc`, and the shopper's marketing-consent status into **cart attributes**. Shopify copies these onto the order as `note_attributes`. - A browser custom pixel that fires `Purchase` with `eventID: 'purchase_<numeric order id>'`. ```javascript // Node 18+ (global fetch). Sketch only — add logging, retries, alerting, secret rotation. import crypto from 'node:crypto'; import express from 'express'; const { META_PIXEL_ID, META_CAPI_TOKEN, // System User access token; store in a secret manager META_GRAPH_VERSION, // pin to a current version, e.g. 'vXX.0' SHOPIFY_WEBHOOK_SECRET, META_TEST_EVENT_CODE // set ONLY during validation; unset in production } = process.env; const app = express(); // ---------- normalization + hashing ---------- const sha256 = (v) => crypto.createHash('sha256').update(v, 'utf8').digest('hex'); const lower = (v) => (v ?? '').toString().trim().toLowerCase(); const hashed = (v) => (v ? [sha256(v)] : undefined); // never hash empty strings const normEmail = (e) => lower(e); const normName = (n) => lower(n).replace(/[^\p{L}]/gu, ''); // letters only const normCity = (c) => lower(c).replace(/[^\p{L}]/gu, ''); const normState = (s) => lower(s); // 'CA' -> 'ca' const normZip = (z, country) => lower(country) === 'us' ? lower(z).replace(/\s/g, '').slice(0, 5) : lower(z).replace(/\s/g, ''); const normCountry = (c) => lower(c); // 'US' -> 'us' const normPhone = (p) => { if (!p) return ''; const raw = p.toString().trim(); if (!raw.startsWith('+')) return ''; // don't guess a country code; omit instead return raw.replace(/\D/g, '').replace(/^0+/, ''); }; const attr = (order, name) => (order.note_attributes || []).find((a) => a.name === name)?.value; // ---------- webhook authenticity ---------- function verifyShopifyHmac(rawBody, hmacHeader) { const digest = crypto.createHmac('sha256', SHOPIFY_WEBHOOK_SECRET).update(rawBody).digest('base64'); const a = Buffer.from(digest); const b = Buffer.from(hmacHeader || ''); return a.length === b.length && crypto.timingSafeEqual(a, b); } // ---------- catalog ID mapping ---------- // MUST return the exact `id` used in the Meta catalog for this item. function catalogIdFor(lineItem) { return String(lineItem.variant_id); // placeholder — replace with your catalog's ID format } app.post('/webhooks/orders-paid', express.raw({ type: 'application/json' }), async (req, res) => { if (!verifyShopifyHmac(req.body, req.get('X-Shopify-Hmac-Sha256'))) return res.sendStatus(401); res.sendStatus(200); // ack fast; process after (or enqueue) const order = JSON.parse(req.body.toString('utf8')); // Consent gate: only send if the shopper granted marketing consent (captured at browse/checkout). if (attr(order, '_marketing_consent') !== 'granted') return; const addr = order.billing_address || order.shipping_address || {}; const country = addr.country_code; const lineItems = order.line_items || []; const contents = lineItems.map((li) => ({ id: catalogIdFor(li), quantity: li.quantity })); const event = { event_name: 'Purchase', event_time: Math.floor(new Date(order.processed_at || order.created_at).getTime() / 1000), event_id: `purchase_${order.id}`, // identical string to the browser eventID action_source: 'website', event_source_url: order.order_status_url, // or the thank-you page URL you capture user_data: { em: hashed(normEmail(order.email)), ph: hashed(normPhone(order.phone || addr.phone)), fn: hashed(normName(addr.first_name)), ln: hashed(normName(addr.last_name)), ct: hashed(normCity(addr.city)), st: hashed(normState(addr.province_code)), zp: hashed(normZip(addr.zip, country)), country: hashed(normCountry(country)), external_id: order.customer?.id ? hashed(String(order.customer.id)) : undefined, // NOT hashed: client_ip_address: order.client_details?.browser_ip || order.browser_ip, client_user_agent: order.client_details?.user_agent, fbp: attr(order, '_fbp'), fbc: attr(order, '_fbc') }, custom_data: { currency: order.currency, // e.g. 'USD' value: Number(order.current_subtotal_price), // match your documented value definition content_ids: contents.map((c) => c.id), content_type: 'product', contents, num_items: lineItems.reduce((n, li) => n + li.quantity, 0), order_id: String(order.id) } }; // Drop undefined keys so Meta doesn't receive empty fields. event.user_data = Object.fromEntries(Object.entries(event.user_data).filter(([, v]) => v)); const body = { data: [event] }; if (META_TEST_EVENT_CODE) body.test_event_code = META_TEST_EVENT_CODE; const url = `https://graph.facebook.com/${META_GRAPH_VERSION}/${META_PIXEL_ID}/events?access_token=${META_CAPI_TOKEN}`; const resp = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const result = await resp.json(); // Log result.events_received and result.fbtrace_id. On failure, retry with the SAME event_id // (safe: duplicates dedup). Alert on repeated failures (e.g. expired token). console.log(JSON.stringify({ order: order.id, status: resp.status, result })); }); app.listen(3000); ``` **Things the sketch shows but you must confirm:** - `catalogIdFor()` must match your catalog's actual ID format. - The browser and server `value` definitions must match. - The browser order ID must resolve to the same numeric `order.id`. - `event_time` must be recent. Meta rejects events older than its limit (documented as 7 days), so don't batch Purchase sends. --- ## 6. End-to-End Validation Before Scaling Spend Treat this as a pass/fail matrix. **An event is "clean" only when it passes every row.** Anything "fine, but…" goes on the findings list with its location and the standard it breaks. ### Step 1: Browser-side check - [ ] Install **Meta Pixel Helper** (Chrome extension). Walk the funnel: product page → add to cart → checkout → (test) purchase. - [ ] Each event fires **once** per action. No duplicate Pixel IDs and no second Pixel. - [ ] Each event shows an event ID. - [ ] Parameters populate: `value` is numeric, `currency` is correct, and `content_ids` matches the catalog ID. - [ ] Checkout and purchase events fire inside Shopify's checkout. Use Events Manager's Test Events (Step 2) for this, because the Helper may not see the sandboxed checkout pixels. ### Step 2: Test Events in Events Manager - [ ] Open **Events Manager → your Pixel → Test events**. Use the browser test option, and for a custom build set `test_event_code` on server requests. - [ ] Place a **real test order.** Use Shopify's test/Bogus gateway, or a real order you refund. Note the order ID. - [ ] For each of the four events, confirm **both** a Browser and a Server event appear. - [ ] Confirm the two copies show as **deduplicated**, with matching event name and event ID. - [ ] For Purchase: `value` equals the order's value under your documented definition, `currency` is correct, `content_ids` matches the catalog, and `order_id` is present. ### Step 3: Event-level diagnostics (after real traffic) - [ ] **Overview:** Browser and Server sources reported for each event, with dedup reported. - [ ] **Diagnostics tab:** no open errors (missing parameters, mismatched IDs, invalid currency, low dedup coverage). - [ ] **Event Match Quality:** note the score per event as a baseline. If it's low, check which `user_data` fields are missing. - [ ] **Catalog match rate:** shows that `content_ids` match catalog items. ### Step 4: Reconcile against Shopify over a closed window Do this after several days of live traffic, still before scaling. - **Use one closed window.** Choose a completed date range, e.g. last full Monday–Sunday, and pull Shopify orders and Meta Purchase events for that exact same range. - **Align time zones.** Confirm the Shopify store and Meta ad account time zones, or convert one to the other. - **Exclude non-comparable orders.** Leave out test and refunded test orders, plus any orders from channels without a Pixel journey (e.g. manual draft orders). - **Compute from rows.** Export the order list and the event list and compare them with a spreadsheet or script rather than by eye. Check counts **and** summed value. - **Spot-check by ID.** Pick 10 orders by `order_id` and confirm each appears in Meta exactly once. ### Step 5: Interpret gaps carefully A gap between Shopify and Meta counts is a **symptom, not a diagnosis.** State what you observed, and treat the cause as a hypothesis until you can show the mechanism. | Observation | Possible explanation (hypothesis) | How to confirm | |---|---|---| | Meta Purchases > Shopify orders | Would be explained by failed dedup or a second Pixel | Find duplicate rows for one `order_id`; check event IDs on both copies | | Meta Purchases < Shopify orders | Consistent with consent-declined shoppers, server send failures, or orders outside the window | Check server logs for those order IDs; check consent status on missing orders | | Purchase value differs from Shopify revenue | Would be explained by different value definitions (tax/shipping/discounts) | Compare the payload value for one order against its Shopify breakdown | | Only Browser events, no Server | Consistent with CAPI disabled or token/connection issue | Check the app's data-sharing level; check server response logs | ### Exit criteria before scaling spend - All four events show both sources and are deduplicated. - Purchase parameters are correct on spot-checked orders. - No open Diagnostics errors. - The closed-window reconciliation has no **unexplained** gaps. Explained gaps, like consent declines, are documented. ### After launch Re-check Diagnostics weekly, and alert on server send failures. Any theme change, app install, or checkout change requires re-running Steps 1–2. --- ## 7. Consent and Compliance Note *This is implementation guidance, not legal advice. Confirm requirements with counsel for the regions you sell to.* - **Consent applies to both paths.** If a shopper declines marketing or tracking consent, suppress or limit **both** the Pixel and the CAPI event. A server-side path is not a way around a declined banner. - **Configure Shopify's consent tools.** Set up Shopify's Customer Privacy settings and consent banner, or a compatible consent platform, for every region you sell to. The native Meta app reads Shopify's consent signals. A custom build must read the Customer Privacy API in the browser and carry the consent state to the server, as the sketch does with `_marketing_consent`. - **EU/UK and similar regimes** generally require opt-in before marketing tracking. - **US state privacy laws.** Some, such as California's, give shoppers rights to opt out of the "sale/sharing" of data for targeted advertising. Meta supports a **Limited Data Use** flag (`data_processing_options`) for these cases. Check Meta's current documentation for the exact values and when to apply them. - **Disclose and minimize.** Update the store privacy policy to state that you share data with Meta for advertising and measurement. Send only the identifiers listed in Section 4, always hashed where required, and never put PII in event names or `custom_data`. - **Protect credentials.** Keep the CAPI access token in a secret manager, use a System User token rather than a personal one, and restrict who can access it. - **Keep reporting honest.** Campaign work is draft-only and no performance data exists yet. Present tracking outputs as measurement infrastructure, not results. Don't cite conversion rates, ROAS, or recovery figures until real, reconciled data exists. --- ### One-page checklist - [ ] Legacy Pixel code removed from theme and checkout - [ ] Facebook & Instagram app installed; Pixel, ad account, and catalog connected - [ ] Data sharing set to the level that enables Conversions API - [ ] Domain verified - [ ] Consent banner and Customer Privacy configured for selling regions - [ ] Value definition documented: `________` - [ ] Test order: all four events show Browser + Server, deduplicated - [ ] Purchase `value`, `currency`, `content_ids`, and `order_id` verified against the order - [ ] Diagnostics clean; Event Match Quality baseline recorded - [ ] Closed-window Shopify vs. Meta reconciliation done from exported rows - [ ] Gaps documented as observations with hypotheses and confirmation steps - [ ] Only then: launch and scale spend
Score the judge's verdict, criterion by criterion11/11 criteria passed
RequirementVerdictEvidence
architecture
The guide recommends browser Pixel plus server-side Conversions API with deduplication and explains why both are needed under browser privacy limits.
✓Section 1 recommends Pixel plus CAPI with deduplication and explains why Pixel alone fails (ad blockers, Safari ITP/Firefox ETP, sandboxed checkout) and why CAPI alone fails (browser-origin matching signals, ViewContent/AddToCart never reach the server).
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓The Section 2 table covers ViewContent, AddToCart, InitiateCheckout and Purchase with key parameters, and Purchase explicitly requires value, currency and content_ids.
code_sketch
A concrete server-side Purchase event code sketch or request example is included showing event_name, event_time, event_id, action_source, and a user_data block.
✓The Node sketch builds an event with event_name 'Purchase', event_time, event_id, action_source 'website' and a user_data block, then POSTs it to the Graph API events endpoint.
validation
End-to-end validation is described using Meta's Events Manager test events tool and an explicit check that duplicate browser/server events are being deduplicated.
✓Step 2 uses Events Manager Test events with test_event_code and requires that 'the two copies show as deduplicated, with matching event name and event ID'.
sources_defined
For each event it is clear where it fires (browser vs server) and what the source of truth is (e.g. Purchase from the Shopify order webhook/server, not only the thank-you page).
✓The tracking plan table gives each event's trigger (Shopify product_viewed, checkout_started, checkout_completed / order webhook), and Section 5 and the sketch send Purchase server-side from the orders/paid webhook while the funnel events use a browser-to-server relay.
limits_stated
Limitations are stated honestly: no promised attribution-recovery percentages, and consent/regional rules are noted as constraints on what may be sent.
✓The scope note declines to predict attribution recovery, and Section 7 states that consent applies to both Pixel and CAPI, with regional rules (EU/UK opt-in, US state laws and Limited Data Use) constraining what is sent.
dedup_correct
Deduplication is technically correct: the same event_id and event_name sent on both the Pixel and CAPI event so Meta drops the duplicate; not a vague mention.
✓Section 3 states dedup requires an identical event_name and an identical event ID (eventID in the Pixel and event_id in CAPI), explains case sensitivity, and lists common failures.
event_id_retry_stability
The event_id is generated or derived once per commerce event, shared by browser and server, and reused unchanged on webhook retries or order updates; a new random suffix per send or retry fails.
✓Purchase uses a deterministic purchase_<shopify_order_id> so 'a webhook retry or a thank-you page reload produces the same ID', and the sketch comments say to retry with the SAME event_id.
event_time_stable
The server Purchase event uses the purchase/order occurrence timestamp in Unix seconds and preserves it across retries; using the current send or retry time fails.
✓The sketch sets event_time to Math.floor(new Date(order.processed_at || order.created_at).getTime()/1000), the order timestamp in Unix seconds, so retries reuse the same value.
pii_hashing
Customer data handling is correct: personally identifiable fields (e.g. email) are normalized (trimmed, lowercased) and SHA-256 hashed before sending in user_data.
✓Section 4 and the code normalize (trim, lowercase, phone digits only) and SHA-256 hash em, ph, fn, ln, ct, st, zp, country and external_id, while leaving IP, user agent, fbp and fbc unhashed and omitting empty fields.
actionable_path
The recommended Shopify path is decisive and executable for a small DTC store (a clear recommendation with concrete setup steps, not an undifferentiated list of options).
✓It compares native vs custom, decisively recommends the native Facebook & Instagram app for a one-product small DTC store, and gives eight concrete setup steps plus revisit triggers.