← Run 20260825-230519-539e42f9
Shopify to Meta ads conversion tracking implementation
task shopify-meta-capiAug 25, 2026skill analytics

Answers & verdicts

GPT-5.6 Luna 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." metadata: version: 2.0.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 --- ## 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.012 · 64.8s · 6.2k tok
# Cedar & Coil: Shopify → Meta Conversion Tracking Implementation Guide **Goal:** Track the Arc Clip Lamp funnel reliably while reducing dependence on browser cookies and JavaScript execution. Use the Meta Pixel for browser-side behavioral events and Meta Conversions API (CAPI) for server-side events, with strict deduplication. The Arc Clip Lamp’s product value is **$68 USD**. Send the actual Shopify transaction value for purchases rather than hard-coding $68, because discounts, taxes, shipping, returns, and multiple quantities can change the final order value. --- ## 1. Recommended architecture ### Recommended design ```text Shopify storefront │ ├── Browser: Meta Pixel │ ├── ViewContent │ ├── AddToCart │ ├── InitiateCheckout │ └── Purchase │ └── Server: Meta Conversions API ├── Purchase from Shopify order confirmation/webhook └── Optional server copies of other events ``` Use the **same Meta Pixel ID** for both channels. ### Why use both **Browser Pixel** - Captures in-session product behavior close to the point where it occurs. - Can receive browser context such as the page URL, Meta browser ID (`fbp`), and click ID (`fbc`). - Supports events such as `ViewContent`, `AddToCart`, `InitiateCheckout`, and `Purchase`. - Is vulnerable to ad blockers, browser restrictions, consent choices, failed JavaScript, and checkout-page limitations. **Conversions API** - Sends events from Shopify or your server directly to Meta. - Is less dependent on browser JavaScript and browser-based blocking. - Can use first-party order data and customer information collected during checkout. - Is especially useful for ensuring that completed Shopify orders reach Meta even when the thank-you-page Pixel does not execute. Shopify’s native Meta integration describes its Enhanced and Maximum settings as using both the Pixel and CAPI; Shopify also notes that browser-based ad blockers can prevent Pixel data from being shared, while server-to-server purchase transmission is not blocked in the same way. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) ### Important implementation rule Do not install: - Shopify’s native Meta integration, - a separate Meta Pixel app, - manually pasted Pixel code, - and a separate CAPI service without first checking for overlap. Multiple implementations can create duplicate events. Shopify specifically advises removing manually added theme Pixel code when using its Meta channel. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-pixel?utm_source=openai)) --- ## 2. Standard events and required parameters Use Meta’s standard event names exactly as shown. Do not create custom names such as `lamp_product_viewed` when a standard event exists. ### Event plan | Event | Trigger | Browser | Server | Important parameters | |---|---|---:|---:|---| | `ViewContent` | Arc Clip Lamp product page viewed | Yes | Optional | `content_ids`, `content_type`, `content_name`, `value`, `currency` | | `AddToCart` | Product successfully added to cart | Yes | Optional | `content_ids`, `content_type`, `content_name`, `value`, `currency`, `num_items` | | `InitiateCheckout` | Customer begins checkout | Yes | Optional | `value`, `currency`, `content_ids`, `content_type`, `num_items` | | `Purchase` | Shopify order is successfully paid/created | Yes | Yes | `value`, `currency`, `content_ids`, `content_type`, `num_items`, `order_id` | Shopify’s native integration supports events including `ViewContent`, `AddToCart`, `InitiateCheckout`, and `Purchase`; its purchase event is associated with completion and viewing of the checkout thank-you page. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) ### Product identifiers Use a stable identifier consistently: ```text content_ids: ["shopify_variant_id"] ``` For the Arc Clip Lamp, prefer the **Shopify variant ID** if the store has variants. If the product has only one variant, use the product or variant ID consistently in: - Shopify product feed, - Pixel events, - CAPI events, - Meta catalog. Do not use the product title as the primary ID. ### `ViewContent` Example browser payload: ```javascript fbq('track', 'ViewContent', { content_ids: ['shopify_variant_123456789'], content_type: 'product', content_name: 'Arc Clip Lamp', value: 68.00, currency: 'USD' }, { eventID: 'vc_product_123456789_session_abc' }); ``` Recommended trigger: - Fire once when the Arc Clip Lamp product page is successfully rendered. - Do not fire merely when a product card appears in a collection grid unless that is intentionally treated as a product view. ### `AddToCart` ```javascript fbq('track', 'AddToCart', { content_ids: ['shopify_variant_123456789'], content_type: 'product', content_name: 'Arc Clip Lamp', value: 68.00, currency: 'USD', num_items: 1 }, { eventID: 'atc_cart_token_abc_line_1' }); ``` Use the quantity and line-item subtotal represented by the add-to-cart action. If the customer adds two lamps, send: ```json { "value": 136.00, "currency": "USD", "num_items": 2 } ``` ### `InitiateCheckout` ```javascript fbq('track', 'InitiateCheckout', { content_ids: ['shopify_variant_123456789'], content_type: 'product', value: 68.00, currency: 'USD', num_items: 1 }, { eventID: 'ic_checkout_token_abc' }); ``` Use the cart or checkout total available at initiation. If shipping, tax, discounts, or other amounts are not final yet, use the best available cart value and document the convention. ### `Purchase` For Purchase, include at minimum: ```json { "value": 68.00, "currency": "USD", "content_ids": ["shopify_variant_123456789"], "content_type": "product", "num_items": 1, "order_id": "1001" } ``` For a multi-item order: ```json { "value": 136.00, "currency": "USD", "content_ids": [ "shopify_variant_123456789", "shopify_variant_123456789" ], "content_type": "product", "num_items": 2, "order_id": "1002" } ``` `content_ids` should correspond to IDs in the Meta catalog. `value` should be numeric, and `currency` should be a three-letter ISO code such as `USD`. For reporting consistency, decide whether `value` means: - Shopify total including taxes and shipping, - subtotal after discounts, - or another defined amount. Then use the same convention in Pixel and CAPI. Shopify notes that its order-value events use the order total, including duties, taxes, and discounts. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) --- ## 3. Exactly how deduplication works ### The core rule For the same customer action, the browser and server events must use: 1. The same Pixel ID, 2. The same standard `event_name`, and 3. The same unique `event_id`. Example: ```text Browser: event_name = Purchase event_id = shopify_order_1001 Server: event_name = Purchase event_id = shopify_order_1001 ``` Meta can then recognize them as two transmissions of one conversion rather than two purchases. Meta’s direct-integration guidance identifies matching `event_name` and `event_id` as the recommended deduplication method, with duplicate events received within the applicable deduplication window treated as duplicates. ([storage.googleapis.com](https://storage.googleapis.com/lr-tech-docs-resources/PDFs/Conversions-API-Direct-Integration-Playbook_English.pdf?utm_source=openai)) ### Browser syntax The browser event ID is passed in the third argument: ```javascript fbq( 'track', 'Purchase', { value: 68.00, currency: 'USD', content_ids: ['shopify_variant_123456789'], content_type: 'product' }, { eventID: 'shopify_order_1001' } ); ``` ### CAPI syntax The server event uses the same value in the event object: ```json { "event_name": "Purchase", "event_id": "shopify_order_1001" } ``` ### Recommended ID strategy For purchases: ```text event_id = shopify_order_<Shopify order ID> ``` For funnel events: ```text ViewContent = vc_<product-or-variant-id>_<unique-view-id> AddToCart = atc_<cart-token>_<line-item-or-action-id> InitiateCheckout = ic_<checkout-token> Purchase = shopify_order_<Shopify order ID> ``` The ID must be: - Unique for the individual action, - Stable across retries, - Available to both browser and server implementations, - Reused only for the same action. ### Do not make this mistake Do not generate a random ID independently in the browser and server: ```text Browser: browser_abc123 Server: server_xyz789 ``` Those represent different events to Meta and may be counted separately. ### Purchase-specific implementation For Purchase, create the ID from the Shopify order identifier. Store it in your event log before sending CAPI so retries use the same ID: ```text order_id: 1001 event_id: shopify_order_1001 status: sent ``` If the request times out, retry the same event with `shopify_order_1001`; do not generate a new ID. ### Event name matters too Matching only the ID is not sufficient. Keep the event name identical: ```text Browser: Purchase Server: Purchase ``` Not: ```text Browser: Purchase Server: OrderCompleted ``` The server-side event must also use the same Pixel ID and represent the same action. --- ## 4. Preparing customer information for server-side events CAPI’s `user_data` helps Meta match a server event to the relevant ad interaction. Send only data that is permitted by the store’s consent and privacy policies. ### Normalize before hashing For email: 1. Trim whitespace. 2. Convert to lowercase. 3. Hash with SHA-256. 4. Send the hexadecimal hash. ```text " Customer@example.com " → "customer@example.com" → SHA-256 → "hashed_value" ``` For phone: 1. Remove spaces, punctuation, and formatting characters. 2. Convert to international format with country code. 3. Hash with SHA-256. ```text (212) 555-0199 → +12125550199 → SHA-256 ``` For names and location fields: - Normalize case and whitespace. - Use the appropriate country/state representation. - Hash fields that Meta specifies as hashed customer identifiers. Meta’s Business SDK documentation states that customer-information parameters such as email and phone are normalized and SHA-256 hashed before transmission when using its parameter-building tools. ([github.com](https://github.com/facebook/facebook-php-business-sdk/blob/main/README.md?utm_source=openai)) ### Typical `user_data` fields Use the strongest legally permitted identifiers available: ```json { "em": ["sha256_email"], "ph": ["sha256_phone"], "fn": ["sha256_first_name"], "ln": ["sha256_last_name"], "ct": ["sha256_city"], "st": ["sha256_state"], "zp": ["sha256_postal_code"], "country": ["sha256_country"], "external_id": ["sha256_customer_id"], "fbp": "fb.1. ...", "fbc": "fb.1. ...", "client_ip_address": "203.0.113.10", "client_user_agent": "Mozilla/5.0 ..." } ``` ### Fields that should not be hashed Do not SHA-256 hash: - `fbp`, - `fbc`, - `client_ip_address`, - `client_user_agent`. These are structured technical values, not ordinary customer identifiers. ### Browser identifiers Capture and preserve: - `fbp`: Meta browser identifier, usually from the `_fbp` cookie. - `fbc`: Meta click identifier, usually derived from the `fbclid` landing-page parameter. If available, associate these values with the Shopify session, cart, checkout, or order record so they can be used on the server-side Purchase event. ### Server-side purchase matching hierarchy For an order, use: 1. Consent-approved email and phone, 2. `fbp` and `fbc`, 3. External customer ID, 4. Client IP and user agent where lawfully collected and available. Do not put raw email, phone, name, or address in: - event names, - custom event parameters, - URLs, - browser console logs, - analytics debugging screenshots, - order IDs. The Meta SDK’s server-event model includes fields such as `event_name`, `event_time`, `event_id`, `user_data`, `custom_data`, `event_source_url`, and `action_source`. ([github.com](https://github.com/facebook/facebook-php-business-sdk/blob/main/README.md?utm_source=openai)) --- ## 5. Concrete Shopify setup path ## Option A: Native Facebook and Instagram by Meta channel ### Setup path In Shopify Admin: 1. Go to **Sales channels**. 2. Install or open **Facebook & Instagram by Meta**. 3. Connect: - Meta Business Portfolio, - Facebook Page, - Meta ad account, - Meta Pixel, - product catalog. 4. Go to: **Sales channels → Facebook & Instagram → Settings → Data sharing settings** 5. Enable customer data sharing. 6. Choose **Enhanced** or **Maximum** rather than Standard if the business has approved the corresponding data-sharing basis. 7. Connect the correct Pixel. 8. Remove any manually installed Meta Pixel from: - `theme.liquid`, - Shopify preferences, - duplicate tracking apps. 9. Confirm that the Arc Clip Lamp is published to the Meta catalog. 10. Verify catalog IDs match the IDs sent by events. Shopify documents the native path through **Sales channels → Facebook & Instagram → Settings → Share data settings**, with Standard, Enhanced, and Maximum data-sharing levels. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) ### Advantages - Fastest setup for a small DTC store. - Shopify owns much of the browser and server event plumbing. - Lower maintenance burden. - Product catalog and Pixel are connected in one channel. - Less custom checkout code. ### Limitations - Less control over exact payload construction. - Less control over event timing and custom order-state logic. - Debugging can be more dependent on Shopify and Meta diagnostics. - A native integration may not expose every internal event ID or data field in the way a custom analytics team expects. - Direct checkout or other Meta-native checkout surfaces can have different tracking behavior; Shopify notes that third-party analytics pixels do not fire when a checkout is completed outside the online store. ([help.shopify.com](https://help.shopify.com/en/manual/online-sales-channels/agentic-storefronts/meta?utm_source=openai)) ### Recommendation for Cedar & Coil For a small store selling one primary product, use the **native Facebook and Instagram by Meta channel with Enhanced data sharing** as the starting implementation. Use Maximum only after confirming that: - the privacy notice and consent mechanism support it, - the business is comfortable sharing the additional customer information, - the data-sharing setting is appropriate for all target markets. Do not build a custom CAPI stack initially unless Cedar & Coil needs: - custom server-side business logic, - post-purchase or offline events, - refunds and cancellations synchronized to a data warehouse, - a multi-channel event pipeline, - precise control over deduplication IDs, - or the ability to audit every payload independently. --- ## Option B: Custom implementation A custom implementation typically requires: 1. A Shopify Web Pixel or app-pixel implementation for browser events. 2. A backend service that receives Shopify order events. 3. A Shopify webhook such as an order-paid or order-created workflow, depending on the defined conversion moment. 4. A durable event table containing: - Shopify order ID, - Meta event ID, - event name, - event time, - consent status, - delivery status, - retry count. 5. Server-side normalization and hashing. 6. A CAPI request to Meta. 7. Monitoring for rejected, delayed, or duplicated events. For custom code, do not place the Meta access token in theme JavaScript or expose it to the browser. The token belongs only on the server. ### Server-side Purchase request code sketch This is a generic Node.js-style request. Replace the placeholders with values from the Shopify order and your server-side consent logic. ```javascript import crypto from "node:crypto"; function sha256(value) { return crypto .createHash("sha256") .update(value) .digest("hex"); } function normalizeEmail(email) { return email?.trim().toLowerCase(); } function normalizePhone(phone) { // Production code should use a proper phone-number library. return phone?.replace(/[^\d+]/g, ""); } async function sendPurchaseToMeta(order, requestContext) { const pixelId = process.env.META_PIXEL_ID; const accessToken = process.env.META_CAPI_ACCESS_TOKEN; const apiVersion = "vXX.X"; // Pin and periodically review the API version. const eventId = `shopify_order_${order.id}`; const email = normalizeEmail(order.email); const phone = normalizePhone(order.phone); const contents = order.line_items.map((line) => ({ id: String(line.variant_id || line.product_id), quantity: Number(line.quantity), item_price: Number(line.price) })); const payload = { data: [ { event_name: "Purchase", event_time: Math.floor( new Date(order.paid_at || order.created_at).getTime() / 1000 ), event_id: eventId, action_source: "website", event_source_url: order.landing_site || undefined, user_data: { em: email ? [sha256(email)] : undefined, ph: phone ? [sha256(phone)] : undefined, // Do not hash these technical identifiers: fbp: requestContext.fbp || undefined, fbc: requestContext.fbc || undefined, client_ip_address: requestContext.clientIp || undefined, client_user_agent: requestContext.userAgent || undefined }, custom_data: { value: Number(order.total_price), currency: order.currency || "USD", content_type: "product", content_ids: contents.map((item) => item.id), contents, num_items: contents.reduce( (total, item) => total + item.quantity, 0 ), order_id: String(order.id) } } ] // Include only during controlled testing: // test_event_code: process.env.META_TEST_EVENT_CODE }; const response = await fetch( `https://graph.facebook.com/${apiVersion}/${pixelId}/events` + `?access_token=${encodeURIComponent(accessToken)}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) } ); const result = await response.json(); if (!response.ok) { throw new Error(`Meta CAPI error: ${JSON.stringify(result)}`); } return result; } ``` The request structure follows Meta’s server-event model: an events array containing `event_name`, `event_time`, `event_id`, `action_source`, `user_data`, and `custom_data`. ([github.com](https://github.com/facebook/facebook-php-business-sdk/blob/main/README.md?utm_source=openai)) ### Custom browser Purchase event The browser must use the same event ID: ```javascript const eventId = `shopify_order_${shopifyOrderId}`; fbq('track', 'Purchase', { value: 68.00, currency: 'USD', content_ids: ['shopify_variant_123456789'], content_type: 'product', num_items: 1, order_id: String(shopifyOrderId) }, { eventID: eventId }); ``` If the browser cannot access the final Shopify order ID at the time of the event, use the native integration or redesign the event handoff so the browser and server receive the same stable transaction identifier. Do not use independently generated random IDs. --- ## 6. End-to-end validation before scaling spend Perform validation in a test environment or with a controlled live order before launching ads. ### A. Confirm the asset configuration Check: - Correct Meta Business Portfolio. - Correct ad account. - Correct Pixel ID. - Correct catalog. - Arc Clip Lamp catalog item is active. - Product or variant IDs match between Shopify and Meta. - No duplicate Pixel in theme code. - No second Meta tracking app installed. Shopify warns that multiple Pixel implementations can produce duplicate or incorrect data. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-pixel?utm_source=openai)) ### B. Test the browser funnel Use a clean browser session and test: 1. Product page load: - one `ViewContent`. 2. Add the Arc Clip Lamp to cart: - one `AddToCart`. 3. Begin checkout: - one `InitiateCheckout`. 4. Complete a test purchase: - one `Purchase`. Use: - Meta Events Manager, - Meta Pixel Helper or browser developer tools, - Shopify order details, - browser network requests. For each event, inspect: - event name, - event ID, - value, - currency, - content IDs, - content type, - page URL, - whether consent allowed the event. ### C. Test the server Purchase In Meta Events Manager: 1. Open the relevant data source. 2. Go to **Test Events**. 3. Add the test event code to the server request. 4. Place one controlled Shopify order. 5. Confirm the server event arrives. 6. Confirm the browser Purchase also arrives. 7. Confirm Meta identifies them as the same event rather than two purchases. 8. Remove the test event code after testing. ### D. Reconcile the order For the same test order, compare Shopify and Meta: | Field | Shopify | Meta | |---|---|---| | Order ID | Same | Same in `order_id` | | Event ID | `shopify_order_1001` | `shopify_order_1001` | | Value | Defined Shopify total | Same numeric value | | Currency | `USD` | `USD` | | Product ID | Variant ID | Same `content_id` | | Quantity | 1 | `num_items = 1` | ### E. Test failure and privacy cases Test at least these cases: - Browser ad blocker enabled. - JavaScript disabled or interrupted. - Safari/private browsing. - Mobile browser. - Consent denied. - Consent granted after initial page load. - Customer checks out as guest. - Payment retry or duplicated thank-you-page reload. - Server timeout followed by retry. - Order cancellation or refund. For a server retry, verify that the same `event_id` is reused. ### F. Monitor after launch For the first several days, monitor: - Meta Events Manager diagnostics. - Event match quality. - Missing or malformed parameters. - Duplicate-event warnings. - Purchase count compared with Shopify paid orders. - Purchase value compared with Shopify revenue. - Browser/server event proportions. - Sudden changes after theme, checkout, or app updates. Do not judge implementation quality by an assumed attribution-recovery percentage. Judge it by event completeness, deduplication, value accuracy, consent behavior, and agreement with Shopify’s order records. --- ## 7. Consent and compliance note Meta tracking should be treated as a governed data-sharing activity, not merely a technical tag installation. Before enabling browser or server events: - Determine which jurisdictions Cedar & Coil serves. - Use the store’s consent-management platform where required. - Block non-essential Pixel and CAPI processing until the required consent is collected. - Pass only consent-approved data to Meta. - Explain Meta Pixel and Conversions API sharing in the privacy policy. - Document the purposes of processing, categories of data, retention, and opt-out/deletion procedures. - Do not send raw email, phone, names, or addresses in event payloads. - Limit server-side fields to what is necessary for measurement and matching. - Honor deletion and opt-out requests in downstream event systems. - Review Meta’s Business Tools terms and applicable privacy requirements with qualified counsel. Shopify explicitly states that customer data sharing is a choice and that the store should explain the sharing practices in its privacy policy. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) ### Practical default for Cedar & Coil For a small U.S.-focused DTC store: 1. Install the native **Facebook and Instagram by Meta** sales channel. 2. Enable the appropriate Enhanced data-sharing setting. 3. Remove duplicate manual Pixel code. 4. Validate the four standard events. 5. Confirm native browser/server deduplication in Events Manager. 6. Move to a custom implementation only if native tracking cannot meet Cedar & Coil’s auditing, consent, or business-event requirements.
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 explicitly recommends Pixel + CAPI on the same Pixel ID and explains browser vulnerability (ad blockers, JS failures) vs server resilience as the reason both are needed.
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓Section 2 provides a table and code examples for ViewContent, AddToCart, InitiateCheckout, and Purchase, with Purchase explicitly including 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.js sendPurchaseToMeta function includes event_name, event_time (Unix seconds), event_id, action_source: 'website', and a full user_data block with hashed em/ph and unhashed fbp/fbc/IP/UA.
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 6C instructs using Meta Events Manager's Test Events tool with a test_event_code and explicitly checks 'Confirm Meta identifies them as the same event rather than 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 event table marks Browser/Server per event and Section 1 states Purchase should come 'from Shopify order confirmation/webhook' so it reaches Meta 'even when the thank-you-page Pixel does not execute.'
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 states 'Do not judge implementation quality by an assumed attribution-recovery percentage' and Section 7 requires blocking non-essential Pixel/CAPI processing until consent is collected per jurisdiction.
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 explains that matching event_name and event_id across Pixel and CAPI lets 'Meta ... recognize them as two transmissions of one conversion rather than two purchases,' with concrete code showing the same eventID/event_id used in both channels.
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 guide specifies event_id = shopify_order_<order ID> and states 'If the request times out, retry the same event with shopify_order_1001; do not generate a new ID,' explicitly warning against random per-send IDs.
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 code sets event_time from `order.paid_at || order.created_at` converted to Unix seconds via Math.floor(...getTime()/1000), i.e., the order occurrence time rather than the current 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 details trimming and lowercasing email, normalizing phone, then SHA-256 hashing before inclusion in user_data, matching the em/ph fields in the code sketch.
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).
✓Section 5 gives a decisive recommendation ('use the native Facebook and Instagram by Meta channel with Enhanced data sharing as the starting implementation') with a numbered concrete setup path in Shopify Admin.

GPT-5.6 Terra 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." metadata: version: 2.0.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 --- ## 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.12 · 74.6s · 7.0k tok
# Cedar & Coil: Shopify → Meta Conversion Tracking Implementation Guide **Goal:** give Meta reliable, privacy-resilient conversion signals for the Arc Clip Lamp while keeping event counts, revenue, and product identifiers consistent. For a small DTC Shopify store, use **one Meta dataset/pixel** and implement Meta’s standard ecommerce funnel: 1. `ViewContent` 2. `AddToCart` 3. `InitiateCheckout` 4. `Purchase` Cedar & Coil’s primary paid-social conversion should be **Purchase**, using the completed order value and currency. The Arc Clip Lamp is currently **$68**, but tracking must always use the live Shopify order/cart values rather than hard-coded campaign values. --- ## 1. Recommended architecture: Meta Pixel + Conversions API ### Recommended design ```text Shopper browser └─ Meta Pixel ├─ ViewContent ├─ AddToCart ├─ InitiateCheckout └─ Purchase │ │ Same event name + same event_id for duplicate events ▼ Shopify / server └─ Meta Conversions API (CAPI) ├─ Purchase at minimum └─ Optionally the earlier funnel events if the implementation can reliably produce the same event_id as the browser event ``` ### Why send both browser and server events? **Browser Meta Pixel** - Captures on-site behavior immediately: product views, cart additions, and checkout starts. - Supplies useful browser context such as the Meta cookies (`_fbp`, `_fbc`), URL, and user agent. - Can be affected by cookie restrictions, tracking prevention, ad blockers, script failures, and users leaving before the browser-side confirmation event fires. **Server-side Conversions API** - Sends the event from Cedar & Coil’s server or Shopify-connected platform to Meta, rather than relying only on a browser script. - Is less vulnerable to browser-side blockers and client-side execution failures. - Can use authoritative commerce data—especially a paid Shopify order—to send the correct order ID, purchased variants, total value, and currency. Shopify describes its Meta data-sharing options as using the pixel for browser collection and CAPI for server-to-server purchase sharing; Shopify also notes that server-to-server events are not blocked by browser-based ad blockers. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) ### Practical recommendation For Cedar & Coil, **use the official Facebook & Instagram by Meta Shopify sales channel with the highest appropriate data-sharing setting**, after consent requirements are configured. This is the recommended default for a small store because it deploys the Meta pixel and Meta’s server-side connection together, while avoiding a bespoke checkout integration. Shopify’s **Enhanced** and **Maximum** settings use both CAPI and the Meta pixel; Shopify identifies server-side purchase transmission as part of those settings. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) **Do not install a second theme pixel, GTM Meta Pixel, or custom Purchase CAPI webhook on top of the native integration unless there is a specific, tested reason.** Parallel installations are a common cause of duplicate events and inconsistent product IDs. --- ## 2. Standard event plan and required parameters Use Meta’s standard event names exactly as shown. Keep product identifiers aligned with the Meta catalog synced from Shopify. ### Identifier rule: use variant IDs consistently The Arc Clip Lamp may eventually have variants—such as finish, bundle, or other purchasable options. Therefore: - Use the **Shopify variant ID** as `content_ids` / `contents[].id`. - Ensure the same IDs are used in: - Shopify catalog sync to Meta, - browser Pixel events, - server-side CAPI events. - Do not use a product page handle in one system and variant ID in another. This alignment matters for catalog sales, dynamic ads, and product-level reporting. ### Event specification | Standard event | Trigger | Minimum recommended parameters | Cedar & Coil implementation notes | |---|---|---|---| | `ViewContent` | Arc Clip Lamp product-detail page loads and product data is available | `content_ids`, `content_type`, `value`, `currency` | Send the viewed variant ID. For a single purchasable variant, send one ID. | | `AddToCart` | Shopper successfully adds an item to cart | `content_ids`, `content_type`, `contents`, `value`, `currency` | Fire after Shopify confirms the cart mutation—not merely when the button is clicked. | | `InitiateCheckout` | Shopper begins Shopify checkout | `content_ids`, `content_type`, `contents`, `num_items`, `value`, `currency` | Use the current cart state. | | `Purchase` | Order is completed / paid | `content_ids`, `content_type`, `contents`, `value`, `currency`, `event_id` | Use the final Shopify order total and the purchased variants. Send from browser and server with the same event ID. | ### Recommended payload fields by event #### `ViewContent` ```javascript fbq("track", "ViewContent", { content_ids: ["SHOPIFY_VARIANT_ID"], content_type: "product", content_name: "Arc Clip Lamp", value: 68.00, currency: "USD" }); ``` Use live Shopify data. `value` should reflect the currently selected purchasable variant, not a static campaign assumption. #### `AddToCart` ```javascript fbq("track", "AddToCart", { content_ids: ["SHOPIFY_VARIANT_ID"], content_type: "product", contents: [{ id: "SHOPIFY_VARIANT_ID", quantity: 1, item_price: 68.00 }], value: 68.00, currency: "USD" }); ``` If quantity is two, set `quantity: 2` and calculate `value` from the cart line subtotal. #### `InitiateCheckout` ```javascript fbq("track", "InitiateCheckout", { content_ids: ["SHOPIFY_VARIANT_ID"], content_type: "product", contents: [{ id: "SHOPIFY_VARIANT_ID", quantity: 1, item_price: 68.00 }], num_items: 1, value: 68.00, currency: "USD" }); ``` For multi-item carts, send all variants in `contents`, all IDs in `content_ids`, the total item count in `num_items`, and the current checkout/cart value. #### `Purchase` ```javascript fbq("track", "Purchase", { content_ids: ["SHOPIFY_VARIANT_ID"], content_type: "product", contents: [{ id: "SHOPIFY_VARIANT_ID", quantity: 1, item_price: 68.00 }], value: 68.00, currency: "USD", order_id: "SHOPIFY_ORDER_ID_OR_NAME" }, { eventID: "order-SHOPIFY_ORDER_ID" }); ``` For `Purchase`: - `value`: use the authoritative Shopify order total selected in the measurement policy—typically the final order total. Shopify’s native integration describes order-value events as using total price, including duties, taxes, and discounts. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) - `currency`: use Shopify’s order currency, such as `USD`. - `content_ids`: include every purchased **variant ID**. - `contents`: include each purchased variant, quantity, and item price. - `order_id`: use a stable order reference for internal auditability. - `eventID`: use a stable ID based on the order, such as `order-<Shopify order ID>`, and reuse it exactly in CAPI. Shopify’s native Meta connection automatically tracks product view, add-to-cart, checkout initiation, and purchase events, among other standard events. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) --- ## 3. Exactly how Pixel/CAPI deduplication works ### The rule When the same real-world action is sent through both the browser Pixel and Conversions API, send: 1. the **same Meta dataset/pixel ID**, 2. the **same standard event name**, and 3. the **same `event_id`**. For the order confirmation: ```text Browser Pixel: event_name = Purchase eventID = order-1234567890 Server CAPI: event_name = Purchase event_id = order-1234567890 ``` Meta can then recognize these as two transport paths for **one purchase**, rather than counting two purchases. ### What not to do **Bad: different identifiers** ```text Pixel: eventID = thankyou-abc CAPI: event_id = order-1234567890 ``` Those can be treated as separate events. **Bad: same event ID, different event names** ```text Pixel: event_name = Purchase CAPI: event_name = OrderPaid ``` Use Meta’s exact standard event name, `Purchase`, on both sides. **Bad: random UUID generated independently in browser and server** ```text Pixel: eventID = random-browser-uuid CAPI: event_id = random-server-uuid ``` Those will not deduplicate because they do not match. ### Recommended event-ID conventions | Event | Event ID pattern | Notes | |---|---|---| | `ViewContent` | `vc-<pageview/session>-<variant-id>` | Only needed if sending this event from both browser and server. | | `AddToCart` | `atc-<cart-token>-<line/sequence>` | Only needed if dual-sending. Avoid reused IDs for repeated cart additions. | | `InitiateCheckout` | `ic-<checkout-token>` | Only needed if dual-sending. | | `Purchase` | `order-<Shopify-order-id>` | Recommended: stable, deterministic, and easy to reconcile. | ### Important Shopify implementation constraint A Shopify `orders/paid` webhook is excellent for sending an authoritative server-side Purchase, because Shopify documents `orders/paid` as occurring when an order is paid. ([shopify.dev](https://shopify.dev/docs/api/webhooks/2025-04?utm_source=openai)) However, a webhook alone does **not** automatically know the browser-generated purchase event ID. To deduplicate a custom implementation, both browser and server must derive the same ID from data both possess—usually a stable Shopify order ID—or the client must persist/pass the ID to the server in a trusted implementation. For Shopify’s native Meta integration, let the integration manage its own browser/server pairing. **Do not attempt to supplement its native Purchase event with your own webhook Purchase event** unless you have disabled the native equivalent and have fully tested deduplication. --- ## 4. Preparing customer information for server-side CAPI CAPI’s `user_data` improves Meta’s ability to associate an event with an eligible Meta user. It is not a license to send all customer information available in Shopify. ### Send only permitted, necessary fields For a server-side Purchase, use the strongest consented identifiers available from the order and request context: | Field | Typical source | Preparation | |---|---|---| | `em` | Shopify checkout email | Normalize, then SHA-256 hash | | `ph` | Checkout phone | Normalize to E.164 digits, then SHA-256 hash | | `fn`, `ln` | Checkout/shipping name | Normalize, then SHA-256 hash | | `ct`, `st`, `zp`, `country` | Billing/shipping address | Normalize, then SHA-256 hash | | `external_id` | Cedar & Coil customer ID | Stable first-party identifier; normalize/hash | | `fbp` | `_fbp` cookie | Send un-hashed | | `fbc` | `_fbc` cookie or click ID-derived value when available | Send un-hashed | | `client_ip_address` | Original shopper request | Do not hash | | `client_user_agent` | Original shopper request | Do not hash | ### Normalization and hashing process For customer fields that require hashing: 1. Convert to lowercase where applicable. 2. Trim leading/trailing whitespace. 3. Normalize formatting: - Email: `Customer@Example.com ` → `customer@example.com` - Phone: convert to a canonical E.164-style digit representation before hashing. - Country: use the expected country code format consistently. - Names/city/state: remove irrelevant formatting differences and normalize case. 4. SHA-256 hash the normalized field. 5. Send the resulting lowercase hexadecimal hash. Example: ```js import crypto from "node:crypto"; function sha256(value) { return crypto .createHash("sha256") .update(value.trim().toLowerCase(), "utf8") .digest("hex"); } const userData = { em: [sha256("customer@example.com")], ph: [sha256("15551234567")], fn: [sha256("jordan")], ln: [sha256("lee")], country: [sha256("us")] }; ``` ### Do not hash or misuse technical identifiers - **Do not hash** `fbp`, `fbc`, IP address, or user agent. - Do not place email addresses, phone numbers, or other raw personal data in `custom_data`, URLs, campaign names, or Meta event parameters not intended for user matching. - Preserve the original request IP and user agent only when the server event is directly tied to the shopper’s request flow. A delayed background webhook often does not have those values unless Cedar & Coil captured them appropriately earlier. ### Data minimization rule Use the smallest set of identifiers that is lawful, consented where required, and operationally useful. For a logged-out Shopify shopper, email plus valid browser identifiers may be the most practical inputs. Do not invent customer IDs or use unreliable placeholders. --- ## 5. Concrete Shopify setup path ## Option A — Native Facebook & Instagram by Meta sales channel ### What it provides The official Shopify channel: - Connects the Meta business assets and pixel/dataset. - Syncs Shopify products to Meta’s catalog. - Offers customer data-sharing levels. - Automatically tracks common store events, including product views, cart additions, checkout initiation, and purchase. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) ### Setup steps 1. In Shopify admin, go to **Settings → Sales channels**. 2. Install or open **Facebook & Instagram by Meta**. 3. Connect the correct: - Meta Business Portfolio, - ad account, - Facebook Page / Instagram account if applicable, - Meta dataset/pixel. 4. Enable product availability for the Facebook & Instagram sales channel so the Arc Clip Lamp syncs to the Meta catalog. 5. In the sales channel, go to **Settings → Data sharing settings**. 6. Activate customer data sharing and select the highest setting appropriate to Cedar & Coil’s consent and privacy configuration: - **Standard:** browser Pixel only. - **Enhanced:** Meta Pixel plus CAPI. - **Maximum:** Meta Pixel, CAPI, and Meta’s latest advertising technology. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) 7. Confirm only one Meta pixel/dataset is installed on the storefront. 8. Remove or disable redundant Meta Pixel scripts, GTM tags, and third-party apps that fire the same standard ecommerce events. Shopify’s documented navigation for data sharing is **Sales channels → Facebook & Instagram → Settings → Data sharing settings**. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) ### Recommendation for Cedar & Coil **Choose Option A: the native sales channel, with Enhanced or Maximum only if Cedar & Coil’s consent setup supports it.** Why: - Cedar & Coil is a small DTC store with a straightforward Shopify checkout. - The business needs reliable Meta optimization signals, not a custom data pipeline to maintain. - Native catalog sync also reduces the risk of mismatch between Shopify products and Meta `content_ids`. - Shopify’s sales channel is free on Shopify plans, subject to eligibility. ([help.shopify.com](https://help.shopify.com/en/manual/online-sales-channels/social-commerce/facebook-instagram-by-meta?utm_source=openai)) ### Native-integration operating rule If using the native channel: - **Do not send custom browser `Purchase` events.** - **Do not add a custom `orders/paid` CAPI Purchase webhook.** - **Do not add another Meta Pixel through theme code or GTM.** Use Meta Events Manager to validate the native events before launching ads. --- ## Option B — Custom Pixel + custom CAPI implementation Use this only if Cedar & Coil has a real requirement that the native channel cannot meet, such as: - a headless storefront, - a custom checkout or non-Shopify payment path, - a first-party server-side event gateway, - specialized event enrichment, - centralized tracking governance across multiple systems. ### Requirements A custom implementation needs: - storefront event instrumentation, - a secure server endpoint, - a Meta system-user access token stored only in server-side secrets, - a Shopify app/custom app with required order access, - webhook HMAC verification, - retry handling and an idempotency store, - monitoring and reconciliation, - consent propagation, - product-ID mapping shared by catalog, browser, and server events. Shopify recommends webhooks for near-real-time reactions to store events and documents headers for webhook topic, webhook ID, and HMAC verification. ([shopify.dev](https://shopify.dev/docs/apps/build/webhooks?utm_source=openai)) ### Custom Purchase event flow ```text 1. Shopify order is paid. 2. Shopify sends orders/paid webhook to Cedar & Coil endpoint. 3. Server verifies Shopify HMAC signature. 4. Server deduplicates webhook delivery / order processing. 5. Server builds CAPI Purchase event from the authoritative order. 6. Server sends Purchase to Meta CAPI. 7. Server records Meta response, retry status, order ID, and event ID. ``` Shopify notes that webhook delivery order is not guaranteed, so the implementation should use timestamps/order state appropriately and be resilient to retries. ([shopify.dev](https://shopify.dev/docs/apps/build/webhooks?utm_source=openai)) ### Code sketch: server-side Purchase event request This is a simplified Node.js-style example. It assumes: - `order` comes from a verified Shopify `orders/paid` webhook; - personal data has been normalized and hashed appropriately; - the browser Purchase event uses the exact same event ID, `order-${order.id}`; - secret values are in environment variables, never theme JavaScript. ```js import crypto from "node:crypto"; const META_API_VERSION = process.env.META_API_VERSION; // e.g. current supported Graph API version const META_PIXEL_ID = process.env.META_PIXEL_ID; const META_CAPI_TOKEN = process.env.META_CAPI_TOKEN; function sha256(value) { return crypto .createHash("sha256") .update(value.trim().toLowerCase(), "utf8") .digest("hex"); } export async function sendMetaPurchase(order, requestContext = {}) { const eventId = `order-${order.id}`; const contents = order.line_items.map((item) => ({ // Must match the catalog identifier sent by browser Pixel events. id: String(item.variant_id), quantity: Number(item.quantity), item_price: Number(item.price) })); const userData = {}; if (order.email) userData.em = [sha256(order.email)]; if (order.phone) { const normalizedPhone = order.phone.replace(/[^\d]/g, ""); userData.ph = [sha256(normalizedPhone)]; } if (order.shipping_address?.first_name) { userData.fn = [sha256(order.shipping_address.first_name)]; } if (order.shipping_address?.last_name) { userData.ln = [sha256(order.shipping_address.last_name)]; } if (order.shipping_address?.city) { userData.ct = [sha256(order.shipping_address.city)]; } if (order.shipping_address?.province_code) { userData.st = [sha256(order.shipping_address.province_code)]; } if (order.shipping_address?.zip) { userData.zp = [sha256(order.shipping_address.zip)]; } if (order.shipping_address?.country_code) { userData.country = [ sha256(order.shipping_address.country_code.toLowerCase()) ]; } // Add only if captured lawfully from the shopper's browser/request. if (requestContext.fbp) userData.fbp = requestContext.fbp; if (requestContext.fbc) userData.fbc = requestContext.fbc; if (requestContext.ip) userData.client_ip_address = requestContext.ip; if (requestContext.userAgent) { userData.client_user_agent = requestContext.userAgent; } const payload = { data: [{ event_name: "Purchase", event_time: Math.floor( new Date(order.processed_at || order.created_at).getTime() / 1000 ), event_id: eventId, action_source: "website", event_source_url: requestContext.eventSourceUrl || "https://cedarandcoil.example/", user_data: userData, custom_data: { currency: order.currency, value: Number(order.total_price), content_type: "product", content_ids: contents.map((item) => item.id), contents, order_id: String(order.id) } }] }; const response = await fetch( `https://graph.facebook.com/${META_API_VERSION}/${META_PIXEL_ID}/events?access_token=${META_CAPI_TOKEN}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) } ); const result = await response.json(); if (!response.ok) { throw new Error(`Meta CAPI failed: ${JSON.stringify(result)}`); } return { eventId, result }; } ``` ### Custom implementation safeguards - Verify Shopify webhook signatures before trusting payloads. - Store a record keyed by `order.id + Purchase` so one paid order does not generate multiple CAPI Purchases. - Separately record Shopify webhook delivery IDs to handle delivery retries. - Return a fast `2xx` to Shopify after durable receipt; process outbound CAPI calls asynchronously. - Retry transient Meta failures with bounded retries and alerting. - Keep a reconciliation report: Shopify paid orders vs. CAPI Purchase events accepted vs. browser Purchases observed. - Do not use an outdated webhook field such as `checkout_id`; Shopify removed it from order webhook topics in API version 2026-04 and advises use of `checkout_token` where needed. ([shopify.dev](https://shopify.dev/changelog/removed-checkout-id-from-checkouts-and-orders-webhooks?utm_source=openai)) --- ## 6. Validate end to end before scaling spend Do not use paid traffic as the first test. Validate in staging if possible, then with a controlled production test order. ### A. Preflight checklist - [ ] One Meta dataset/pixel ID is selected for Cedar & Coil. - [ ] The Arc Clip Lamp and its variants are present in the Meta catalog. - [ ] Catalog item IDs match the `content_ids` sent by events. - [ ] No duplicate Meta scripts/apps are installed. - [ ] Consent banner behavior has been tested. - [ ] Server token is stored securely and never exposed to the browser. - [ ] Currency and prices are pulled from Shopify rather than hard-coded. - [ ] The native app **or** custom implementation owns each event path; there is no overlapping Purchase sender. ### B. Browser event test In a clean browser profile: 1. Visit the Arc Clip Lamp product page. 2. Confirm one `ViewContent`. 3. Add one lamp to cart. 4. Confirm one `AddToCart`, with: - correct variant ID, - `value: 68.00` for a one-lamp cart at the current listed price, - `currency: "USD"`. 5. Start checkout. 6. Confirm one `InitiateCheckout` with current cart contents and value. 7. Complete a test order. 8. Confirm one browser `Purchase` containing: - actual final order value, - actual order currency, - all purchased variant IDs in `content_ids`, - `contents` line-item detail, - expected event ID. Use Meta Events Manager’s **Test Events** / diagnostics workflow and browser network inspection to confirm what left the page. ### C. Server event test For the same completed order: 1. Verify Shopify produced the expected paid-order event if using custom CAPI. 2. Confirm the webhook signature was accepted. 3. Confirm exactly one server-side `Purchase` was sent. 4. Check Meta’s CAPI response for acceptance/errors. 5. Confirm `event_name = "Purchase"` and `event_id = "order-<same order ID>"`. 6. Verify the CAPI event has: - `action_source: "website"`, - correct `value` and `currency`, - correct `content_ids`, - correct `contents`, - consent-appropriate `user_data`. ### D. Deduplication test For a single real or test order: - Browser Pixel Purchase event: `eventID = order-123` - CAPI Purchase event: `event_id = order-123` Then inspect Meta Events Manager for: - browser and server receipt, - no duplicate purchase count attributable to the paired events, - no missing/dropped parameter warnings requiring correction. Also test these edge cases: | Scenario | Expected behavior | |---|---| | Shopper reloads thank-you page | No additional counted Purchase; stable event ID supports duplicate control. | | Shopify webhook retries | Server idempotency prevents another CAPI Purchase. | | Shopper blocks Meta browser scripts | Server Purchase can still be transmitted if consent and server event flow allow it. | | Browser Purchase arrives but webhook is delayed | Same event ID should pair once both are received. | | Multi-item cart | All variant IDs and quantities are present; total equals the Shopify order total used by policy. | | Discount, shipping, tax | `value` follows the documented order-total policy consistently. | | Mobile Safari / private browsing | Browser signals may be reduced; server event still validates independently where permitted. | ### E. Launch gate Before increasing spend, require all of the following: - No duplicate `Purchase` events for controlled orders. - `Purchase` values match Shopify orders. - `content_ids` match catalog item IDs. - Pixel and CAPI Purchase events share the expected event ID when both are used. - Consent behavior works for visitors who decline marketing tracking. - Meta diagnostics show no unresolved critical implementation warnings. - A simple daily reconciliation is in place. A useful operational metric is: ```text Shopify paid orders vs. unique internal Purchase event IDs sent to CAPI vs. Meta-received Purchase events ``` These figures will not be identical in every reporting surface because of consent, platform rules, and attribution windows, but large unexplained discrepancies should trigger investigation. --- ## 7. Consent and compliance note This guide is technical implementation guidance, not legal advice. ### Required operating principles 1. **Update Cedar & Coil’s privacy policy** to explain use of Meta Business Tools, including browser Pixel and server-side CAPI where enabled. Shopify explicitly states that merchants are responsible for informing customers about how personal information is shared and keeping the privacy policy current. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) 2. **Use a consent management platform (CMP)** that reflects the jurisdictions in which Cedar & Coil sells and advertises. The CMP should be able to: - block or limit Meta browser tags until the appropriate consent is present where required; - prevent nonessential server-side marketing data from being sent when consent is declined or withdrawn; - retain consent records; - honor applicable opt-out and deletion requests. 3. **Respect opt-out signals and applicable state/privacy laws.** For U.S. visitors, requirements can vary by state and by the nature of data sharing. If Cedar & Coil sells into the EU/UK, ePrivacy/GDPR-style consent requirements are generally stricter for advertising technologies. 4. **Minimize data.** Send only fields that are necessary, lawfully collected, and permitted for Meta use. Never expose access tokens, raw customer data, or order details in storefront JavaScript, URLs, or client-visible logs. 5. **Align Shopify setting with policy.** Shopify labels Meta data sharing as optional and offers Standard, Enhanced, and Maximum levels. Select the level Cedar & Coil can support with its disclosures and consent flow—not merely the setting that sends the most data. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) --- ## Final recommendation For Cedar & Coil’s initial Meta ads launch: 1. Install and configure **Facebook & Instagram by Meta** in Shopify. 2. Connect a single Meta dataset/pixel and catalog. 3. Enable **Enhanced or Maximum** data sharing only after consent and policy review. 4. Validate `ViewContent`, `AddToCart`, `InitiateCheckout`, and `Purchase`. 5. Confirm the Arc Clip Lamp’s catalog IDs match event `content_ids`. 6. Verify browser and server Purchase handling is deduplicated. 7. Do **not** add a parallel custom Purchase webhook unless Cedar & Coil intentionally replaces the native Meta purchase pipeline and can own testing, idempotency, and ongoing maintenance.
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.
✓The guide dedicates Section 1 to explaining browser Pixel vs server CAPI limitations (cookie blocking, ad blockers) and why both are needed for resilience.
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓Section 2 provides a table and code snippets for ViewContent, AddToCart, InitiateCheckout, and Purchase, with Purchase explicitly requiring 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 sendMetaPurchase Node.js function includes event_name, event_time, event_id, action_source: 'website', and a user_data object with hashed fields.
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 explicitly instructs using 'Meta Events Manager's Test Events / diagnostics workflow' and includes a dedicated 'Deduplication test' subsection checking for duplicate purchase counts.
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 guide states Purchase should be authoritative from the Shopify orders/paid webhook ('A Shopify orders/paid webhook is excellent for sending an authoritative server-side Purchase') rather than only the thank-you page, and specifies browser triggers for the other three events.
limits_stated
Limitations are stated honestly: no promised attribution-recovery percentages, and consent/regional rules are noted as constraints on what may be sent.
✓No attribution-recovery percentages are promised anywhere, and Section 7 explicitly ties consent/CMP behavior and regional privacy laws as constraints on what data can be 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 specifies sending the 'same Meta dataset/pixel ID', 'same standard event name', and 'same event_id' on both Pixel and CAPI, with explicit bad-example contrasts, showing technical correctness rather than a vague mention.
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 event_id is derived deterministically as `order-${order.id}` and the guide notes 'Shopify webhook retries: server idempotency prevents another CAPI Purchase,' confirming stable reuse across retries.
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 code sets `event_time: Math.floor(new Date(order.processed_at || order.created_at).getTime() / 1000)`, using the order's own timestamp rather than the current send time, in Unix seconds.
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 sha256 function trims and lowercases values before hashing, and the guide explicitly instructs normalizing (lowercase, trim, canonical format) before SHA-256 hashing email, phone, name, and address 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).
✓The guide gives a clear, decisive recommendation ('Choose Option A: the native sales channel...') with concrete numbered setup steps for a small DTC store, rather than an undifferentiated list.

GPT-5.6 Sol 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." metadata: version: 2.0.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 --- ## 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.55 · 128.3s · 7.9k tok
# Cedar & Coil: Shopify-to-Meta Conversion Tracking Implementation Guide ## 1. Recommended architecture Use two complementary data paths: ```text Shopify storefront ├─ Browser: Meta Pixel ──────────────────┐ └─ Server: Shopify → Conversions API ────┤→ Meta dataset/pixel shared event IDs ──────┘ deduplicated ``` ### Browser Meta Pixel The browser Pixel should report customer interactions as they happen: - `ViewContent` - `AddToCart` - `InitiateCheckout` - `Purchase` The browser path supplies useful browser context, including the page URL, browser identifiers, and Meta click/browser cookies when available. However, browsers, consent settings, tracking prevention, network failures, and ad blockers can prevent these requests from reaching Meta. ### Server-side Conversions API Conversions API, or CAPI, sends events from Shopify or Cedar & Coil’s backend directly to Meta. Server-to-server delivery is not blocked by browser-based ad blockers and is especially useful for ensuring completed orders are reported when the browser Purchase request fails. Shopify’s Enhanced and Maximum sharing levels use both the Pixel and CAPI; Shopify specifically documents server-side Purchase reporting for these levels. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing)) ### Why both are needed - **Pixel only:** Rich browser context, but susceptible to browser privacy controls and page abandonment. - **CAPI only:** More dependable order delivery, but may lack browser identifiers and immediate interaction context. - **Pixel plus CAPI:** Combines browser context with a more reliable server event, provided duplicate copies are assigned the same event ID. CAPI does not bypass consent requirements, create missing identity data, or guarantee attribution. It makes delivery more resilient; Meta still determines matching and attribution. --- ## 2. Standard events and parameters Use Meta’s standard event names exactly as capitalized below. Shopify’s native integration automatically supports these four events, along with several others. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing)) Keep product identifiers consistent across: 1. Browser events 2. Server events 3. The Meta product catalog, if Cedar & Coil uses catalog or dynamic ads For Shopify, a stable variant ID is generally preferable. If the catalog feed uses SKUs instead, use the same SKU format in every event. ### Event plan | Meta event | Trigger | Key parameters | |---|---|---| | `ViewContent` | Arc Clip Lamp product page is viewed | `content_ids`, `content_type`, `content_name`, `value`, `currency` | | `AddToCart` | Shopify confirms the lamp was added to cart | `content_ids`, `contents`, `content_type`, `value`, `currency`, `num_items` | | `InitiateCheckout` | Customer enters Shopify checkout | `content_ids`, `contents`, `value`, `currency`, `num_items` | | `Purchase` | Order is completed or paid, according to the chosen accounting rule | `content_ids`, `contents`, `value`, `currency`, `num_items`, optionally `order_id` | Shopify exposes standard customer events such as `product_viewed` and checkout progression events through its Web Pixels API, including structured product, checkout, currency, and URL data. ([shopify.dev](https://shopify.dev/docs/api/web-pixels-api/standard-events/product_viewed?utm_source=openai)) ### `ViewContent` Fire once when the Arc Clip Lamp product detail page is viewed. ```javascript fbq('track', 'ViewContent', { content_ids: ['SHOPIFY_VARIANT_ID'], content_type: 'product', content_name: 'Arc Clip Lamp', value: 68.00, currency: 'USD' }, { eventID: 'vc_UNIQUE_EVENT_ID' }); ``` Guidance: - Use the selected variant ID, not the page handle. - `value` should reflect the displayed product/variant price. - Do not fire `ViewContent` on collection pages or every general page view. ### `AddToCart` Fire only after Shopify confirms a successful cart addition—not merely when the button is clicked. ```javascript fbq('track', 'AddToCart', { content_ids: ['SHOPIFY_VARIANT_ID'], content_type: 'product', contents: [{ id: 'SHOPIFY_VARIANT_ID', quantity: 1, item_price: 68.00 }], value: 68.00, currency: 'USD', num_items: 1 }, { eventID: 'atc_UNIQUE_EVENT_ID' }); ``` For multiple units, `value` should be the quantity multiplied by the unit price. ### `InitiateCheckout` Fire when the customer actually enters checkout. Shopify’s `checkout_started` customer event is the appropriate custom-implementation trigger. ([shopify.dev](https://shopify.dev/docs/api/web-pixels-api/standard-events/checkout_started?utm_source=openai)) ```javascript fbq('track', 'InitiateCheckout', { content_ids: ['SHOPIFY_VARIANT_ID'], content_type: 'product', contents: [{ id: 'SHOPIFY_VARIANT_ID', quantity: 1, item_price: 68.00 }], value: 68.00, currency: 'USD', num_items: 1 }, { eventID: 'ic_UNIQUE_EVENT_ID' }); ``` Use the checkout’s actual value. Decide whether this represents subtotal or total and apply that definition consistently. ### `Purchase` Fire once per successfully completed order. For a server implementation, `orders/paid` is usually safer than `orders/create` when payment can remain pending; Shopify publishes `orders/paid` when an order becomes paid. ([shopify.dev](https://shopify.dev/docs/api/webhooks/2025-04?utm_source=openai)) ```javascript fbq('track', 'Purchase', { content_ids: ['SHOPIFY_VARIANT_ID'], content_type: 'product', contents: [{ id: 'SHOPIFY_VARIANT_ID', quantity: 1, item_price: 68.00 }], value: 74.12, // Example only: use the real order total currency: 'USD', num_items: 1, order_id: 'SHOPIFY_ORDER_ID' }, { eventID: 'shopify_purchase_SHOPIFY_ORDER_ID' }); ``` Purchase requirements: - **Do not hardcode `$68`.** Send the order’s actual monetary value. - Include `value` as a number, not a currency-formatted string. - Include the actual three-letter currency code. - Include all purchased item IDs in `content_ids`. - `contents` should contain item ID, quantity, and preferably item price. - Use the same product-ID format as preceding funnel events. - Do not fire again when a thank-you or order-status page is reloaded. Shopify’s native integration defines an order-value event as the checkout’s total price, including duties, taxes, and discounts. Use that same definition if comparing native Shopify events with your own reports. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing)) --- ## 3. Exactly how Pixel/CAPI deduplication works For the same real-world action, send: 1. The exact same event name 2. The exact same unique event ID 3. To the same Meta pixel/dataset The field names differ by transport: | Browser Pixel | Server CAPI | |---|---| | Event name: `Purchase` | `event_name: "Purchase"` | | `eventID` | `event_id` | Meta uses the event name and event ID combination to identify the browser and server copies as the same event. Its published server-event schema specifies that the browser `eventID` must match the server `event_id`, with `event_name` also participating in deduplication. ([github.com](https://github.com/facebookincubator/Facebook-Server-Side-API-Swagger/blob/main/server-side-api.yaml?utm_source=openai)) ### Purchase example Browser: ```javascript const eventId = `shopify_purchase_${orderId}`; fbq('track', 'Purchase', purchaseData, { eventID: eventId }); ``` Server: ```json { "event_name": "Purchase", "event_id": "shopify_purchase_1234567890" } ``` ### Requirements - IDs are case-sensitive strings; do not transform one side. - `Purchase` and `purchase` do not match. - `shopify_purchase_123` and `123` do not match. - Generate one ID per actual event occurrence. - Never reuse one `AddToCart` ID for multiple additions. - Retrying the same server request must reuse the original ID. - Send the browser and server copies promptly rather than relying on delayed backfills. For Purchase, a deterministic order-based ID is appropriate: ```text shopify_purchase_{shopify_order_id} ``` For behavioral events, Shopify’s customer-event ID can be used as the basis: ```text meta_{shopify_customer_event_id} ``` ### Two different kinds of deduplication Do not confuse: 1. **Meta transport deduplication:** Pixel and CAPI copies share `eventID`/`event_id`. 2. **Shopify webhook idempotency:** The backend ignores repeated webhook deliveries using `X-Shopify-Webhook-Id` or a stored order-processing key. Shopify warns that webhooks can be delivered more than once and recommends idempotent processing or storing the webhook ID. It also requires verifying each webhook’s HMAC signature before trusting the payload. ([shopify.dev](https://shopify.dev/docs/apps/build/webhooks/verify-deliveries)) --- ## 4. Preparing customer information for server-side events CAPI `user_data` helps Meta match the event to an account. Send only data Cedar & Coil is permitted to process for this purpose. ### Normalize and SHA-256 hash matching fields Typical fields include: | CAPI field | Source | Preparation | |---|---|---| | `em` | Customer email | Trim, lowercase, normalize, then SHA-256 | | `ph` | Customer phone | Normalize with country code, remove formatting, then SHA-256 | | `fn` | First name | Normalize, then SHA-256 | | `ln` | Last name | Normalize, then SHA-256 | | `ct` | City | Normalize, then SHA-256 | | `st` | State/region | Normalize, then SHA-256 | | `zp` | Postal code | Normalize, then SHA-256 | | `country` | Country code | Lowercase two-letter code, then SHA-256 | | `external_id` | Stable internal customer ID | Normalize, then SHA-256 | Prefer Meta’s current Business SDK over hand-built normalization. The official Node SDK can normalize and SHA-256-hash customer-information parameters automatically. ([github.com](https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md)) ### Do not hash these fields Send these in their expected raw formats: - `client_ip_address` - `client_user_agent` - `fbp` - `fbc` `fbp` represents Meta’s browser identifier. `fbc` represents a Meta click identifier derived from a valid Meta click context, typically involving `fbclid`. Do not manufacture either value. ### Important Shopify detail If using an `orders/paid` webhook: - Do **not** use the webhook request’s IP address or user-agent; those identify Shopify’s server, not the buyer. - Use buyer browser information retained on the order or captured earlier, where available and permitted. - Capture `fbp` and `fbc` during the browser session and associate them with the cart, checkout, or order if implementing custom CAPI. - If a field is unavailable, omit it rather than sending a placeholder. Meta’s current parameter-builder tooling can populate `fbc`, `fbp`, client IP, source URL, and referrer URL from an incoming customer request. That is useful for browser-to-backend requests, but not for a later Shopify webhook whose request context belongs to Shopify. ([github.com](https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md)) Hashing is a transmission requirement for matching fields; it does not make the data anonymous or remove Cedar & Coil’s privacy obligations. --- ## 5. Concrete Shopify setup path ## Option A: Native Facebook & Instagram by Meta sales channel ### Setup steps 1. In Shopify admin, go to **Sales channels → Facebook & Instagram**. 2. Complete the Meta business connection, selecting the correct: - Meta business portfolio - Ad account - Facebook Page - Product catalog, if used 3. Open **Settings → Share data settings** or **Data sharing settings**. 4. Enable customer data sharing. 5. Select the correct Meta pixel/dataset. 6. Choose **Maximum**, subject to Cedar & Coil’s consent and legal configuration. 7. Confirm the setup. 8. Remove any old Meta Pixel installation from: - `theme.liquid` - Shopify Online Store preferences - Google Tag Manager - Third-party tracking apps Shopify documents this admin path and warns that leaving a separately installed theme Pixel in place can produce duplicate or incorrect reporting. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-pixel)) The native integration automatically tracks events including `ViewContent`, `AddToCart`, `InitiateCheckout`, and `Purchase`. Maximum uses the Pixel, Conversions API, and Shopify’s current supported Meta advertising integration. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing)) ### Recommendation for Cedar & Coil **Use the native Facebook & Instagram sales channel with Maximum sharing for this small DTC store**, assuming the consent configuration permits it. Reasons: - Low implementation and maintenance burden - Shopify-managed checkout coverage - Built-in browser Pixel and server-side Purchase connection - Automatic event mapping - Less risk of malformed customer data - Less risk of webhook or API-version maintenance problems - Better fit for a one-product store without unusual attribution requirements Do not run a second CAPI app or custom Meta Pixel for the same events unless you can prove that both systems share exactly the same event IDs. Usually they will not, creating double-counting risk. ## Option B: Custom implementation Use custom tracking only if Cedar & Coil needs: - Full control over event IDs and payloads - Server-side funnel events beyond Purchase - A first-party event store or routing layer - Custom refund or lifecycle handling - Detailed logging and reconciliation - Control over the precise product-ID namespace A robust custom Shopify implementation consists of: 1. **Browser:** Shopify Web Pixel app extension subscribing to: - `product_viewed` - `product_added_to_cart` - `checkout_started` - `checkout_completed` 2. **Backend:** A Shopify app receiving an `orders/paid` webhook. 3. **Identity bridge:** Storage linking browser IDs and Meta click data to checkout/order IDs. 4. **Queue:** Asynchronous CAPI delivery with retries. 5. **Idempotency store:** Prevent repeated processing of the same order or webhook. 6. **Reconciliation job:** Periodically check paid orders against successfully sent Meta events. Shopify recommends web pixel app extensions for app implementations; these consume structured Shopify customer events across storefront and checkout surfaces. Custom pixels run in a sandbox with important browser limitations, and Shopify recommends app pixels for stronger integrations. ([shopify.dev](https://shopify.dev/docs/apps/build/marketing/pixels)) ### Server-side Purchase sketch The following Node.js sketch illustrates the CAPI portion of an `orders/paid` handler. Production code must first verify Shopify’s HMAC, enforce consent rules, acknowledge quickly, and queue processing. ```javascript import crypto from 'node:crypto'; const PIXEL_ID = process.env.META_PIXEL_ID; const ACCESS_TOKEN = process.env.META_CAPI_ACCESS_TOKEN; const GRAPH_VERSION = 'v26.0'; // Pin and review during API upgrades. const sha256 = value => crypto .createHash('sha256') .update(String(value), 'utf8') .digest('hex'); const hashText = value => { if (!value) return undefined; return sha256(String(value).trim().toLowerCase()); }; const hashPhone = value => { if (!value) return undefined; // Ensure the source includes its country code before hashing. const normalized = String(value).replace(/[^\d]/g, ''); return normalized ? sha256(normalized) : undefined; }; const compact = object => Object.fromEntries( Object.entries(object).filter( ([, value]) => value !== undefined && value !== null && value !== '' ) ); const getNoteAttribute = (order, name) => order.note_attributes?.find(attribute => attribute.name === name)?.value; export async function sendMetaPurchase(order, { testEventCode } = {}) { const eventId = `shopify_purchase_${order.id}`; const contentIds = order.line_items.map(line => String(line.variant_id || line.product_id) ); const contents = order.line_items.map(line => ({ id: String(line.variant_id || line.product_id), quantity: Number(line.quantity), item_price: Number(line.price) })); const address = order.billing_address || order.shipping_address || {}; const userData = compact({ // Hashed matching fields em: order.email ? [hashText(order.email)] : undefined, ph: order.phone ? [hashPhone(order.phone)] : undefined, fn: hashText(address.first_name), ln: hashText(address.last_name), ct: hashText(address.city), st: hashText(address.province_code || address.province), zp: hashText(address.zip), country: hashText(address.country_code), external_id: order.customer?.id ? [hashText(order.customer.id)] : undefined, // Do not hash these client_ip_address: order.browser_ip || undefined, client_user_agent: order.client_details?.user_agent || undefined, fbp: getNoteAttribute(order, '_fbp') || undefined, fbc: getNoteAttribute(order, '_fbc') || undefined }); const payload = compact({ data: [{ event_name: 'Purchase', event_time: Math.floor( new Date(order.processed_at || order.created_at).getTime() / 1000 ), event_id: eventId, action_source: 'website', event_source_url: `https://cedar-and-coil.example/checkouts/order/${order.id}`, user_data: userData, custom_data: { currency: order.currency, value: Number(order.total_price), content_ids: contentIds, content_type: 'product', contents, num_items: order.line_items.reduce( (sum, line) => sum + Number(line.quantity), 0 ), order_id: String(order.id) } }], test_event_code: testEventCode }); const endpoint = `https://graph.facebook.com/${GRAPH_VERSION}/${PIXEL_ID}/events` + `?access_token=${encodeURIComponent(ACCESS_TOKEN)}`; const response = await fetch(endpoint, { method: 'POST', headers: {'content-type': 'application/json'}, body: JSON.stringify(payload) }); const responseBody = await response.json(); if (!response.ok) { throw new Error( `Meta CAPI error ${response.status}: ${JSON.stringify(responseBody)}` ); } return { eventId, metaResponse: responseBody }; } ``` Implementation notes: - Store a record such as `meta:Purchase:{order.id}` before or atomically with processing. - Retry network and temporary API failures with the **same** `event_id`. - Store the response, status, attempt count, and last error. - Keep the access token in a secrets manager, never in theme or pixel code. - Verify the Shopify webhook against the raw request body before parsing it. - Periodically reconcile Shopify paid orders because Shopify advises against treating webhooks as an infallible delivery mechanism. ([shopify.dev](https://shopify.dev/docs/apps/build/webhooks?utm_source=openai)) - Prefer Meta’s supported Business SDK when possible; its CAPI client supplies typed event objects and current normalization support. ([github.com](https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md)) --- ## 6. End-to-end validation before scaling spend No Meta campaign has launched and no performance baseline exists, so validate signal quality before using the Purchase event for meaningful optimization. ### A. Audit existing installations Check for: - Meta Pixel code in `theme.liquid` - A Pixel under Online Store preferences - Meta tags in GTM - Facebook & Instagram sales channel - Third-party Shopify Meta/CAPI apps - Old checkout or order-status scripts Assign one system as the owner of each Meta event. ### B. Use Meta Test Events In Meta Events Manager: 1. Select the correct dataset/pixel. 2. Open **Test Events**. 3. Open the Shopify store using the browser test flow. 4. If testing custom CAPI, add the displayed `test_event_code` to the server request. 5. Perform this sequence: - View the Arc Clip Lamp page - Add one lamp to cart - Begin checkout - Complete a test purchase 6. Confirm the four expected event names appear. Remove `test_event_code` from production requests. ### C. Validate every event’s payload For each event, inspect: - Correct event name and trigger - Valid, stable `content_ids` - Correct `content_type` - Numeric `value` - Correct `currency` - Correct item quantities - Actual order total on Purchase - No email, phone number, or other raw PII in `custom_data` - No placeholder or test values ### D. Validate Purchase deduplication For one test order, confirm: - A browser Purchase is received. - A server Purchase is received. - Both have the same event name. - Both have the same event ID. - Events Manager identifies browser and server connection methods for the event. - The order is processed as one Purchase, not two. Also reload the thank-you/order-status page and confirm that it does not create another distinct Purchase. ### E. Validate failure modes Test at least: - Chrome - Safari - Firefox - Mobile Safari or Chrome - Browser with a common ad blocker - Consent accepted - Consent rejected - Slow connection - Checkout using an accelerated wallet if offered Expected behavior: - Browser events may be unavailable under blocked or denied conditions. - Server events should follow Cedar & Coil’s consent and legal policy. - A failed CAPI delivery should retry without creating a new event ID. - A repeated Shopify webhook should not produce a second server Purchase. ### F. Reconcile against Shopify For a controlled test period, compare: ```text Shopify paid online-store orders versus Meta Purchase events received ``` Use **received events**, not attributed conversions, for this technical comparison. Attribution reporting will not equal Shopify order counts because attribution applies separate identity, ad-interaction, timing, and reporting rules. Investigate: - Missing orders - Duplicate Purchases - Currency discrepancies - Purchase values that differ from Shopify - Server events without expected matching fields - API failures or delayed queue jobs ### G. Monitor after launch Initially review: - Meta Events Manager Diagnostics - Browser/server connection-method coverage - Event Match Quality trends - CAPI API errors - Shopify webhook failures - Daily paid-order/event reconciliation - Sudden changes in event volume or Purchase value Do not scale solely because Events Manager shows events. First confirm that real paid orders, event values, deduplication, and consent behavior are correct. --- ## 7. Consent and compliance note Before enabling Maximum sharing or custom CAPI: - Update Cedar & Coil’s privacy policy to disclose Meta Pixel and CAPI use. - Configure Shopify’s privacy and consent tools for the regions served. - Ensure browser pixels respect required consent signals. - Apply the same consent decision to server-side events; CAPI must not become a way to transmit events that the customer declined. - Honor applicable opt-out signals and requests, including relevant US state privacy rights and Global Privacy Control where required. - Collect only the customer fields needed for matching. - Limit access and retention for raw identity and event-delivery logs. - Establish processes for deletion and access requests. - Review Meta’s Business Tools terms and applicable data-processing terms. - Obtain legal advice for Cedar & Coil’s markets and data practices. Shopify’s web pixel app extensions honor customer consent signals and, in opt-in regions, execute tracking callbacks only after the required consent is provided. Shopify also states that merchants are responsible for explaining Facebook/Meta data sharing in their privacy policy. ([shopify.dev](https://shopify.dev/docs/apps/build/marketing/pixels)) **Recommended final configuration:** Facebook & Instagram by Meta sales channel, Maximum data sharing where legally permitted, one connected dataset/pixel, no parallel Pixel installations, and a documented pre-launch test purchase confirming browser/server Purchase deduplication.
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.
✓The guide dedicates Section 1 to Pixel + CAPI architecture, explaining browser limitations (ad blockers, consent) and why CAPI provides reliable server delivery, concluding with 'Pixel plus CAPI: Combines browser context with a more reliable server event.'
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓Section 2 provides a table and code for ViewContent, AddToCart, InitiateCheckout, and Purchase, each with value/currency and content_ids, with Purchase explicitly requiring 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.js sendMetaPurchase function includes event_name: 'Purchase', event_time computed from order timestamp, event_id, action_source: 'website', and a compact user_data object with hashed fields.
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 6B walks through Meta Events Manager Test Events with test_event_code, and Section 6D explicitly checks 'Both have the same event ID... The order is processed as one Purchase, not 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).
✓The guide specifies browser triggers for ViewContent/AddToCart/InitiateCheckout and designates the orders/paid webhook as the server-side source of truth for Purchase, explicitly warning 'Do not fire again when a thank-you or order-status page is reloaded.'
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 response states 'CAPI does not bypass consent requirements, create missing identity data, or guarantee attribution' and Section 7 lists consent/regional constraints (GPC, US state privacy rights, opt-out honoring).
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 explains that 'the exact same event name' and 'the exact same unique event ID' sent to the same pixel/dataset lets 'Meta uses the event name and event ID combination to identify the browser and server copies as the same event,' with matching code examples.
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 event_id is derived deterministically as `shopify_purchase_${order.id}` and the guide instructs 'Retry network and temporary API failures with the same event_id,' ensuring stability across retries.
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 computed as `Math.floor(new Date(order.processed_at || order.created_at).getTime() / 1000)`, tying it to the order's actual timestamp rather than the send/retry 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.
✓The hashText function trims and lowercases values before SHA-256 hashing (`crypto.createHash('sha256')...`), and hashPhone normalizes phone digits before hashing.
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).
✓The guide gives a decisive 8-step setup for the native Facebook & Instagram sales channel and explicitly states 'Use the native Facebook & Instagram sales channel with Maximum sharing for this small DTC store' as the recommendation.

Claude Sonnet 5 default

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." metadata: version: 2.0.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 --- ## 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.19 · 96.7s · 7.2k tok
# Meta Conversions Tracking Implementation Guide — Cedar & Coil / Arc Clip Lamp **Scope:** This is a technical implementation guide for wiring reliable Meta ad conversion tracking into the Cedar & Coil Shopify store ahead of Arc Clip Lamp campaign launch. It assumes standard Shopify (non-headless) checkout and a technical marketer who can install apps, edit theme/app settings, and either write or brief a developer on a small server-side script. --- ## 1. Recommended Architecture: Pixel + Conversions API (CAPI), Deduplicated **Architecture:** Meta Pixel (browser JavaScript) fires events client-side, and a server-side integration — either Shopify's native Meta channel or a custom script — sends the same events to Meta's Conversions API from your server/Shopify's backend. Both paths send data to the same Meta pixel ID, and each event carries a matching `event_id` so Meta can deduplicate. **Why both are needed, not just one:** - **Pixel alone is fragile.** Safari's Intelligent Tracking Prevention, ad blockers, and users declining cookie consent all reduce or block browser-side pixel firing, especially for post-purchase events on the order status page. - **CAPI alone loses some browser signal.** CAPI is only as good as the identifiers you pass it (see Section 4); without the `fbp`/`fbc` browser cookies and click IDs that the Pixel captures, server-side events match less precisely. - **Sending both events maximizes signal coverage** while the deduplication layer prevents Meta from counting the same conversion twice. As advertisers increasingly rely on a hybrid setup that combines the Meta Pixel (client-side) with the Conversions API (server-side), a new technical risk emerges: duplicate events. That risk is fully solved by proper `event_id` matching (Section 3), so it is not a reason to avoid the hybrid setup — it's a reason to implement dedup correctly. Do not treat this as a claim about a specific percentage of "recovered" conversions — actual impact depends on your traffic mix, browser share, and consent rates, and no fixed number should be promised to stakeholders. --- ## 2. Standard Events and Key Parameters Send these four standard events from **both** Pixel and CAPI, using identical `event_name` values so Meta can match them for optimization and reporting. | Event | Fires when | Required/key parameters | |---|---|---| | **ViewContent** | Arc Clip Lamp product page loads | `content_ids: ["arc-clip-lamp-<variant_id>"]`, `content_type: "product"`, `content_name: "Arc Clip Lamp"`, `value: 68.00`, `currency: "USD"` | | **AddToCart** | Item added to cart | Same as above plus `contents: [{id, quantity}]`; `value` = price × quantity | | **InitiateCheckout** | Checkout begins | `content_ids`, `contents` (with quantities), `num_items`, `value` (cart subtotal), `currency: "USD"` | | **Purchase** | Order confirmed (thank-you/order-status page and server-side on order creation) | `content_ids` (SKU or variant IDs for every line item), `content_type: "product"`, `contents: [{id, quantity, item_price}]`, `value` (order total, matching what's charged, e.g., including or excluding tax/shipping consistently), `currency: "USD"`, `order_id` (Shopify order ID, used as part of the dedup key) | Notes specific to Cedar & Coil's single-SKU launch: - Since the Arc Clip Lamp is a single $68 product (with possible variants like color/finish if added later), keep `content_ids` scoped to the Shopify **variant ID**, not just a generic product ID — this keeps catalog matching and any future dynamic ads accurate. - `value` and `currency` are **required on every event above** for Meta to optimize for and report on purchase value/ROAS; never omit them or send `0`. - On **Purchase**, `content_ids` must reflect the actual line items in that specific order (not a static default), since this powers Meta's value-based optimization. --- ## 3. How Pixel/CAPI Deduplication Works Meta deduplicates by comparing two fields on incoming events: **`event_name`** and **`event_id`**. - Every Pixel event includes an event_id. This ID must be unique per conversion and consistent across both client and server implementations. - Concretely: when the browser fires `Purchase` via Pixel, generate a unique ID (e.g., the Shopify order ID, or a UUID) and pass it as the event's `eventID`. When your server sends the corresponding `Purchase` event via CAPI for that same order, it must use **the exact same `event_id` string** and the **exact same `event_name`** ("Purchase"). - The event name must be the same (e.g., Purchase, AddToCart) — mismatched names between the two events will defeat dedup even if the ID matches. - Meta then treats the pair as one event for reporting and optimization, keeping whichever has richer/better-matched data, rather than double-counting. - Practical rule for Cedar & Coil: use the **Shopify order ID** (or order `id`/`token`) as the `event_id` for Purchase, and a generated session-scoped ID (e.g., cart token + timestamp) for ViewContent/AddToCart/InitiateCheckout, applied identically on both the Pixel call and the corresponding CAPI call. --- ## 4. Preparing Customer Information for Server-Side Sending CAPI events include a `user_data` object that Meta uses to match the event to a person and ad click. Before sending, customer data must be normalized and hashed: **Normalize first, then hash with SHA-256, lowercase hex output:** - **Email (`em`):** lowercase, trim whitespace, hash. - **Phone (`ph`):** strip all non-digit characters (no `+`, spaces, dashes, parentheses), include country code, then hash. - **First/last name (`fn`/`ln`):** lowercase, trim, strip accents/punctuation, then hash. - **City/state/zip (`ct`/`st`/`zp`):** lowercase, trim, no spaces for zip, then hash. - **Country (`country`):** lowercase two-letter ISO code, hash. **Never hash or transform these — send as plain text:** - **`client_ip_address`** — the customer's real IP at the time of the event (server-captured, not your server's IP). - **`client_user_agent`** — the browser's user agent string from the original request. - **`fbp`** — the `_fbp` cookie value set by the Meta Pixel in the browser. - **`fbc`** — the `_fbc` cookie value (derived from the `fbclid` URL parameter on ad click), if present. - **`external_id`** — you may hash this too (recommended), typically the Shopify customer ID. **Practical checklist before any server-side send:** 1. Confirm you're capturing `_fbp`/`_fbc` cookies from the browser session and passing them through to whatever creates the server-side event (this is what links CAPI events back to the original ad click). 2. Apply hashing consistently — a formatting mismatch (e.g., uppercase email) produces a different hash and silently breaks matching without erroring. 3. Never log or store raw (unhashed) PII in the pipeline used for sending events, beyond what's needed transiently to compute the hash. 4. Send as many matching parameters as are legitimately available (email + phone + name + address) — more matched fields generally improve match quality, though Meta does not publish guaranteed match-rate outcomes. --- ## 5. Shopify Setup Path: Native App vs. Custom Implementation ### Option A — Shopify's native Meta sales channel ("Facebook & Instagram" app) Install the Meta channel from the Shopify App Store, connect it to your Meta Business Manager, and turn on Conversions API in its settings. Shopify's native Meta sales channel integration is the simplest path to enabling the Conversion API for most Shopify merchants. It handles the server-side event sending automatically once you flip the switch. It also handles the browser Pixel via Shopify's Web Pixels framework and keeps `event_id` matching between Pixel and CAPI internally. **Pros:** no code, no server to maintain, Shopify handles dedup and event mapping (including checkout events, which are otherwise hard to instrument without Shopify Plus checkout extensibility access). **Cons:** less control over custom parameters, timing, or non-standard events; troubleshooting is limited to what the app's settings and Meta Events Manager expose. ### Option B — Custom implementation (Pixel via theme/Web Pixels API + your own CAPI server call) You add the Meta Pixel yourself (via Shopify's Web Pixels API or a tag manager) and write a small backend service (e.g., a Shopify webhook listener on `orders/create` and `orders/paid`) that builds and sends the CAPI payload directly to Meta's Graph API. **Pros:** full control over parameters, custom event logic, easier to extend later (e.g., adding server-side events beyond the standard four). **Cons:** requires ongoing developer maintenance, you own webhook reliability/retries, and you must implement dedup logic yourself correctly. ### Recommendation for Cedar & Coil (small DTC store, single SKU, pre-launch) **Use the native Meta sales channel app (Option A).** At this stage — one product, no campaign history, a small team — the native integration gets Pixel + CAPI + deduplication working correctly with minimal engineering time, which matters most before any ad spend has started. Revisit a custom build only if you later need event parameters or logic the native app doesn't support (e.g., custom audiences based on non-standard behavioral events). ### Code sketch: server-side Purchase event (for reference, or if you outgrow the native app) ```python import hashlib import requests import time PIXEL_ID = "YOUR_PIXEL_ID" ACCESS_TOKEN = "YOUR_CAPI_ACCESS_TOKEN" GRAPH_API_VERSION = "v19.0" def sha256_hash(value: str) -> str: return hashlib.sha256(value.strip().lower().encode("utf-8")).hexdigest() def build_purchase_event(order, request_meta): return { "event_name": "Purchase", "event_time": int(time.time()), "event_id": str(order["id"]), # must match the Pixel event_id for this order "action_source": "website", "event_source_url": order.get("order_status_url"), "user_data": { "em": [sha256_hash(order["customer_email"])], "ph": [sha256_hash(order["customer_phone"])] if order.get("customer_phone") else [], "client_ip_address": request_meta["ip"], # plain text, not hashed "client_user_agent": request_meta["user_agent"],# plain text, not hashed "fbp": request_meta.get("fbp"), # plain text, not hashed "fbc": request_meta.get("fbc"), # plain text, not hashed }, "custom_data": { "currency": "USD", "value": float(order["total_price"]), "content_type": "product", "content_ids": [str(li["variant_id"]) for li in order["line_items"]], "contents": [ {"id": str(li["variant_id"]), "quantity": li["quantity"], "item_price": float(li["price"])} for li in order["line_items"] ], }, } def send_purchase_event(order, request_meta): payload = {"data": [build_purchase_event(order, request_meta)]} url = f"https://graph.facebook.com/{GRAPH_API_VERSION}/{PIXEL_ID}/events" resp = requests.post(url, params={"access_token": ACCESS_TOKEN}, json=payload, timeout=5) resp.raise_for_status() return resp.json() ``` This would be triggered from a Shopify `orders/paid` webhook, with `fbp`/`fbc`/`client_ip_address`/`client_user_agent` captured at checkout time and stored against the order (e.g., via a checkout UI extension or order note) so they're available when the webhook fires. --- ## 6. Validating the Setup Before Scaling Spend Do not turn on paid delivery until all of the following pass: 1. **Meta Events Manager → Test Events:** Place a real test order (or use the browser test event tool) and confirm ViewContent, AddToCart, InitiateCheckout, and Purchase all arrive from **both** the browser and server sources. 2. **Deduplication status:** In Events Manager, check the "Event Deduplication" column for each event. Each should show pairs matched between "Browser" and "Server" sources rather than two separate unmatched counts. Persistent unmatched duplicates indicate an `event_id`/`event_name` mismatch to fix (Section 3). 3. **Parameter completeness:** Spot-check that `value` and `currency` are present and correct on every event (especially Purchase — the value should equal the actual order total, not just $68 flat, once discounts/shipping are factored in consistently). 4. **Match quality:** Review the Diagnostics/match quality indicator in Events Manager for the Purchase event; low match quality signals missing or malformed `user_data` fields (check hashing/normalization per Section 4). 5. **End-to-end order test:** Complete a real (or test-mode) purchase of the Arc Clip Lamp end to end and verify the order appears as a Purchase event with the correct `content_ids` (matching the actual variant purchased) and no duplicate rows in Events Manager's raw event view. 6. **Cross-device/browser check:** Repeat the test in Safari (with ITP active) and with an ad blocker enabled to confirm the server-side event still arrives even when the Pixel is blocked. 7. Only after these checks are clean should you connect the pixel to an active campaign and begin optimizing spend toward Purchase. --- ## 7. Consent and Compliance Note Server-side tracking does not exempt Cedar & Coil from consent requirements. Both the Pixel and CAPI events described here should only fire for users who have provided any consent required in their jurisdiction (e.g., EU/UK/CA visitors) — use a consent management platform integrated with the Shopify Web Pixels/CAPI setup so that events are suppressed or adjusted (e.g., via Meta's Limited Data Use flag) when consent is declined. Do not send hashed PII fields for users who have opted out of tracking, and ensure the store's privacy policy accurately reflects that customer data is shared with Meta for advertising measurement purposes. This guide covers technical implementation only — final compliance language and consent-flow decisions should be reviewed against applicable law in each market Cedar & Coil ships to.
Score the judge's verdict, criterion by criterion10/11 criteria passed · failed: event_time_stable
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 explains 'Meta Pixel (browser JavaScript)... and a server-side integration... send the same events to Meta's Conversions API' and lists reasons like Safari ITP/ad blockers as why both are needed.
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓The table in Section 2 lists ViewContent, AddToCart, InitiateCheckout, and Purchase with value, currency, and content_ids explicitly required on Purchase.
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 Python code sketch in Section 5 includes event_name, event_time, event_id, action_source, and a user_data dict with hashed and plain fields.
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 instructs using 'Meta Events Manager → Test Events' and checking the 'Event Deduplication' column for matched browser/server pairs before scaling spend.
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 guide states events fire from both Pixel and CAPI ('Send these four standard events from both Pixel and CAPI') and specifies Purchase should be tied to the orders/paid webhook rather than only the thank-you page ('a Shopify webhook listener on orders/create and orders/paid').
limits_stated
Limitations are stated honestly: no promised attribution-recovery percentages, and consent/regional rules are noted as constraints on what may be sent.
✓Section 1 explicitly avoids promising a fixed percentage ('Do not treat this as a claim about a specific percentage of recovered conversions') and Section 7 notes consent/regional constraints on what may be 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 correctly explains that matching event_name and event_id across Pixel and CAPI lets Meta 'treat the pair as one event... rather than double-counting'.
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 design uses the immutable Shopify order ID as the event_id for Purchase ('event_id': str(order['id'])), which inherently stays constant across retries or order updates rather than being regenerated randomly.
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 code sketch sets 'event_time': int(time.time()), which captures the current send time rather than the order's actual occurrence timestamp, violating retry-stability requirements.
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 sha256_hash function specify trimming and lowercasing email/phone before SHA-256 hashing ('value.strip().lower()... hashlib.sha256').
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).
✓Section 5 gives a clear recommendation ('Use the native Meta sales channel app (Option A)') with concrete installation steps for a small DTC store.

Claude Opus 5 default

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." metadata: version: 2.0.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 --- ## 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$1.05 · 259.8s · 18.0k tok
Guide written and exported: **`cedar-coil-meta-tracking-implementation.md`** (7 labeled sections + rollout checklist). ## What's in it **1. Recommended architecture** — Pixel + CAPI into one dataset, joined by a shared `event_id`. The rationale is redundancy, not addition: the browser alone loses events to ad blockers, ITP/ETP, ATT, and network failures with no way to know how much; the server alone is blind to `fbp`/`fbc`, the strongest matching signals for ad-clicked traffic. Includes domain verification and AEM event prioritization (Purchase ranked first) as prerequisites. Framed as improving completeness and durability of signal — no recovery percentage claimed, and the guide notes explicitly that with no launched campaign, the first campaign's numbers *are* the baseline. **2. Standard events** — table of trigger + required/recommended params for all four, plus per-event `value` rules (unit price → line total → cart subtotal → order subtotal). Key calls: `value` is a number not a string; `currency` is required whenever `value` is present; `content_ids` must be Shopify **variant IDs** matching the catalog or you get zero matches; send `contents` *and* `content_ids` together; Purchase also carries `num_items` and `order_id`. Canonical JSON payload included. **3. Deduplication** — matched on `event_name` + `event_id` only, within roughly a 48-hour window. Emphasized that email, phone, `fbp`, and `fbc` do *not* participate in dedup — they're user matching. Recommends **deterministic IDs** (`purchase_<shopify_order_id>`) so browser and server never need to exchange anything, plus the four failure modes: random IDs on each side, case drift, double pixels (the native app + a hand-pasted snippet in `theme.liquid`), and retries that mint new IDs. **4. Customer information prep** — split into must-hash (`em`, `ph`, `fn`, `ln`, `ct`, `st`, `zp`, `country`, `external_id`) with exact normalization rules, and must-NOT-hash (`fbp`, `fbc`, `client_ip_address`, `client_user_agent`). The rules that break setups: normalize *before* hashing, hash server-side only, never hash an empty string, and capture IP/UA at the moment of user action rather than at webhook processing time. **5. Shopify setup path** — pros/cons tables for the native Meta sales channel vs. a custom Web Pixel extension + `orders/paid` webhook. **Recommendation: native app at Maximum data sharing** for a one-product, one-currency store with no campaign history — it delivers pixel + CAPI + dedup without an unmaintained pipeline. Named triggers for revisiting later (unexplained variance, a different `value` rule, non-standard order types, warehouse needs). A full commented Node.js serverless Purchase handler is included as reference — HMAC verification, consent gate, normalization/hashing helpers, deterministic `event_id`, retry-with-same-ID — plus the matching Web Pixel `checkout_completed` snippet. **6. Validation** — seven steps: Pixel Helper funnel walk, Test Events, a dedup confirmation (3 test orders must show 3 purchases, not 6), match quality/diagnostics, a Shopify-vs-Meta reconciliation table, refund edge cases, and a dated baseline snapshot. Flags that *more* Meta purchases than Shopify orders means a dedup or double-pixel bug that must be fixed before spend. **7. Consent and compliance** — the load-bearing point: CAPI is a resilience measure, not a consent bypass; no consent means neither path fires. Covers the Shopify Customer Privacy API, carrying consent forward as a checkout attribute so the webhook can honor it, GDPR/US state/LDU obligations, token handling, and logging discipline. Two things worth deciding before implementation, both flagged in the doc: your Purchase `value` rule (it recommends post-discount subtotal excluding shipping and tax, so Meta revenue is comparable to Shopify net sales) and your refund handling — Meta doesn't reverse them automatically.
Score the judge's verdict, criterion by criterion7/11 criteria passed · failed: code_sketch, sources_defined, event_time_stable, pii_hashing
RequirementVerdictEvidence
architecture
The guide recommends browser Pixel plus server-side Conversions API with deduplication and explains why both are needed under browser privacy limits.
✓The response explains Pixel + CAPI joined by shared event_id, noting the browser alone loses events to ad blockers/ITP/ATT while the server alone lacks fbp/fbc signals, framing it as redundancy for durability.
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓Section 2 describes a table of trigger + required params for all four events plus per-event value rules and explicit content_ids/currency requirements for Purchase.
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 response only references that 'a full commented Node.js serverless Purchase handler is included as reference' in the exported file but does not show any actual code in the text provided.
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 lists Test Events and a dedup confirmation step ('3 test orders must show 3 purchases, not 6') as part of end-to-end validation before scaling spend.
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).
✗Only Purchase's server source (orders/paid webhook) and browser source (Web Pixel checkout_completed) are clearly distinguished; ViewContent, AddToCart, and InitiateCheckout are not explicitly assigned browser vs server sources.
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 states 'no recovery percentage claimed' and that 'no consent means neither path fires,' tying consent and compliance to what may be 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.
✓It states dedup is 'matched on event_name + event_id only, within roughly a 48-hour window' and clarifies fbp/fbc/email do not participate in dedup, describing the mechanism correctly.
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.
✓Recommends 'deterministic IDs (purchase_<shopify_order_id>)' and explicitly includes 'retry-with-same-ID' in the described handler logic.
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 response never discusses event_time handling, Unix timestamps, or preserving the original purchase time across 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.
✗It lists fields to hash and normalization rules ('normalize before hashing, hash server-side only') but never explicitly states SHA-256 as the hashing algorithm.
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 gives a decisive recommendation: 'native app at Maximum data sharing for a one-product, one-currency store with no campaign history' with concrete rationale and revisit triggers.

Claude Haiku 4.5 default

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." metadata: version: 2.0.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 --- ## 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.038 · 57.5s · 6.7k tok
# Meta Conversions API Implementation Guide for Cedar & Coil ## 1. Recommended Architecture: Browser Pixel + Server-Side CAPI with Deduplication ### Why Both Are Needed **Meta Pixel (Browser-Side)** captures user interactions in real time and builds audience segments. However, it faces growing constraints: - Apple's App Tracking Transparency (ATT) blocks iOS cookie access - Safari's Intelligent Tracking Prevention (ITP) limits third-party cookie persistence - GDPR/CCPA consent modes may delay or block Pixel firing - Network errors and ad blockers can prevent event transmission **Conversions API (Server-Side)** sends events directly from your Shopify server to Meta's backend, bypassing browser limitations entirely: - No reliance on cookies or local storage - Works even if the Pixel never fired - Deterministic hashing of customer data (email, phone, address) enables matching in Meta's systems - Server-to-server communication is more reliable and auditable **Combined, they maximize conversion attribution:** - The Pixel catches immediate post-purchase signals and builds lookalike audiences from real-time user behavior - CAPI ensures the conversion is recorded even if the browser dropped the Pixel - Deduplication prevents double-counting the same purchase in Meta's reporting and campaign optimization --- ## 2. Standard Events to Send Send these four events in this order through both Pixel and CAPI: ### **ViewContent** Fired when a user lands on or scrolls into view of the Arc Clip Lamp product page. **Key Parameters:** - `content_name`: "Arc Clip Lamp" - `content_type`: "product" - `value`: 68 (the product price) - `currency`: "USD" - `content_ids`: ["[product_id_or_sku]"] (e.g., ["arc-clip-lamp-001"]) **Why:** Signals product interest to Meta's learning algorithm; used for catalog matching. --- ### **AddToCart** Fired when a user adds the Arc Clip Lamp to their cart. **Key Parameters:** - `content_name`: "Arc Clip Lamp" - `content_type`: "product" - `value`: 68 - `currency`: "USD" - `content_ids`: ["[product_id_or_sku]"] - `num_items`: 1 (or quantity if user added multiple) **Why:** High-intent signal; Meta uses this to optimize for users likely to complete purchase. --- ### **InitiateCheckout** Fired when a user lands on the checkout page (after clicking "Proceed to Checkout"). **Key Parameters:** - `content_name`: "Arc Clip Lamp" - `content_type`: "product" - `value`: 68 (subtotal, pre-tax/shipping) - `currency`: "USD" - `content_ids`: ["[product_id_or_sku]"] - `num_items`: 1 **Why:** Marks the point of maximum commitment; helps Meta identify users most likely to convert. --- ### **Purchase** Fired after order confirmation (ideally server-side on the Shopify webhook). **Key Parameters:** - `content_name`: "Arc Clip Lamp" (or comma-separated if multiple items, unlikely for Cedar & Coil) - `content_type`: "product" - `value`: [total order value, including tax and shipping] - `currency`: "USD" - `content_ids`: ["[product_id_or_sku]"] - `num_items`: 1 - `transaction_id`: "[unique order id]" (e.g., order number from Shopify) **Why:** The primary conversion event; server-side firing is critical to ensure Meta records the purchase even if the customer's browser blocked the Pixel. --- ## 3. How Deduplication Works Between Pixel and CAPI Meta deduplicates using a **request-level deduplication ID** built into both the Pixel and CAPI. ### Mechanism 1. **Browser Pixel fires:** Meta assigns the event an internal `event_id` and stores it temporarily in its event buffer. 2. **Server-side CAPI fires:** You include the same `event_id` in your CAPI request payload. 3. **Meta's backend checks:** Within a 24-hour window, if an incoming CAPI event has the same `event_id` as a recent Pixel event from the same user, Meta counts it only once in reporting and campaign optimization. ### Implementation **On the Pixel side** (automatic with meta-pixel.js): ```javascript fbq('track', 'Purchase', { value: 68.00, currency: 'USD', content_ids: ['arc-clip-lamp-001'], content_type: 'product' }, { eventID: 'order_12345_' + Math.random() // or generated server-side }); ``` **On the CAPI side** (in your server request): ```json { "data": [ { "event_name": "Purchase", "event_id": "order_12345_abc123def456", "event_time": 1692374400, "user_data": { ... }, "custom_data": { "value": 68.00, "currency": "USD", "content_ids": ["arc-clip-lamp-001"] } } ] } ``` ### Best Practice for Cedar & Coil - Generate the `event_id` server-side at the moment the Pixel is loaded (embed it in the HTML). - Pass the same `event_id` to the CAPI call in a subsequent webhook or delayed server event. - If you cannot reliably match them, allow Meta's system to deduplicate by email/phone hash (see section 4). --- ## 4. Customer Information Preparation (Server-Side) The Conversions API **must hash and normalize user identifiers** before sending to Meta. ### Required Field: `user_data` This object contains hashed customer PII used to match events to Meta user profiles: ```json { "user_data": { "em": ["hash_of_email_1", "hash_of_email_2"], "ph": ["hash_of_phone_1"], "fn": ["hash_of_first_name"], "ln": ["hash_of_last_name"], "ct": ["hash_of_city"], "st": ["hash_of_state"], "zp": ["hash_of_zip"], "country": ["hash_of_country_code"], "external_id": ["your_customer_id"] } } ``` ### Hashing Rules Meta requires **SHA-256 hashing** of these fields: 1. **Email (`em`):** - Lowercase the email - Strip leading/trailing whitespace - SHA-256 hash - Example: `sha256('john@example.com')` → `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` 2. **Phone (`ph`):** - Remove all non-numeric characters (spaces, dashes, `+`) - Lowercase - Keep country code (for US, starts with `1`) - SHA-256 hash - Example: `sha256('14155552671')` → (hashed value) 3. **Name, City, State, Zip, Country:** - Lowercase - Remove leading/trailing whitespace - SHA-256 hash 4. **External ID (`external_id`):** - Your own customer/account ID (not hashed; sent as-is) - Used to match repeat customers ### Shopify Data Mapping Extract from the Shopify order object: ```javascript const order = { // From Shopify webhook email: "customer@example.com", billing_address: { first_name: "John", last_name: "Doe", city: "San Francisco", province: "CA", zip: "94105", country: "US", phone: "+1 (415) 555-2671" }, customer: { id: 1234567890 } }; // Prepare user_data const userEmail = order.email.toLowerCase().trim(); const emHash = sha256(userEmail); const userPhone = (order.billing_address.phone || '') .replace(/\D/g, '') .toLowerCase(); const phHash = sha256(userPhone); const fnHash = sha256((order.billing_address.first_name || '').toLowerCase().trim()); const lnHash = sha256((order.billing_address.last_name || '').toLowerCase().trim()); const userData = { em: [emHash], ph: phHash ? [phHash] : [], fn: [fnHash], ln: [lnHash], ct: [sha256((order.billing_address.city || '').toLowerCase().trim())], st: [sha256((order.billing_address.province || '').toLowerCase().trim())], zp: [sha256((order.billing_address.zip || '').toLowerCase().trim())], country: [sha256((order.billing_address.country || '').toLowerCase().trim())], external_id: [order.customer.id.toString()] }; ``` ### PII Safety - **Never** send unhashed PII to Meta's API. - **Never** log hashed values in plain text; treat them as sensitive. - Use a server-side library (e.g., Node.js `crypto`, Python `hashlib`) to hash; do not hash in the browser. - If email or phone is missing, send the field as an empty array `[]`; do not omit it. --- ## 5. Concrete Shopify Setup Path ### Option A: Native Meta Sales Channel App (Built-in) **Pros:** - No code required; configure in Shopify Admin - Meta manages Pixel and CAPI automatically - Direct Shopify–Meta sync for inventory and product catalog **Cons:** - Limited customization of event parameters (e.g., cannot easily add custom properties) - Relies on Shopify's event mapping; you cannot control exact payload - Minimal support for complex deduplication logic **Recommended for:** Non-technical teams; simple, standard conversion tracking. **Setup Steps (via Shopify Admin):** 1. Admin → Apps and integrations → App and channel marketplace 2. Search "Meta for Shopify" or "Meta Sales Channel" 3. Install and authenticate with your Meta Business Account 4. Configure the Pixel ID and Catalog ID 5. Enable product sync and checkout tracking 6. Meta will auto-fire ViewContent, AddToCart, InitiateCheckout, Purchase --- ### Option B: Custom Implementation (Recommended for Cedar & Coil) **Pros:** - Full control over event parameters, deduplication logic, and CAPI payload - Ability to test and iterate on event quality - Better suited for small, performance-focused DTC brands **Cons:** - Requires developer resources (backend + frontend) - Must maintain tracking code across updates **Recommended for:** Small DTC stores with engineering support; Cedar & Coil's scale. **Setup Steps:** 1. **Install Meta Pixel on Store Front** - Add Meta Pixel ID to Shopify theme (via Theme Code Editor or using Shopify Script Editor): ```html <!-- In your theme's <head> --> <script> !function(f,b,e,v,n,t,s) {if(f.fbq)return;n=f.fbq=function(){n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments)}; if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0'; n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t,s)}(window, document,'script', 'https://connect.facebook.net/en_US/fbevents.js'); fbq('init', 'YOUR_PIXEL_ID'); fbq('track', 'PageView'); </script> <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=YOUR_PIXEL_ID&ev=PageView&noscript=1" /></noscript> ``` 2. **Add Product Page Tracking (Frontend)** ```javascript <script> document.addEventListener('DOMContentLoaded', function() { // Extract product info from page (Shopify theme variables or DOM) const productId = "{{ product.id }}"; const productName = "{{ product.title }}"; const productPrice = {{ product.price | money_without_currency | strip_html }}; fbq('track', 'ViewContent', { content_name: productName, content_type: 'product', content_ids: [productId], value: productPrice, currency: 'USD' }); }); </script> ``` 3. **Add to Cart Tracking (Frontend)** ```javascript <script> document.querySelector('[data-add-to-cart]').addEventListener('click', function() { fbq('track', 'AddToCart', { content_name: "{{ product.title }}", content_type: 'product', content_ids: ["{{ product.id }}"], value: {{ product.price | money_without_currency | strip_html }}, currency: 'USD', num_items: 1 }); }); </script> ``` 4. **Checkout Tracking (Frontend)** ```javascript <script> // On Shopify checkout page, fire InitiateCheckout fbq('track', 'InitiateCheckout', { content_type: 'product', num_items: 1, value: Shopify.checkout.subtotal_price, currency: 'USD' }); </script> ``` 5. **Server-Side Purchase Event (Backend)** - Set up a webhook listener in your Node.js/Python backend to receive Shopify `orders/create` webhooks. - On receipt, call the Meta Conversions API: ```javascript // Node.js example (express) const crypto = require('crypto'); const https = require('https'); function sha256(str) { return crypto.createHash('sha256').update(str).digest('hex'); } app.post('/shopify/webhook/order-create', async (req, res) => { const order = req.body; // Prepare user data const userData = { em: order.email ? [sha256(order.email.toLowerCase().trim())] : [], ph: order.billing_address?.phone ? [sha256(order.billing_address.phone.replace(/\D/g, '').toLowerCase())] : [], fn: order.billing_address?.first_name ? [sha256(order.billing_address.first_name.toLowerCase().trim())] : [], ln: order.billing_address?.last_name ? [sha256(order.billing_address.last_name.toLowerCase().trim())] : [], ct: order.billing_address?.city ? [sha256(order.billing_address.city.toLowerCase().trim())] : [], st: order.billing_address?.province ? [sha256(order.billing_address.province.toLowerCase().trim())] : [], zp: order.billing_address?.zip ? [sha256(order.billing_address.zip.toLowerCase().trim())] : [], country: order.billing_address?.country ? [sha256(order.billing_address.country.toLowerCase().trim())] : [], external_id: order.customer?.id ? [order.customer.id.toString()] : [] }; // Prepare CAPI payload const eventData = { data: [ { event_name: 'Purchase', event_id: `order_${order.id}_${Date.now()}`, event_time: Math.floor(new Date(order.created_at).getTime() / 1000), user_data: userData, custom_data: { value: parseFloat(order.total_price), currency: 'USD', content_ids: order.line_items.map(item => item.product_id.toString()), content_type: 'product', num_items: order.line_items.length, transaction_id: order.id.toString() }, user_agent: req.headers['user-agent'], client_ip_address: req.ip } ], test_event_code: process.env.META_TEST_EVENT_CODE // Optional: for testing }; // Call Meta Conversions API const metaUrl = new URL( `https://graph.facebook.com/v18.0/${process.env.META_PIXEL_ID}/events` ); metaUrl.searchParams.append('access_token', process.env.META_CAPI_TOKEN); const postData = JSON.stringify(eventData); const options = { hostname: 'graph.facebook.com', port: 443, path: metaUrl.pathname + metaUrl.search, method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; const request = https.request(options, (res) => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => { console.log('Meta CAPI Response:', data); }); }); request.on('error', (e) => console.error('CAPI Error:', e)); request.write(postData); request.end(); res.sendStatus(200); }); ``` 6. **Environment Variables (.env)** ``` META_PIXEL_ID=your_pixel_id META_CAPI_TOKEN=your_access_token META_TEST_EVENT_CODE=TEST_EVENT_CODE_IF_TESTING ``` --- ### Recommendation for Cedar & Coil **Use Option B (Custom Implementation)** for the following reasons: - Cedar & Coil is a small DTC brand with a single high-intent product (Arc Clip Lamp at $68). - Engineering support is available to implement and maintain CAPI. - Custom implementation allows you to validate event quality and optimize deduplication early. - The effort (2–3 developer days) pays off in reliable, auditable conversion tracking. - Start with the code sketch above; iterate based on validation (see section 6). --- ## 6. End-to-End Validation Before Scaling Spend ### Pre-Launch Checklist #### Browser-Side (Pixel) - [ ] Pixel is loaded on all pages (verify in Network tab or Facebook Pixel Helper extension) - [ ] ViewContent fires on product page; check in Meta Events Manager **Test Events** - [ ] AddToCart fires when item is added; verify value, currency, and content_ids are correct - [ ] InitiateCheckout fires on checkout page - [ ] Install [Facebook Pixel Helper](https://chrome.google.com/webstore/detail/facebook-pixel-helper/fdghodnadnanlhakjemijphpdkkemmda) and scan pages; should show all events with correct payload #### Server-Side (CAPI) - [ ] Meta Pixel ID and CAPI token are correctly set in environment - [ ] Shopify webhook is registered and receiving orders (test by placing a test order) - [ ] CAPI request is well-formed JSON and includes: - `event_name`, `event_time`, `event_id` - `user_data` with hashed email, phone, or external_id - `custom_data` with value, currency, content_ids, transaction_id - [ ] Log the full CAPI request and response for inspection - [ ] CAPI response code is 200 and no errors are returned #### Deduplication - [ ] Place a test purchase through the store - [ ] Verify the Pixel fires (EventID visible in Pixel Helper) - [ ] Check Meta Events Manager for the Pixel Purchase event (should appear within 1 minute) - [ ] Verify the CAPI Purchase event is also recorded (within a few seconds) - [ ] In Meta Events Manager, check that **only one Purchase event is counted** (not duplicated) - [ ] Inspect the deduplication ID (event_id) to confirm it matches between Pixel and CAPI #### Data Quality - [ ] Place 3–5 test orders with different payment methods and customer info - [ ] For each order: - Verify the value is correct (e.g., $68 for Arc Clip Lamp) - Verify currency is "USD" - Verify content_ids match the product - Verify transaction_id is unique - [ ] Check that no PII (plain email, phone, or address) appears in logs - [ ] Verify hashed user_data is consistent (same email should always hash to the same value) #### Cross-Browser & Device Testing - [ ] Test on Chrome, Safari, and Firefox desktop - [ ] Test on iOS and Android mobile browsers - [ ] Verify Pixel fires in all environments - [ ] Verify CAPI still records even if Pixel is blocked (e.g., in Safari with ITP enabled) ### Validation Tools & Dashboards | Tool | Use | |------|-----| | **Facebook Pixel Helper** (Chrome extension) | Real-time Pixel event inspection; check payload and timing | | **Meta Events Manager** | Verify events in Meta dashboard; check Test Events tab for real-time firing | | **Shopify Admin > Webhooks** | Confirm webhook endpoint is active and processing orders | | **Server Logs** | Print CAPI request/response to confirm transmission and HTTP 200 status | | **Meta Conversions API Test Events** | Send test events with `test_event_code` parameter for isolated testing | ### Test Event Flow (Safe for Staging) 1. In your CAPI call, include a `test_event_code`: ```json { "data": [ { ... } ], "test_event_code": "TEST_abc123" } ``` 2. In Meta Business Suite, go to **Events Manager** > **Your Pixel** > **Test Events**. 3. Enter the Test Event Code above. 4. Send a test order; it should appear in **Test Events** within seconds (isolated from live conversions). 5. Once validated, remove the `test_event_code` for production. ### Go/No-Go Decision **Before spending on ads, confirm:** - ✅ 100% of test purchases are recorded in Meta (both Pixel and CAPI visible in Events Manager) - ✅ No duplicate Purchase events in reporting - ✅ Value, currency, and content_ids are accurate - ✅ CAPI works even if Pixel does not fire (test by disabling Pixel temporarily) - ✅ Events arrive within 2–5 seconds for Pixel, 30 seconds for CAPI **If any check fails,** debug that step before scaling. --- ## 7. Consent and Compliance Note ### Data Privacy - **Hashing and PII:** The Conversions API requires hashing of PII (email, phone, address) using SHA-256. Hashing is a one-way function; Meta cannot recover the original data. However, hashing remains PII in regulatory terms (it is identifiable if combined with other sources). - **User Consent:** In jurisdictions requiring consent (EU GDPR, UK PECR, Canada PIPEDA, California CCPA), you must obtain explicit opt-in from users before sending their data to Meta via the Pixel or CAPI. Implement a consent management platform (CMP) such as OneTrust, TrustArc, or Termly to: - Display a banner at first visit - Obtain consent for "Marketing" or "Advertising" purposes - Store consent state locally - Only fire Pixel/CAPI if consent is granted - **Server-Side Considerations:** CAPI sends data server-to-server (not from the user's browser). You may be able to send CAPI events even if the Pixel does not fire, depending on your consent design. Document your approach and confirm alignment with your legal/privacy team. - **Data Retention:** Meta stores converted customer data for up to 3 months for retargeting. Users can request deletion of their data under GDPR. Ensure your privacy policy discloses data sharing with Meta. - **Ad Targeting Restrictions:** Do not use sensitive categories (health, religion, political affiliation) in audience targeting. Meta's advertising policies prohibit discrimination. Cedar & Coil's product (task lighting) poses no elevated risk, but document this in your compliance checklist. ### Do Not Promise Attribution Recovery Percentages Avoid claims such as "This setup will recover X% of lost iOS conversions" or "CAPI will increase conversion attribution by Y%." The recovery depends on: - Match rate (what % of customers can Meta identify by hashed email/phone) - Customer data quality (incomplete or incorrect email/address reduces match) - Meta's attribution window (standard 28-day click, 1-day view) - Offline conversion upload (if applicable) **Instead, frame it as:** "This dual-channel approach (Pixel + CAPI) provides redundancy and allows Meta's matching algorithms to record conversions that browser privacy constraints might otherwise miss. Measurement accuracy will improve over time as match rates stabilize." ### Documentation Checklist - [ ] Privacy policy discloses Meta data sharing - [ ] Consent banner and CMP are in place (if required by jurisdiction) - [ ] Hashing is performed server-side only; no plain PII is logged - [ ] CAPI token and Pixel ID are stored securely (not in frontend code) - [ ] Shopify webhook endpoint is HTTPS and authenticated - [ ] Data deletion requests from users are forwarded to Meta - [ ] Conversions API documentation is kept up to date with Meta's API versioning (currently v18.0; check [developers.facebook.com](https://developers.facebook.com) for updates) --- ## Summary This guide provides Cedar & Coil with a complete, resilient setup for tracking Arc Clip Lamp conversions through Meta's Pixel and Conversions API. The dual-channel approach (browser + server-side) with deduplication ensures reliable measurement even as browser privacy constraints tighten. Custom implementation (Option B) gives you control over data quality and allows early iteration before scaling ad spend. Validate end-to-end with test orders and the Facebook Pixel Helper before increasing spend, and ensure consent and privacy compliance are in place from the start.
Score the judge's verdict, criterion by criterion9/11 criteria passed · failed: code_sketch, event_id_retry_stability
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 explicitly recommends Pixel + CAPI with deduplication and explains browser privacy limits (ATT, ITP, consent) that necessitate both.
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓Section 2 covers ViewContent, AddToCart, InitiateCheckout, and Purchase, each with value, currency, and content_ids, plus Purchase includes transaction_id.
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 server-side Purchase JSON/code sketches include event_name, event_id, event_time, and user_data but never include an 'action_source' field anywhere in the payload.
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 details using Meta Events Manager Test Events and explicitly checks 'only one Purchase event is counted (not duplicated)' and that event_id matches between Pixel and CAPI.
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).
✓ViewContent/AddToCart/InitiateCheckout are shown firing client-side via fbq in the theme, while Purchase is explicitly fired 'ideally server-side on the Shopify webhook' as the source of truth.
limits_stated
Limitations are stated honestly: no promised attribution-recovery percentages, and consent/regional rules are noted as constraints on what may be sent.
✓Section 7 has a dedicated subsection 'Do Not Promise Attribution Recovery Percentages' and discusses GDPR/CCPA consent requirements as constraints on sending data.
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 explains that the same event_id is included in both the Pixel and CAPI requests so Meta counts the event only once within a 24-hour window.
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 CAPI code sketch generates event_id as `order_${order.id}_${Date.now()}`, which changes value on every webhook retry rather than being fixed per commerce event.
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 Purchase event_time is computed as `Math.floor(new Date(order.created_at).getTime() / 1000)`, using the order's creation timestamp rather than the current 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 shows email being lowercased and trimmed before SHA-256 hashing (`sha256(userEmail)`), consistent with Meta's required normalization.
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).
✓The guide explicitly recommends 'Option B (Custom Implementation)' for Cedar & Coil with concrete numbered setup steps and code, rather than leaving the choice undifferentiated.