← Run 20261118-175617-f3bfc2f3
Shopify to Meta ads conversion tracking implementation
task shopify-meta-capiNov 18, 2026Models on marketing tasks + Marketing Skillsskill analytics

Answers & verdicts

Claude Sonnet 5.5 high effort

Task failed
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." metadata: version: 2.2.0 --- # 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. 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. --- ## 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
✓ Attempt 1
Answer · attempt 1 the model's full response$0.33 · 108.9s · 12.0k tok
I'll check a few current Meta and Shopify details before writing the guide.# Cedar & Coil: Meta Conversion Tracking Implementation Guide (Shopify → Pixel + CAPI) **Scope:** Arc Clip Lamp ($68), Shopify store, Meta ads in draft stage. No campaign has launched and no performance data exists, so nothing here is a performance claim. **Verification note:** I checked the Meta developer docs, Meta's Shopify help page, and several third-party guides (listed at the end). I hit a search limit partway through. Items marked **[confirm]** come from general knowledge, not a source I checked, so check them against current Meta or Shopify docs before you build. --- ## 1. Recommended architecture and why both channels are needed **Architecture:** run the browser Meta Pixel and the server-side Conversions API (CAPI) together. Send the same four standard events from both channels, each with a shared `event_id`, so Meta counts each action once. ``` Shopper browser ──► Meta Pixel (fbq) ─────────────┐ │ ▼ │ (cookies _fbp/_fbc, UA, IP) Meta dataset (Pixel ID) ▼ ▲ dedup on event_name + event_id Shopify (checkout, order) ──► server ──► CAPI ────┘ ``` **Why both:** - **The Pixel alone depends on the browser.** Ad blockers, tracking-prevention features, in-app browsers, and consent choices can stop the script or its cookies. Those losses are silent. - **CAPI alone loses browser signals.** Pixel events carry click and browser identifiers (`fbc`, `fbp`) and see on-site behavior like ViewContent and AddToCart. CAPI can only send those if you capture and forward them yourself. - **Together, Meta gets two paths for the same event.** Deduplication stops the overlap from double-counting. Don't expect the two channels to produce identical counts. The goal is a more resilient signal, not a recovery figure. Measure how your own store behaves in section 6. **Naming exception:** the analytics skill's default is lowercase snake_case. Meta's standard events are case-sensitive PascalCase (`Purchase`, not `purchase`). Use Meta's names exactly. A name mismatch breaks deduplication. --- ## 2. Standard events and key parameters | Event | Trigger | Key parameters | |---|---|---| | **ViewContent** | Arc Clip Lamp product page loads | `content_ids`, `content_type`, `content_name`, `value`, `currency` | | **AddToCart** | Add-to-cart success | Same as ViewContent, plus `contents` with `quantity` | | **InitiateCheckout** | Checkout begins | `content_ids`, `contents`, `num_items`, `value`, `currency` | | **Purchase** | Order confirmed/paid | **`value`, `currency` (required)**, **`content_ids`**, `content_type`, `contents`, `num_items`, optional `order_id` | Parameter rules: - **`value`:** a decimal number in the currency's base unit, not a string and not cents. For one lamp, that is `68.00` in USD, not `6800`. - **`currency`:** ISO 4217 code, e.g. `USD`. - **`content_ids`:** one stable ID per product or variant, as strings. The ID must be identical on the Pixel and server sides and match your catalog if you run catalog ads. Pick the Shopify variant ID or SKU and never mix schemes. **[confirm]** The native Shopify app may use its own ID format for catalog matching, so inspect what it sends. - **`contents`:** `[{ "id": "...", "quantity": 1, "item_price": 68.00 }]`. - **`content_type`:** `product` for individual variant IDs. **Decide the Purchase `value` policy once and document it.** I recommend merchandise value after discounts, excluding tax and shipping. Whatever you pick, use it on both channels and never change it mid-flight, or reported ROAS will shift without any real change in performance. Website events sent via CAPI also require `action_source` (`website`), `event_source_url`, and `client_user_agent`, per Meta's parameters documentation. Skip AddPaymentInfo at launch. Every event should inform a decision, and these four cover the funnel for a single-SKU store. --- ## 3. How deduplication works Meta collapses a Pixel event and a server event into one when all of these are true: 1. **Same `event_name`**, case-sensitive. `Purchase` and `purchase` do not match. 2. **Same event ID.** The Pixel's `eventID` must equal the server's `event_id`. 3. **Received within 48 hours** of the first event Meta received with that ID. Practical rules: - **Generate one ID per action and use it in both places.** The Pixel call is: ```js fbq('track', 'Purchase', {value: 68.00, currency: 'USD', content_ids: ['<variant_id>'], content_type: 'product'}, {eventID: 'purchase_<order_id>'}); ``` - **For Purchase, derive the ID from the Shopify order ID** (`purchase_<order_id>`). Both sides can compute it independently, so no coordination is needed. For ViewContent, AddToCart, and InitiateCheckout, generate a UUID in the browser and pass it to your server endpoint. - **Send the server event promptly, after the browser event.** One source states that matching works when the browser event arrives first and the server event second. Another says delayed or batched server sends beyond 48 hours won't deduplicate. A server event is not discarded just because no browser event was seen. - **Fallback matching:** one source says Meta can deduplicate without `event_id` using event name plus `fbp` and/or `external_id`. Treat that as a safety net, not the plan. - **Customer data does not deduplicate.** `fbp`, `fbc`, and `em` improve matching, but only `event_name` + `event_id` deduplicate. - **Mismatch symptom:** server events counted separately from browser events, which inflates Purchase counts. --- ## 4. Preparing customer information for server-side sending Meta requires hashing for most identifiers. Normalize first, then hash with SHA-256 and send lowercase hex. A wrongly normalized value hashes cleanly but never matches anyone, so there is no error to warn you. | Field | Normalize before hashing | Hash? | |---|---|---| | `em` | Trim whitespace, lowercase | Yes | | `ph` | Digits only, with country code (E.164 without symbols), no leading trunk zero | Yes | | `fn`, `ln` | Lowercase, strip punctuation and spaces | Yes | | `ct` | Lowercase, no spaces | Yes | | `st` | Two-letter lowercase code | Yes | | `zp` | Lowercase, no spaces or hyphens (for US, use the first 5 digits **[confirm]**) | Yes | | `country` | Two-letter lowercase code | Yes | | `external_id` | Stable ID, e.g. Shopify customer ID | Hashing recommended | | `client_ip_address` | As captured | **No** | | `client_user_agent` | As captured | **No** | | `fbp`, `fbc` | As read from cookies/URL | **No** | Handling notes: - **Send arrays for hashed fields** (`"em": ["<hash>"]`), and **omit** empty fields entirely. Never hash an empty string. - **Hash on the server.** Don't ship raw PII to the browser for this. - **Capture `_fbp`, `_fbc`, and the user agent in the browser** at cart time and store them as Shopify cart attributes. They then arrive with the order and can be forwarded unhashed. - **Hashing is pseudonymization, not anonymization.** See section 7. --- ## 5. Shopify setup path ### Option A: native Facebook & Instagram app (Meta sales channel) **Setup (from Meta's help page):** - **Prerequisites:** a Shopify store that isn't password-protected, Basic plan or higher, a Facebook Page, a Meta business portfolio owning that Page, and admin permissions on the portfolio. - **Install:** Sales channels → Facebook and Instagram → Add app → Start setup → Login with Facebook, then connect the Pixel/dataset. - **Settings:** choose **Enhanced or Maximum** data sharing and **Always on** (or Optimized) data access. Meta recommends Always on for the most reliable performance. Enhanced and Maximum are the levels that send events through CAPI alongside the Pixel. Standard is Pixel-only. | | Native app | Custom implementation | |---|---|---| | Build effort | Minutes to hours | Days, plus ongoing maintenance | | Deduplication | Handled by the app | You own `event_id` design | | Control over `value` and `content_ids` | Limited | Full | | Failure modes | Fewer, but opaque | Webhook failures, retries, token expiry, API version drift | | Cost | Free | Developer time and hosting | | Best for | Standard store, one pixel | Unusual value logic, multi-store, custom events | ### Recommendation: Option A for Cedar & Coil This follows from the launch goal: a single $68 SKU with a small team and no historical data. The priority is getting a trustworthy Purchase signal live before spend starts. The native app delivers that fastest, with deduplication and consent plumbing already built. You trade away control of the `event_id` scheme, the `value` definition, and how `fbc`/`fbp` are captured. **Revisit a custom build only if** validation (section 6) shows the app's `content_ids` or `value` don't match your catalog or reporting needs, or if you add things the app can't send (e.g., subscriptions, a second storefront). **Do not run both.** If you add a custom Purchase pipeline while the native app's CAPI is on, you'll have two server senders with different IDs and will double-count. ### Option B: code sketch of a server-side Purchase This sketch is for the custom path. It runs from a Shopify `orders/paid` webhook. Treat it as a sketch, not production code. Field names reflect the Shopify Order payload **[confirm against your API version]**. ```js // purchase-capi.mjs (Node 18+) import crypto from "node:crypto"; const PIXEL_ID = process.env.META_PIXEL_ID; const TOKEN = process.env.META_CAPI_TOKEN; // keep in a secret store const API_VER = process.env.META_API_VERSION || "v25.0"; // confirm current version const TEST_CODE = process.env.META_TEST_EVENT_CODE; // set ONLY while testing const sha256 = (s) => crypto.createHash("sha256").update(s).digest("hex"); const clean = (s) => (s ?? "").toString().trim(); const h = (v, fn = (x) => x) => { const n = fn(clean(v)); return n ? [sha256(n)] : undefined; }; const lc = (x) => x.toLowerCase(); const alnumLc = (x) => x.toLowerCase().replace(/[^a-z0-9]/g, ""); const phone = (x) => { const d = x.replace(/\D/g, ""); return d.length === 10 ? "1" + d : d; }; const attr = (order, name) => (order.note_attributes || []).find((a) => a.name === name)?.value; export function buildPurchaseEvent(order) { const b = order.billing_address || order.shipping_address || {}; const user_data = { em: h(order.email, lc), ph: h(order.phone || b.phone, phone), fn: h(b.first_name, alnumLc), ln: h(b.last_name, alnumLc), ct: h(b.city, alnumLc), st: h(b.province_code, alnumLc), zp: h(b.zip, alnumLc), country: h(b.country_code, alnumLc), external_id: h(order.customer?.id?.toString()), // NOT hashed: client_ip_address: attr(order, "_client_ip") || order.browser_ip, client_user_agent: attr(order, "_client_ua"), // required for website events fbp: attr(order, "_fbp"), fbc: attr(order, "_fbc"), }; Object.keys(user_data).forEach((k) => user_data[k] === undefined && delete user_data[k]); return { event_name: "Purchase", // exact, case-sensitive event_time: Math.floor(Date.parse(order.processed_at || order.created_at) / 1000), event_id: `purchase_${order.id}`, // must equal Pixel eventID action_source: "website", event_source_url: order.order_status_url, user_data, custom_data: { value: Number(order.current_subtotal_price), // policy: after discounts, excl. tax/shipping currency: order.currency, // e.g. "USD" content_type: "product", content_ids: order.line_items.map((li) => String(li.variant_id)), contents: order.line_items.map((li) => ({ id: String(li.variant_id), quantity: li.quantity, item_price: Number(li.price), })), num_items: order.line_items.reduce((n, li) => n + li.quantity, 0), order_id: String(order.id), }, }; } export async function sendPurchase(order) { const body = { data: [buildPurchaseEvent(order)], access_token: TOKEN }; if (TEST_CODE) body.test_event_code = TEST_CODE; // remove for production const res = await fetch(`https://graph.facebook.com/${API_VER}/${PIXEL_ID}/events`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); const json = await res.json(); if (!res.ok || json.events_received !== 1) { throw new Error(`CAPI failure: ${res.status} ${JSON.stringify(json)}`); // queue + retry } return json; } ``` Production hardening that the sketch leaves out: - **Verify the Shopify webhook HMAC** before processing. - **Make the handler idempotent.** Key on `order.id` so webhook retries don't send twice. - **Retry with backoff on 5xx**, and stay well inside the 48-hour dedup window and the 7-day `event_time` limit. - **Capture `_fbp`, `_fbc`, and user agent into cart attributes** in the theme. Without them, match quality drops. - **Make `order.id` match the Pixel's order ID.** If the Pixel's purchase event reports a different ID, dedup will fail. Check this during testing. --- ## 6. Validation before scaling spend Run this sequence before any budget is committed. Meta's Test Events caveat matters here: events sent with a `test_event_code` are **not dropped**. They flow into Events Manager and are used for targeting and measurement. Use test codes sparingly, and remove them from production payloads. **Step 1: Test each channel.** - Events Manager → Data Sources → your Pixel → **Test Events**. Copy the test code. - On the native app, open the store in a browser session and walk the funnel: product page → add to cart → checkout → place a test order. Confirm all four events appear. - Confirm each event shows both a **Browser** and a **Server** source. **Step 2: Confirm deduplication.** - The same action should appear as one event, not two, with browser and server both attached. - If Purchase shows twice, check the name casing, the event ID on both sides, and the timing gap. **Step 3: Check parameters.** - Purchase has `value` as a number and the right `currency`. - `content_ids` match the catalog or variant IDs. - A $68 single-lamp order reports `68.00` under your documented value policy. - No raw PII appears in any parameter, and hashed fields look like 64-character hex strings. **Step 4: Check match quality.** - Review Event Match Quality in Events Manager. If it's weak, check whether the app's data sharing level, or your custom `em`/`ph`/`fbp`/`fbc` capture, is the cause. **Step 5: Reconcile against Shopify over a closed window.** - Pick a fully completed date range, e.g. a whole week. - Export Shopify orders for that range. Export Meta Purchase events for the **same** range, with the same timezone. - Compute counts and summed values **with a script**, not by eye, and cross-check each total a second way. - Chase any difference down to specific order IDs. Common causes are test orders left in, refunds or cancellations, timezone boundaries, and duplicate sends. - Don't set a pass threshold in advance from someone else's benchmark. Establish what a clean reconciliation looks like for your own store, and record the explanation for any gap. **Step 6: Clean up.** - Remove `test_event_code` from any custom sender. - Remove or tag test orders. - Document the final event names, ID scheme, value policy, and who owns the token. **Soft launch:** start with modest spend. Re-run the reconciliation after the first full week of real orders. Don't judge ad performance on a window that has only partial data. --- ## 7. Consent and compliance note *This is a practical checklist, not legal advice. Have counsel review it for your markets.* - **CAPI does not bypass consent.** Where law or policy requires consent (e.g. the EU/UK and some US states), server-side sending still needs a lawful basis. Connect your consent banner to the Shopify customer privacy settings so both the Pixel and the server path honor opt-outs. - **Hashing is not anonymization.** Hashed emails and phone numbers are still personal data in most privacy regimes. - **Data minimization:** send only the fields that the tracking plan uses. For a one-SKU store, that is email, phone, name/address fields at purchase, and the browser identifiers. - **Disclose it.** Your privacy policy should say you share purchase and customer data with Meta for advertising and measurement. - **Check the data sharing setting deliberately.** Enhanced and Maximum share more customer data than Standard. Pick the level your consent posture supports, and don't default to the highest one just for matching. - **Honor deletion and opt-out requests** in your own systems, and don't put PII in event properties, URLs, or order notes sent to Meta. - **US state laws:** Meta offers restricted-data options for some state laws. Ask counsel whether you need them **[confirm in current Meta docs]**. - **Ad content:** this guide covers tracking only. All campaign work stays draft-only, with no invented reviews, scarcity, or performance claims. --- ## Sources checked - Meta for Developers, Conversions API Parameters (v25.0): required website-event parameters and the hashing/no-hash field list. - Meta for Developers, Using the API: the Test Events tool and `test_event_code` behavior. - Meta Business Help, "Connect Shopify to Facebook and Instagram" (facebook.com/business/help/646757258759189): prerequisites, data sharing and access settings. - Third-party guides, used for supporting detail on deduplication timing, normalization rules, and Shopify data sharing levels: relevantaudience.com, blazebytesolutions.com, daniilmaximkin.com, lukaswojcik.com, enalitica.com, cometly.com, ultro.co.jp, attribuly.com. The third-party sources are secondary, so check any rule that affects your build against Meta's own docs.
Score · attempt 1 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 a shared event_id, and explains that ad blockers, tracking prevention and consent choices cause silent Pixel loss while CAPI alone lacks fbc/fbp browser signals.
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 parameters, and Purchase lists value, currency (required) 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's buildPurchaseEvent returns event_name 'Purchase', event_time, event_id, action_source 'website' and a user_data block, and sendPurchase 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.
✓Section 6 uses Events Manager Test Events, checks that each event shows both Browser and Server sources, and has a dedicated 'Confirm deduplication' step that shows one event instead of two.
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).
✓Triggers are tabulated, the Purchase server event runs from the Shopify orders/paid webhook with the ID derived from order.id, and the other events use a browser-generated UUID passed to the server endpoint; the browser-versus-server split is somewhat implicit.
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 guide says 'The goal is a more resilient signal, not a recovery figure' and gives no percentages, and section 7 states that CAPI does not bypass consent, with regional rules and data-sharing levels as constraints.
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 requires the same case-sensitive event_name and the same event ID (Pixel eventID equals server event_id) within 48 hours, with a concrete fbq eventID example, and says customer data does not deduplicate.
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 the deterministic event_id `purchase_${order.id}` on both sides, the handler is made idempotent on order.id so retries don't resend, and other events use one UUID per action shared with the server.
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.
✓event_time is Math.floor(Date.parse(order.processed_at || order.created_at)/1000), the order timestamp in Unix seconds, so it stays the same on retries rather than using the send time.
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 trim and lowercase em, normalize the other identifiers, SHA-256 hash to lowercase hex in arrays, and leave IP, user agent, fbp and fbc unhashed.
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 the native app with a custom build, decisively recommends the native Meta app for a small single-SKU store with concrete install and settings steps, and gives conditions for revisiting a custom build.
✓ Attempt 2
Answer · attempt 2 the model's full response$0.36 · 130.2s · 14.9k tok
I'll check a few details that change often (Meta's deduplication rules, the Shopify app's data-sharing settings, and the current API specs) before writing.# Cedar & Coil: Meta Conversion Tracking Implementation Guide (Shopify → Meta Pixel + Conversions API) **Status:** Draft. No campaign has launched and no performance data exists, so this guide has no benchmarks and makes no recovery estimates. **Research note:** I checked Meta's documentation and several implementation guides for deduplication, hashing, the Test Events tool and Shopify's data-sharing levels. My search quota ran out before I could re-check a few details. These are marked **[confirm]** and should be checked against Meta's current developer docs before build: - the exact normalization rules for each field - the fbc cookie format - the Graph API version - the Limited Data Use values --- ## 1. Recommended architecture and why both channels are needed ``` Shopper browser Shopify backend / app ────────────── ───────────────────── Meta Pixel (fbq) ── ViewContent ──┐ ── AddToCart ────┤──► Meta dataset (Pixel ID) ── InitiateCheckout ── Purchase (eventID = X) ──┐ ├──► Meta dedupes on Server (Conversions API) │ event_name + event_id ── Purchase (event_id = X) ─┘ ``` **Why the Pixel is still needed** - It runs where the browsing happens, so it sees product views and add-to-carts in real time. - It sets and reads the `_fbp` and `_fbc` cookies. The server needs those values to match a purchase to an ad click. **Why the Conversions API (CAPI) is also needed** - It sends events server to server, so browser ad blockers can't stop them. One source says this directly about purchases (whymatters.co.uk). - It sends the confirmed order, including hashed email and phone, which the browser may never have. **Why neither alone is enough** - Pixel-only data is exposed to blockers and browser privacy limits. - CAPI-only data lacks the browser signals (fbp, fbc, user agent) and the upper-funnel behavior. - Together, the two channels feed one dataset, and deduplication (section 3) stops double counting. I'm not claiming a specific recovery percentage. How much CAPI adds depends on your audience and traffic, and it can only be measured after launch. --- ## 2. Tracking plan: standard events and parameters Meta standard event names are case-sensitive, so use them exactly as written. The product is the Arc Clip Lamp at $68. `ARC-CLIP-LAMP` below is a **placeholder ID**. Pick one ID scheme and use it identically in the Pixel, CAPI and any product catalog. | Event | Trigger | Key parameters | |---|---|---| | **ViewContent** | Product page load | `content_type: "product"`, `content_ids: ["ARC-CLIP-LAMP"]`, `content_name: "Arc Clip Lamp"`, `value: 68.00`, `currency: "USD"` | | **AddToCart** | Add-to-cart success (not just a button click) | Same as ViewContent, plus `contents: [{id, quantity}]` | | **InitiateCheckout** | Checkout start | `content_ids`, `contents`, `num_items`, `value` (cart value), `currency` | | **Purchase** | Order confirmed/paid | **`value`**, **`currency`**, **`content_ids`**, `content_type: "product"`, `contents: [{id, quantity, item_price}]`, `num_items`, `order_id` | **Purchase requirements** - `value` is a number, not a string and not formatted with a currency symbol. `currency` is an ISO 4217 code (`USD`). Send both on every Purchase. Without them, value-based reporting and optimization can't work. - **Decide one definition of `value` and use it in both channels.** For example, subtotal after discounts and excluding tax and shipping. Write the definition in the tracking plan. A mismatch between Pixel and server values is a common, silent reporting error. - `content_ids` must use the same ID scheme as the ViewContent and AddToCart events and as the catalog. **Server-event envelope (required fields, per Meta's Server Event Parameters doc)** - `event_name`, `event_time`, `user_data`, `action_source` (`"website"`). - `event_source_url`, which is required for website events sent via CAPI. - `event_id`, which is marked optional but recommended for deduplication. **Sequencing:** Get Purchase right first. Add server-side ViewContent, AddToCart and InitiateCheckout only if you have a decision that needs them. --- ## 3. How deduplication works Meta's rules, as stated in its documentation and echoed by several implementation guides: 1. **Matching keys.** The Pixel's `eventID` (third argument of `fbq`) must equal the server's `event_id`. The Pixel event name must also equal the server `event_name`. Matching is exact, so treat it as case-sensitive. 2. **Window.** Events are deduplicated only when they arrive within 48 hours of the first event received with that `event_id`. 3. **Which copy wins.** If the same `event_id` and `event_name` arrive more than once, Meta keeps the first copy. 4. **Same dataset.** Both channels must send to the same Pixel/dataset ID. 5. **Fallback method.** Meta also supports matching on `event_name` plus `fbp` and/or `external_id`. It only works when the browser event arrives first and the server event second, so don't rely on it as your primary method. **Rules for your implementation** - **Use a deterministic ID derived from the order.** Use `purchase_<numeric order id>` on both sides. A random ID generated separately in each place will never match. - **Normalize the ID format.** Shopify's browser events and webhooks can expose IDs in different forms, such as a GraphQL `gid://…` versus a numeric ID. Strip to the numeric ID on both sides. - **Never reuse an `event_id` for a different action.** Meta would wrongly discard a legitimate event. - **Run one server sender per event.** The native app *plus* a custom sender sends two server events with different IDs. That double-counts and is not fixed by deduplication. - **Verify the matched pair.** In Test Events, a deduplicated purchase should appear once as a matched browser and server pair, not as two separate purchases. --- ## 4. Preparing customer information for server-side sending **Rule:** Normalize, then hash with SHA-256, for personal identifiers. Send four technical fields **unhashed**: `fbc`, `fbp`, `client_ip_address` and `client_user_agent`. (This matches the guidance in the Enalitica and Chatterbuzz summaries of Meta's parameters page.) Hashing the technical fields is a frequently cited cause of unmatched events and a stuck match score. | `user_data` key | Source in Shopify order | Prep before hashing **[confirm against Meta docs]** | Hash? | |---|---|---|---| | `em` | `email` | trim, lowercase | Yes | | `ph` | `phone` / address phone | digits only, **with country code** (E.164 without the `+`), no symbols or leading zeros | Yes | | `fn`, `ln` | customer/billing name | lowercase, no punctuation | Yes | | `ct` | city | lowercase, no spaces or punctuation | Yes | | `st` | province code | 2-letter lowercase code | Yes | | `zp` | postal code | lowercase, no spaces/dashes; US: first 5 digits | Yes | | `country` | country code | 2-letter lowercase ISO 3166-1 | Yes | | `external_id` | Shopify customer ID | consistent string; hashing recommended | Yes (recommended) | | `fbc` | cookie, copied at cart | the `fb.1.<timestamp>.<fbclid>` value, unmodified | **No** | | `fbp` | cookie, copied at cart | the `fb.1.…` value, unmodified | **No** | | `client_ip_address` | order `browser_ip` or captured | as received | **No** | | `client_user_agent` | captured at cart/checkout | as received | **No** | **Practical notes** - **Hash format:** use lowercase hex SHA-256. Hash after normalizing, never before. - **Never send an empty string or placeholder.** Omit a field you don't have, because hashing `""` produces a valid-looking but meaningless value. - **Capture `_fbp`, `_fbc` and the user agent in the browser and store them as cart attributes.** Shopify carries cart attributes onto the order (`note_attributes`), so your webhook can read them. Without this, server events lose their strongest matching signals. Email and `fbc` are listed as high-priority match signals in the sources I reviewed. - **Keep identifiers consistent.** Use the same `external_id` scheme on both channels. - **No PII in `custom_data`.** Personal data goes in `user_data` only, hashed. --- ## 5. Shopify setup path ### Option comparison | | **A. Native Facebook & Instagram (Meta) sales channel app** | **B. Custom implementation** (custom pixel + order webhook → CAPI, or server-side GTM / third-party connector) | |---|---|---| | Build effort | Connect an account and choose a setting; no theme code | Build, host, secure and monitor a service | | Server events | Available at the **Enhanced** and **Maximum** data-sharing levels; **Standard** is Pixel only (per Shopify's levels as summarized by whymatters.co.uk and Attribuly) | Whatever you build | | Deduplication | Handled by the app | You own it (section 3) | | Hashing / normalization | Handled by the app | You own it (section 4) | | Control over `value`, `content_ids`, custom params, extra events | Limited | Full | | Failure modes | Fewer, but opaque | Many: webhook retries, missing cookies, API version changes, token expiry | | Ongoing maintenance | Shopify/Meta maintain it | Your team | ### Recommendation: Option A, with data sharing at Enhanced or Maximum This argument is based on the goals in the brief rather than convenience. The brief is a first launch of a single $68 product for renters, students and makers, with no performance data yet. - **Goal served: a reliable signal at launch.** The native app gives a tested Pixel + CAPI + dedup path without bespoke code. For a single-SKU store, the main risk is a misconfigured custom build silently double-counting or dropping Purchases, which would mislead the first budget decisions. - **Goal served: staying lean.** A small DTC team shouldn't take on webhook hosting and token rotation for one product. - **What you trade away:** control over the `value` definition, ID formats and extra server-only events. Since only one product exists, you lose little. - **Choosing the level:** Maximum shares richer customer information than Enhanced. Both add CAPI. Choose based on your privacy policy and consent setup (section 7), not on enthusiasm. Update the privacy policy and consent banner **before** enabling either level. - **Revisit Option B if** you need custom events, a value definition the app can't express, multiple datasets, or server-side GTM. Moving to B means turning off the app's server events first to avoid duplicates. **Setup steps (Option A)** 1. In Shopify admin, go to **Sales channels → Facebook & Instagram → Settings → Data sharing settings**. 2. Connect the correct Business Manager account, Pixel/dataset, and ad account. 3. Turn on customer data sharing and choose **Enhanced** or **Maximum**. 4. Remove any hard-coded Pixel from the theme and any other Meta app. Leaving them in is the most common source of duplicates. 5. Verify with Test Events (section 6). Check which **ID format** the app sends in `content_ids` and confirm it matches your catalog if you plan catalog ads **[confirm in Test Events]**. ### Code sketch: server-side Purchase (Option B, for reference or future migration) This is a sketch, not production code. It assumes a Node 18+ endpoint receiving Shopify's `orders/paid` webhook. All identifiers (SKU, domain, env vars) are placeholders. ```js import crypto from "node:crypto"; import express from "express"; const { META_PIXEL_ID, META_CAPI_TOKEN, SHOPIFY_WEBHOOK_SECRET, META_GRAPH_VERSION, // set to a currently supported version META_TEST_EVENT_CODE // set ONLY while testing; unset in production } = process.env; const sha256 = (s) => crypto.createHash("sha256").update(s).digest("hex"); const clean = (s) => (s ?? "").toString().trim().toLowerCase(); const hashEm = (v) => clean(v) && sha256(clean(v)); const hashPh = (v) => { let d = (v ?? "").replace(/\D/g, "").replace(/^0+/, ""); if (d.length === 10) d = "1" + d; // assumes US if no country code return d && sha256(d); }; const hashText = (v) => { const t = clean(v).replace(/[^\p{L}\p{N}]/gu, ""); // lowercase, no punctuation/spaces return t && sha256(t); }; const attr = (order, name) => order.note_attributes?.find((a) => a.name === name)?.value; const app = express(); app.post("/webhooks/orders-paid", express.raw({ type: "application/json" }), async (req, res) => { // 1) Verify the request is from Shopify const digest = crypto.createHmac("sha256", SHOPIFY_WEBHOOK_SECRET) .update(req.body).digest("base64"); const sent = req.get("X-Shopify-Hmac-Sha256") || ""; if (digest.length !== sent.length || !crypto.timingSafeEqual(Buffer.from(digest), Buffer.from(sent))) { return res.sendStatus(401); } res.sendStatus(200); // ack fast; process after const order = JSON.parse(req.body.toString("utf8")); // 2) Consent gate: only send if consent was recorded in the browser (section 7) if (attr(order, "_consent_marketing") !== "granted") return; const addr = order.billing_address ?? order.shipping_address ?? {}; const userData = { em: [hashEm(order.email)].filter(Boolean), ph: [hashPh(order.phone || addr.phone)].filter(Boolean), fn: [hashText(addr.first_name)].filter(Boolean), ln: [hashText(addr.last_name)].filter(Boolean), ct: [hashText(addr.city)].filter(Boolean), st: [hashText(addr.province_code)].filter(Boolean), zp: [hashText(addr.zip)].filter(Boolean), country: [hashText(addr.country_code)].filter(Boolean), external_id: order.customer?.id ? [sha256(String(order.customer.id))] : undefined, // NEVER hash these four: fbp: attr(order, "_fbp"), fbc: attr(order, "_fbc"), client_ip_address: order.browser_ip, client_user_agent: attr(order, "_ua") }; Object.keys(userData).forEach((k) => { const v = userData[k]; if (v == null || (Array.isArray(v) && !v.length)) delete userData[k]; }); const idOf = (li) => li.sku || String(li.variant_id); // MUST match Pixel + catalog scheme const event = { event_name: "Purchase", event_time: Math.floor(Date.parse(order.processed_at || order.created_at) / 1000), event_id: `purchase_${order.id}`, // MUST equal the Pixel eventID action_source: "website", event_source_url: order.order_status_url, // or the thank-you URL the Pixel fired on user_data: userData, custom_data: { value: Number(order.subtotal_price), // use the definition in your tracking plan currency: order.currency, // e.g. "USD" content_type: "product", content_ids: order.line_items.map(idOf), contents: order.line_items.map((li) => ({ id: idOf(li), quantity: li.quantity, item_price: Number(li.price) })), num_items: order.line_items.reduce((n, li) => n + li.quantity, 0), order_id: String(order.id) } }; const body = { data: [event] }; if (META_TEST_EVENT_CODE) body.test_event_code = META_TEST_EVENT_CODE; const r = await fetch( `https://graph.facebook.com/${META_GRAPH_VERSION}/${META_PIXEL_ID}/events` + `?access_token=${encodeURIComponent(META_CAPI_TOKEN)}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } ); const out = await r.json(); if (!r.ok || out.events_received !== 1) { console.error("CAPI failure", order.id, out); // add retry + alerting in production } }); ``` **Matching browser side (Option B only)** - **Purchase:** In a Shopify custom pixel subscribed to `checkout_completed`, fire `fbq('track', 'Purchase', {value, currency, content_ids, …}, {eventID: 'purchase_' + numericOrderId})`. - **Cart attributes:** In the theme, write `_fbp`, `_fbc`, the user agent and the consent state to cart attributes via `/cart/update.js`. - **Retries:** Shopify may redeliver webhooks, so keep your own record of sent order IDs. Meta's deduplication only protects you within 48 hours. --- ## 6. End-to-end validation before scaling spend Run all of this before any budget increase. **A. Install and event-level checks** 1. Install the **Meta Pixel Helper** extension. Walk through ViewContent → AddToCart → InitiateCheckout → Purchase and confirm each event fires **once** with the right parameters. 2. In **Events Manager → Data Sources → your Pixel → Test Events**, copy the test ID. Send it as `test_event_code` on server events. Meta notes that events sent with a test code are **not dropped**, since they flow into Events Manager and are used for targeting and measurement. Use a low-value order, test only as much as needed, and **remove the test code before go-live**. 3. Confirm Purchase in Test Events shows the **browser and server pair deduplicated**, not two purchases. 4. Open the Purchase payload and check: - `value` is a number, and `currency` is `USD`. - `content_ids` use the correct ID scheme. - `event_id` is identical on both channels. - The test purchase value reconciles to the order (for example, a single lamp should show the product value you've defined as `value`). 5. Check match quality. **Event Match Quality** is scored out of 10 per event, and Meta recommends aiming for 6.0 or higher where possible (as summarized by relevantaudience.com). Low scores usually mean missing identifiers or wrongly hashed fields. **B. Resilience checks** 6. Repeat a test purchase in a browser with a content blocker enabled, and in Safari. Confirm the **server** Purchase still arrives. 7. Confirm **Overview** shows both Browser and Server under connection method for Purchase. 8. Check **Diagnostics** for warnings, such as missing parameters or deduplication problems. **C. Reconciliation, with matched windows** 9. After a few real orders, compare **Shopify orders** with **Events Manager received Purchase events** for the same **fully closed** days and the same time zone. Compute the counts and the summed value from the row-level order export and from the Events Manager export, using a script or spreadsheet rather than eyeballing. Chase any mismatch to the specific order. 10. Don't compare Shopify orders with Ads Manager *attributed* purchases. They answer different questions (all orders versus orders Meta credits to ads), so a gap is expected and is not a tracking error. 11. Don't judge efficiency on partial periods. Any rate such as cost per purchase must divide spend and results over the **same closed window**. **D. Go/no-go gate:** Scale spend only when every item below is true: - Each event fires once. - Purchase is deduplicated. - Value and currency are correct. - Server events arrive with the blocker on. - Reconciliation shows no unexplained order-level gaps. - The consent test in section 7 passes. --- ## 7. Consent and compliance note (not legal advice) - **Consent first.** Under EU/UK rules and several US state laws, marketing tracking generally needs a lawful basis, and the details depend on where your customers are. Have counsel confirm your obligations. - **Gate both channels.** Server-side sending doesn't bypass consent. If a shopper declines marketing tracking, neither the Pixel nor CAPI should send their event. Use Shopify's customer-privacy / consent tooling, and in a custom build record the consent state at the browser (the `_consent_marketing` cart attribute in the sketch) and check it on the server. - **Update disclosures.** Update the privacy policy and cookie/consent banner **before** enabling Enhanced or Maximum data sharing, since they share customer information such as email and phone. - **Minimize.** Send only what the plan needs. Keep PII out of `custom_data`, and send personal identifiers only hashed in `user_data`. - **US state privacy laws.** Meta's server event spec includes a Limited Data Use mechanism (`data_processing_options`). Ask counsel whether you need it, and confirm the exact values in Meta's docs **[confirm]**. - **Test the decline path.** Decline consent and confirm that no Meta events fire in Pixel Helper or Test Events. - **Data hygiene.** Store the CAPI access token in a secrets manager, rotate it, and keep webhook logs free of raw PII. - **Brand constraint.** All campaign work is draft-only. Tracking and creative must not imply performance guarantees, reviews or other claims the brand facts don't support. --- ### Sources consulted - Meta for Developers: Server Event Parameters and Using the API (Test Events). - relevantaudience.com: Meta Pixel and CAPI guide, and Events Manager guide. - metricmaven.io and traculo.com: deduplication explainers. - enalitica.com and chatterbuzzmedia.com: parameter hashing and match quality. - whymatters.co.uk and attribuly.com: Shopify data-sharing levels.
Score · attempt 2 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 deduplicated into one dataset, and explains that blockers and privacy limits hurt Pixel-only data while CAPI-only lacks browser signals.
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 parameters, and Purchase explicitly lists 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 /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.
✓Section 6 uses Events Manager Test Events with test_event_code and says to 'Confirm Purchase in Test Events shows the browser and server pair deduplicated, not two purchases.'
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 diagram and table show browser Pixel for the funnel events, and Purchase is sent from the orders/paid webhook with a matching browser checkout_completed event; the server-side funnel events are explicitly optional.
limits_stated
Limitations are stated honestly: no promised attribution-recovery percentages, and consent/regional rules are noted as constraints on what may be sent.
✓It says 'I'm not claiming a specific recovery percentage', and section 7 says server-side sending doesn't bypass consent and that regional rules constrain 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 says the Pixel eventID must equal server event_id and the event names must match, with a 48-hour window, the same dataset, and first-copy-kept behavior.
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.
✓The ID is deterministic, `purchase_${order.id}`, on both sides, with no random suffix, and the guide says to keep a record of sent order IDs for webhook redeliveries.
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.
✓event_time is Math.floor(Date.parse(order.processed_at || order.created_at)/1000), the order timestamp in Unix seconds, so it is unchanged on retries.
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.
✓The code and table trim and lowercase, then SHA-256 hash em, ph, fn, ln and the address fields, and leave fbp, fbc, IP and user agent unhashed.
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 the native app against a custom build, decisively recommends Option A at Enhanced or Maximum data sharing, and gives numbered setup steps.
✗ Attempt 3
Answer · attempt 3 the model's full response$0.25 · 99.4s · 11.6k tok
I'll check Meta's and Shopify's current documentation on a few details first: deduplication rules, hashing requirements, and Shopify's data-sharing settings.# Cedar & Coil: Meta Conversion Tracking Implementation Guide (Arc Clip Lamp) **Status:** Draft. No campaign has launched and no performance data exists, so nothing here relies on results. I don't promise any attribution recovery percentage. How much a server-side setup recovers depends on your traffic and consent mix, and you can only measure it after launch. **Assumptions to confirm:** one SKU at $68 USD, a store on Shopify's hosted checkout, and no Pixel or CAPI connection yet. If a Pixel already exists, audit it first (see section 6) so you don't stack a second one on top. **Source note:** I checked Meta's developer docs for the request shape, required fields, and test-events behavior. Shopify's data-sharing levels come from secondary write-ups, so confirm the menu labels in your own admin. --- ## 1. Recommended architecture: Pixel + Conversions API (CAPI) + deduplication ``` Shopper browser ──Meta Pixel──────────────────────────┐ (ViewContent, AddToCart, InitiateCheckout, Purchase)│ Meta ├─► dedupes on Shopify (order paid) ──server──► CAPI /events ─────────┘ event_name + event_id ``` **Why both:** - **The Pixel** runs in the browser. It sees the whole funnel, including ViewContent and AddToCart, and it captures browser identifiers (`_fbp`, `_fbc`). Ad blockers, browser tracking protections, and cookie limits can stop it from firing or shorten how long identifiers last. - **CAPI** is sent from a server. A browser blocker can't stop it, and it can include data the browser may not have, such as the order's final value and the customer's email. It can't see the browser on its own, so it depends on identifiers the browser passes along. - **Together:** each event is sent twice and Meta counts it once. If the Pixel is blocked, the server copy still counts. If the server copy fails, the Pixel copy still counts. **Why this matches the launch goal:** Cedar & Coil is a single-SKU, $68, first-campaign launch aimed at renters, students, and makers. Meta's delivery will learn from very few purchases at the start. Losing purchase events to browser limits would hurt that learning, so redundant Purchase delivery matters more than funnel-stage detail. --- ## 2. Standard events and key parameters Use one convention everywhere: `content_ids` holds the same ID type that your Meta catalog uses (variant ID or SKU), and `value` uses one agreed definition. | Event | Fires when | Key parameters | |---|---|---| | **ViewContent** | Product page loads | `content_ids`, `content_type: "product"`, `content_name: "Arc Clip Lamp"`, `value: 68.00`, `currency: "USD"` | | **AddToCart** | Add-to-cart succeeds | Same as above, plus `contents: [{id, quantity}]` | | **InitiateCheckout** | Checkout begins | `content_ids`, `contents`, `num_items`, `value`, `currency` | | **Purchase** | Order completed | **`value`, `currency`, `content_ids`**, `content_type`, `contents: [{id, quantity, item_price}]`, `num_items` | **Purchase rules:** - `value` must be a number, not a string like "$68". `currency` must be an ISO 4217 code ("USD"). - Decide once whether `value` is the product subtotal after discounts or the grand total with shipping and tax. I suggest the discounted subtotal, because that is the revenue from the product itself. Apply the same definition in the Pixel and the server event, or deduplicated counts will carry mismatched values. - Server events also need `action_source: "website"`, `event_source_url`, `event_time` (Unix seconds, no older than 7 days), and at least one `user_data` field. - Refunds and cancellations aren't subtracted automatically, so compare Meta revenue to Shopify net revenue with that in mind. --- ## 3. How deduplication works Meta treats a browser event and a server event as the same event when two things match: 1. **Event name:** Pixel `Purchase` equals server `event_name: "Purchase"` (case-sensitive). 2. **Event ID:** Pixel `eventID` equals server `event_id`. The matching pair must arrive within **48 hours** of the first copy Meta received. Meta also has a fallback that matches on `event_name` plus `fbp` or `external_id`, but treat it as a safety net, not the plan. **Practical pattern:** build the ID from something both sides already know. - Purchase: `purchase_<shopify_order_id>`. The checkout-completed browser event and the order webhook both carry the order ID. - Pre-purchase events: generate a UUID in the browser at event time. Pass it to the server in the same request or store it as a cart attribute so the server reuses it. ```js // Browser (Shopify Custom Pixel, on checkout_completed) fbq('track', 'Purchase', { value: 68.00, currency: 'USD', content_ids: ['VARIANT_ID'], content_type: 'product' }, { eventID: 'purchase_' + event.data.checkout.order.id }); // 4th argument ``` **Common failure modes:** - Random UUIDs generated separately on each side, so the IDs never match. - Event name casing mismatch, such as `purchase` and `Purchase`. - Sending server events only, with no `event_id`, which then double-counts when the Pixel also fires. - Checking IDs in the Pixel but never confirming the webhook produces the same string. --- ## 4. Preparing customer information (server-side) Normalize each field, then hash it with **SHA-256** (lowercase hex). A trailing space or uppercase letter produces a different hash, which means no match. | Field | Normalize before hashing | Hash? | |---|---|---| | `em` email | Trim, lowercase | Yes | | `ph` phone | Digits only, include country code, no symbols or leading zeros (US: `1` + 10 digits) | Yes | | `fn`, `ln` | Trim, lowercase, no punctuation | Yes | | `ct` city | Lowercase, no spaces or punctuation | Yes | | `st` state | 2-letter lowercase code | Yes | | `zp` ZIP | US: first 5 digits | Yes | | `country` | 2-letter lowercase ISO code | Yes | | `external_id` | Your stable customer ID, same format everywhere | Yes (recommended) | | `client_ip_address`, `client_user_agent` | Raw | **No** | | `fbp`, `fbc` | Raw, as read from cookies | **No** | The `fbc` value is `fb.1.<timestamp_ms>.<fbclid>`. Don't alter it or rebuild it from a lowercased `fbclid`. Send everything you legitimately have. More matched identifiers generally improve Event Match Quality, though I'm not committing to a score. --- ## 5. Shopify setup path ### Option A: Native Meta sales channel (Facebook & Instagram app) - Installs the Pixel without theme code and, at the **Enhanced** or **Maximum** data-sharing level, adds CAPI. **Standard** is Pixel only. - Typical path: Sales channels → Facebook & Instagram → Settings → Data sharing settings. Confirm the exact labels in your admin. - Handles deduplication, hashing, catalog sync, and consent signals for you. - Limits: you can't change `value` logic, the ID format, or what data is sent. Debugging is mostly black-box. ### Option B: Custom (Shopify Custom Pixel + webhook server + CAPI) - Browser side via Shopify Customer Events (Custom Pixel). Server side via an `orders/paid` webhook sent to your own endpoint. - You control IDs, value definition, and enrichment, but you also own the maintenance. - You must capture `fbp`, `fbc`, and the user agent in the browser and carry them to the server, for example as cart attributes that appear on the order. - Running it alongside the native app creates duplicate Pixels. Disable one. ### Recommendation: Option A for a small DTC store - **Launch goal:** get reliable Purchase signal into Meta quickly, for a single product with no history. The native app delivers browser plus server events with dedup handled for you, and you can launch without engineering time. - **What you trade away:** control over value definition, event IDs, and custom enrichment. - **When to switch to B:** you need a different value rule, multi-system order sources (marketplace, subscription), or the native app's Event Match Quality or counts can't be fixed in Test Events. If you go with A, there's no code to write, but the Option B sketch below is what the native app is doing for you. ### Code sketch: server-side Purchase (Option B) ```js // Node 18+, Express. Secrets via environment variables, never in the repo. import express from "express"; import crypto from "node:crypto"; const app = express(); const sha256 = (v) => crypto.createHash("sha256").update(v).digest("hex"); const h = (v) => (v ? sha256(v) : undefined); const normEmail = (v) => v?.trim().toLowerCase(); const normPhone = (v) => { // approximate; use a phone library in production if (!v) return; let d = v.replace(/\D/g, "").replace(/^0+/, ""); if (d.length === 10) d = "1" + d; // US default return d || undefined; }; const normText = (v) => v?.trim().toLowerCase().replace(/[^\p{L}\p{N}]/gu, ""); const normZip = (v) => v?.trim().toLowerCase().replace(/\s/g, "").slice(0, 5); function verifyShopify(rawBody, hmacHeader) { const digest = crypto.createHmac("sha256", process.env.SHOPIFY_WEBHOOK_SECRET) .update(rawBody).digest("base64"); const a = Buffer.from(digest), b = Buffer.from(hmacHeader || ""); return a.length === b.length && crypto.timingSafeEqual(a, b); } app.post("/webhooks/orders-paid", express.raw({ type: "application/json" }), async (req, res) => { if (!verifyShopify(req.body, req.get("X-Shopify-Hmac-Sha256"))) return res.sendStatus(401); const order = JSON.parse(req.body.toString("utf8")); // Idempotency: Shopify can deliver the same webhook more than once. if (await alreadySent(order.id)) return res.sendStatus(200); // your datastore const attr = Object.fromEntries((order.note_attributes || []).map(a => [a.name, a.value])); const addr = order.billing_address || order.shipping_address || {}; const ids = order.line_items.map(li => String(li.variant_id)); // must match catalog ID type 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 to the Pixel eventID action_source: "website", event_source_url: attr.cc_source_url || "https://YOUR-STORE-DOMAIN/", user_data: { em: [h(normEmail(order.email))].filter(Boolean), ph: [h(normPhone(order.phone || addr.phone))].filter(Boolean), fn: h(normText(addr.first_name)), ln: h(normText(addr.last_name)), ct: h(normText(addr.city)), st: h(normText(addr.province_code)), zp: h(normZip(addr.zip)), country: h(normText(addr.country_code)), external_id: h(order.customer?.id && String(order.customer.id)), client_ip_address: order.browser_ip || undefined, // raw, if present client_user_agent: attr.cc_ua, // raw, captured in browser fbp: attr.cc_fbp, // raw fbc: attr.cc_fbc, // raw }, custom_data: { value: Number(order.subtotal_price), // same definition as the Pixel currency: order.currency, // "USD" content_type: "product", content_ids: ids, contents: order.line_items.map(li => ({ id: String(li.variant_id), quantity: li.quantity, item_price: Number(li.price), })), num_items: order.line_items.reduce((n, li) => n + li.quantity, 0), order_id: String(order.id), }, }; const body = { data: [event] }; if (process.env.META_TEST_EVENT_CODE) body.test_event_code = process.env.META_TEST_EVENT_CODE; const r = await fetch( `https://graph.facebook.com/${process.env.META_API_VERSION}/${process.env.META_PIXEL_ID}/events`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...body, access_token: process.env.META_CAPI_TOKEN }), } ); if (!r.ok) { await queueRetry(order.id, await r.text()); return res.sendStatus(500); } await markSent(order.id); res.sendStatus(200); }); ``` Notes on the sketch: - `META_API_VERSION` is a placeholder. Use a currently supported Graph API version from Meta's docs. - Confirm in your own webhook payload that `browser_ip` and `note_attributes` are populated. Both depend on your setup. - Confirm that the Pixel's `event.data.checkout.order.id` produces the same string as `order.id` in the webhook, or `event_id` won't match. - Only send events for customers whose consent allows it (section 7). --- ## 6. Validate end to end before scaling spend 1. **Audit for duplicates.** Check Events Manager and, in Shopify, the Customer Events and installed apps. Remove any extra Pixel, such as a manual theme snippet beside the native app. 2. **Test Events tool.** In Events Manager → Data Sources → your Pixel → Test Events, generate a test code. For Option B, send it as `test_event_code` on the request. Per Meta's docs, test-code events are not dropped and still feed targeting and measurement, so keep test volume small and remove the code from production. 3. **Walk the funnel yourself.** Run ViewContent → AddToCart → InitiateCheckout → Purchase with a test order, in at least one browser with protections on and one with an ad blocker. 4. **Check each event shows both sources.** In Test Events or Event Details, each event should show Browser and Server, with a "Deduplicated" status. Purchase with server-only is expected if the blocker stopped the Pixel. 5. **Check parameters.** On Purchase confirm `value` = 68.00 for one lamp, `currency` = USD, `content_ids` match your catalog IDs, and `event_id` is identical on both copies. 6. **Check Event Match Quality** for Purchase and look at which identifiers are missing. Fix gaps rather than chasing a number. 7. **Reconcile against Shopify over matching closed windows.** After launch, pick complete days or weeks with the same timezone and the same date range on both sides. Don't divide full-period ad spend by a partial period's purchases. Compute with a script: ```python import pandas as pd shop = pd.read_csv("shopify_orders.csv", parse_dates=["created_at"]) # net of cancellations meta = pd.read_csv("meta_purchases.csv", parse_dates=["day"]) start, end = "2025-01-06", "2025-01-12" # one closed window, store timezone s = shop[(shop.created_at >= start) & (shop.created_at < pd.Timestamp(end) + pd.Timedelta(days=1))] m = meta[(meta.day >= start) & (meta.day <= end)] print(len(s), m.purchases.sum(), s.subtotal.sum(), m.value.sum()) ``` Expect a gap, since Meta counts attributed purchases and Shopify counts all orders. Investigate if it's erratic, if Meta *exceeds* Shopify (a sign of double-counting), or if values don't match the order definitions. Don't set a target percentage before you have data. 8. **Launch small.** Keep early budget modest until two or more consecutive closed windows reconcile cleanly. --- ## 7. Consent and compliance note This is operational guidance, not legal advice. Have counsel review it for your markets. - **Consent first.** Honor the visitor's consent choice for both the Pixel and server events. Shopify's Customer Privacy settings and cookie-banner tooling should gate the browser Pixel. For Option B, make sure the server doesn't send events for people who declined. Email-marketing opt-in is a different permission from tracking consent, so don't use one as a proxy for the other. - **Update your privacy policy and banner before enabling Enhanced or Maximum** data sharing, since these share customer information such as email and phone. - **Hashing is not anonymization.** Hashed email and phone are still personal data in many regulations. Hash them to meet Meta's format and your own security posture, not to avoid consent. - **US state privacy laws.** Meta offers Limited Data Use via `data_processing_options` for some states. Ask counsel whether to apply it. - **Data minimization.** Send only the fields in section 4. Don't put health, financial, or other sensitive data in custom parameters. - **Security.** Keep the CAPI access token and webhook secret in a secret manager. Verify webhook signatures. Log failures without logging raw PII. --- ## Launch checklist - [ ] One Pixel only; native app or custom, not both - [ ] Data sharing level set (Option A) or webhook live (Option B) - [ ] Event IDs confirmed identical in Test Events - [ ] Purchase has `value`, `currency`, `content_ids` - [ ] `test_event_code` removed from production - [ ] Consent gating tested in a restrictive-region scenario - [ ] First reconciliation window defined, with the same dates on both sides
Score · attempt 3 the judge's verdict, criterion by criterion10/11 criteria passed · failed: sources_defined
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 dedup on event_name + event_id and explains that blockers and cookie limits hit the Pixel while CAPI can't see the browser on its own.
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, and Purchase lists value, currency and content_ids in bold.
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 Express webhook sketch builds an event with event_name, event_time, event_id, action_source and a full 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.
✓Section 6 uses Events Manager Test Events with test_event_code and checks that each event shows Browser and Server sources with a 'Deduplicated' status and an identical 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).
✗Purchase is tied to the orders/paid webhook and the checkout_completed pixel, but the table's 'Fires when' column gives triggers rather than browser vs server, and no server path or source of truth is defined for ViewContent, AddToCart or InitiateCheckout beyond a vague 'pass UUID to server'.
limits_stated
Limitations are stated honestly: no promised attribution-recovery percentages, and consent/regional rules are noted as constraints on what may be sent.
✓It states 'I don't promise any attribution recovery percentage', says not to set a target percentage, and section 7 treats consent and regional rules as constraints on 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 says Pixel eventID must equal server event_id and Pixel Purchase must equal server event_name (case-sensitive), with the 48-hour window and a worked purchase_<order_id> example in both browser and server code.
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.
✓event_id is deterministic as `purchase_${order.id}` and matches the Pixel's eventID, and the alreadySent idempotency check plus queueRetry reuse it, so webhook retries don't change the 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.
✓event_time is Math.floor of order.processed_at || created_at in Unix seconds, so it comes from the order timestamp rather than send time and stays the same on retries.
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 trim and lowercase email and other fields, normalize phone, SHA-256 hash them, and leave IP, user agent, fbp and fbc raw.
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 the native app and the custom build, decisively recommends Option A for a small DTC store with the Sales channels → Data sharing path, and states when to switch to B.