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

Answers & verdicts

GPT-5.6 Luna medium effort

Task failed
Task the exact prompt the model was given — assignment, source material, and skill guidance
Cedar & Coil sells the Arc Clip Lamp on Shopify and is preparing Meta ads. Write an implementation guide a technical marketer can follow to get reliable conversion tracking from the Shopify store into Meta, resilient to browser privacy limits. Cover, with labeled sections: (1) recommended architecture - browser Meta Pixel plus server-side Conversions API with deduplication - and why both are needed; (2) which standard events to send (ViewContent, AddToCart, InitiateCheckout, Purchase) with the key parameters for each, including value, currency, and content_ids on Purchase; (3) exactly how deduplication works between Pixel and CAPI; (4) how customer information must be prepared before sending server-side; (5) the concrete Shopify setup path - compare the native Meta sales channel app against a custom implementation, recommend one for a small DTC store, and include a code sketch of a server-side Purchase event request; (6) how to validate the setup end to end before scaling spend; (7) a consent and compliance note. Do not promise specific attribution recovery percentages. --- ## Supplied source: product-marketing.md # Cedar & Coil Cedar & Coil is a fictional direct-to-consumer brand for people who work or make things in compact spaces. Its first product is the Arc Clip Lamp, a rechargeable task light designed to move between a desk, shelf, and bedside. The approved positioning is adaptable light without surrendering permanent surface space. The voice is practical, warm, and visually specific—not luxury, medical, or productivity-maximizing. All campaign work must remain draft-only. Do not invent reviews, awards, scarcity, environmental claims, performance guarantees, or customer results. --- ## Supplied source: facts.md # Authoritative synthetic facts - Product: Arc Clip Lamp. - Price: $68. - Included: lamp, padded clamp, USB-C charging cable, and storage sleeve. - Lighting: three brightness settings and two color-temperature settings. - Battery statement allowed: up to eight hours on the lowest brightness. - Clamp opening: surfaces up to 2.25 inches thick. - Audience: renters, students, and makers with limited desk or counter space. - Approved CTA: Explore the Arc Clip Lamp. - No campaign has launched and no performance data exists. --- ## Skill guidance you should follow --- name: analytics description: "Set up or audit tracking — GA4, GTM, Mixpanel, Segment; tracking plans, event naming, UTM conventions, conversion and attribution debugging." 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.006 · 46.2s · 4.6k tok
# Cedar & Coil Shopify → Meta Conversion Tracking Implementation Guide ## 1. Recommended architecture Use both: 1. **Browser-side Meta Pixel** 2. **Server-side Meta Conversions API (CAPI)** ### Recommended flow ```text Shopify storefront ├─ Meta Pixel: browser events │ ├─ ViewContent │ ├─ AddToCart │ ├─ InitiateCheckout │ └─ Purchase │ └─ Shopify/server integration: CAPI events ├─ Purchase └─ optionally the earlier funnel events Meta receives both copies and deduplicates them using: event_name + event_id + pixel/dataset ``` ### Why use both? The Pixel supplies browser context such as: - Page URL and referrer - Browser and device information - Meta cookies such as `_fbp` - Click identifier `_fbc`, when available - Immediate event delivery from storefront interactions CAPI supplies a server-side signal that is less dependent on: - Browser cookie restrictions - Ad blockers - Intelligent Tracking Prevention - JavaScript failures - Checkout or thank-you-page navigation issues Neither method is complete by itself. Pixel data generally has stronger browser context, while CAPI is useful for reliable server-confirmed actions such as completed orders. CAPI does not bypass consent requirements or guarantee that Meta can attribute every conversion. ### Recommended event ownership For a small DTC store: - Send the funnel events through the native Shopify/Meta integration where possible. - Treat the Shopify order record or paid-order webhook as the authoritative source for `Purchase`. - Do not install multiple independent Pixel or CAPI implementations. That is a common cause of duplicate conversions. --- ## 2. Standard events and required parameters Use Meta’s standard event names exactly as shown. Values should come from Shopify’s actual product and checkout data rather than hard-coded marketing copy. For the Arc Clip Lamp, the approved product price is **$68**. If the Shopify store’s transaction currency is USD, send `currency: "USD"` and the applicable checkout value. ### Event plan | Meta event | Trigger | Important parameters | |---|---|---| | `ViewContent` | Product detail page viewed | `content_ids`, `content_type`, `content_name`, `value`, `currency` | | `AddToCart` | Product successfully added to cart | `content_ids`, `contents`, `content_type`, `value`, `currency` | | `InitiateCheckout` | Checkout begins | `content_ids`, `contents`, `num_items`, `value`, `currency` | | `Purchase` | Payment/order is confirmed | `content_ids`, `contents`, `num_items`, `value`, `currency`, order identifier | ### `ViewContent` Send when the Arc Clip Lamp product page is viewed. ```javascript fbq('track', 'ViewContent', { content_ids: ['shopify-product-or-variant-id'], content_type: 'product', content_name: 'Arc Clip Lamp', value: 68.00, currency: 'USD' }, { eventID: 'unique-view-event-id' }); ``` Recommendations: - Prefer the Shopify product or variant ID used consistently in the catalog and event payloads. - If variants exist, use the selected variant ID. - Do not fire this event repeatedly for every minor page interaction. ### `AddToCart` Send only after Shopify confirms that the item was added successfully. ```javascript fbq('track', 'AddToCart', { content_ids: ['shopify-variant-id'], contents: [{ id: 'shopify-variant-id', quantity: 1, item_price: 68.00 }], content_type: 'product', value: 68.00, currency: 'USD' }, { eventID: 'unique-add-to-cart-event-id' }); ``` For multiple items, calculate: ```text value = sum(item_price × quantity) ``` ### `InitiateCheckout` Send when the customer actually enters or starts Shopify checkout, not merely when the cart drawer opens. ```javascript fbq('track', 'InitiateCheckout', { content_ids: ['shopify-variant-id'], contents: [{ id: 'shopify-variant-id', quantity: 1, item_price: 68.00 }], content_type: 'product', num_items: 1, value: 68.00, currency: 'USD' }, { eventID: 'unique-checkout-event-id' }); ``` Use the actual checkout subtotal or total consistently. Document whether `value` includes discounts, shipping, and tax, and use the same convention for browser and server events. ### `Purchase` Send after a successful, paid order. ```javascript fbq('track', 'Purchase', { content_ids: ['shopify-variant-id'], contents: [{ id: 'shopify-variant-id', quantity: 1, item_price: 68.00 }], content_type: 'product', num_items: 1, value: 68.00, currency: 'USD', order_id: 'shopify-order-id' }, { eventID: 'purchase-event-id' }); ``` For `Purchase`, ensure that: - `value` is the actual order value selected by your measurement policy. - `currency` is the three-letter ISO currency code. - `content_ids` contains the purchased product or variant IDs. - `contents` reflects every purchased line item. - The event fires once per order, not once per page refresh. Refunds and cancellations should not be represented as additional purchases. Handle them in reporting or with a separate operational data process. --- ## 3. Exactly how Pixel and CAPI deduplication works Deduplication requires that the browser and server versions of the same event use: 1. The same Meta Pixel/dataset 2. The same standard `event_name` 3. The same `event_id` Example: ```text Browser: event_name = Purchase event_id = purchase_100045 Server: event_name = Purchase event_id = purchase_100045 ``` Meta can then recognize them as two transmissions of one conversion rather than two purchases. ### Correct implementation sequence 1. Generate one unique ID for the event. 2. Pass that ID to the browser Pixel. 3. Store or transmit that same ID to the server. 4. Send the server event with the same event name and ID. 5. Do not generate a second random ID server-side for the same conversion. For a purchase, a Shopify order-based ID can work if it is unique and stable, for example: ```text purchase_shopify_100045 ``` However, the same order ID must be used by both the browser and server implementations. If a browser Purchase event is not reliably available, the server may send the purchase independently, but there will be no browser event to deduplicate against. ### Important distinctions - `event_id` is the deduplication identifier. - `event_id` is not the same as `event_name`. - `fbp` and `fbc` help event matching but do not replace `event_id`. - Sending the same purchase twice with different event IDs will generally look like two separate events. - Installing Shopify’s native integration and a custom Pixel/CAPI implementation at the same time can create duplicates. --- ## 4. Preparing customer information for server-side events CAPI `user_data` should be prepared carefully before transmission. ### Normalize before hashing For fields that Meta expects to be hashed: 1. Trim leading and trailing whitespace. 2. Convert text to lowercase. 3. Normalize phone numbers to international format, including country code. 4. Remove unnecessary punctuation and formatting. 5. Apply SHA-256 hashing. 6. Send the resulting hexadecimal hash. Example normalization: ```text Email: " Customer@Example.com " → "customer@example.com" → SHA-256 Phone: "(555) 123-4567" → "+15551234567" → SHA-256 ``` Common hashable fields include: - `em`: email - `ph`: phone - `fn`: first name - `ln`: last name - `ct`: city - `st`: state or region - `zp`: postal code - `country` - `external_id` Do not hash fields that Meta expects in their original form, including: - `client_ip_address` - `client_user_agent` - `fbp` - `fbc` Do not send raw email addresses, phone numbers, or names in event parameters. Keep the access token and all server-side credentials off the browser. ### Example server `user_data` ```json { "em": ["sha256-email"], "ph": ["sha256-phone"], "fn": ["sha256-first-name"], "ln": ["sha256-last-name"], "ct": ["sha256-city"], "st": ["sha256-region"], "zp": ["sha256-postal-code"], "country": ["sha256-country"], "fbp": "fb.1.1700000000000.123456789", "fbc": "fb.1.1700000000000.IwAR-example", "client_ip_address": "203.0.113.10", "client_user_agent": "Mozilla/5.0 ..." } ``` Use only information collected lawfully and permitted for the stated marketing purpose. If a field is unavailable or the person has not consented to its use, omit it. --- ## 5. Concrete Shopify setup path ### Option A: Native Shopify Meta sales channel For a small DTC store, this is the recommended starting point. Typical path: 1. In Shopify Admin, open **Settings → Customer events** and review existing pixels and web pixels. 2. Open **Sales channels → Facebook & Instagram by Meta**. 3. Connect the relevant Meta Business Portfolio, ad account, Page, and Pixel/dataset. 4. Choose the appropriate data-sharing level available in the Shopify integration. 5. Confirm that the correct Shopify catalog is connected. 6. Remove or disable any manually installed duplicate Pixel code in: - Theme files - Google Tag Manager - Additional scripts - Custom checkout or thank-you-page scripts 7. Configure consent behavior through Shopify’s privacy settings and consent-management solution. 8. Place a test order and validate the resulting Pixel and CAPI events in Meta Events Manager. #### Advantages - Faster to deploy - Uses Shopify’s supported checkout and customer-event integrations - Less custom code to maintain - Better fit for Shopify checkout restrictions and platform updates - Usually handles standard ecommerce event mapping and server-side order signals #### Limitations - Less control over custom event payloads and event timing - Debugging may require checking both Shopify and Meta - Advanced event IDs, order-state logic, and custom data may require additional development - The exact options vary by Shopify plan and current Meta/Shopify integration capabilities For Cedar & Coil’s Arc Clip Lamp store, use the native integration unless there is a specific requirement it cannot satisfy. ### Option B: Custom implementation Use a custom implementation only when you need control such as: - A custom data layer - A separate server-side event gateway - Complex catalog or variant mapping - Custom consent orchestration - Order-state and refund workflows - A need to integrate multiple ad platforms from one event pipeline A custom setup typically includes: 1. A Shopify Web Pixel or approved storefront integration for browser events. 2. A backend service that receives Shopify order webhooks or checkout events. 3. A persistent event ID strategy. 4. An idempotency store to prevent repeated webhook deliveries from creating repeated purchases. 5. Secure storage for the Meta access token. 6. Monitoring for failed requests and retries. Do not send CAPI requests directly from browser JavaScript because that would expose the access token. ### Server-side Purchase request code sketch The following is illustrative Node.js-style code. Use the current Graph API version in production and confirm the endpoint and required fields against Meta’s current documentation. ```javascript import crypto from 'node:crypto'; const PIXEL_ID = process.env.META_PIXEL_ID; const ACCESS_TOKEN = process.env.META_CAPI_ACCESS_TOKEN; const API_VERSION = 'vXX.X'; // Set to Meta's supported version. function sha256(value) { return crypto .createHash('sha256') .update(value) .digest('hex'); } function normalize(value) { return String(value ?? '').trim().toLowerCase(); } function hashIfPresent(value) { const normalized = normalize(value); return normalized ? sha256(normalized) : undefined; } export async function sendPurchaseToMeta(order) { // This must be stable across webhook retries and match the browser event ID. const eventId = `purchase_shopify_${order.id}`; const userData = { em: order.email ? [hashIfPresent(order.email)] : undefined, ph: order.phone ? [hashIfPresent(order.phone)] : undefined, fbp: order.fbp || undefined, fbc: order.fbc || undefined, client_ip_address: order.clientIp || undefined, client_user_agent: order.userAgent || undefined }; // Remove undefined fields. Object.keys(userData).forEach((key) => { if (userData[key] === undefined) delete userData[key]; }); const event = { event_name: 'Purchase', event_time: Math.floor(Date.now() / 1000), event_id: eventId, action_source: 'website', event_source_url: order.checkoutUrl || 'https://cedarandcoil.example/', user_data: userData, custom_data: { value: Number(order.totalPrice), currency: order.currency, // e.g. "USD" content_type: 'product', content_ids: order.lineItems.map(item => String(item.variantId)), contents: order.lineItems.map(item => ({ id: String(item.variantId), quantity: Number(item.quantity), item_price: Number(item.price) })), num_items: order.lineItems.reduce( (sum, item) => sum + Number(item.quantity), 0 ), order_id: String(order.id) } }; const response = await fetch( `https://graph.facebook.com/${API_VERSION}/${PIXEL_ID}/events?access_token=${ACCESS_TOKEN}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data: [event] }) } ); const result = await response.json(); if (!response.ok) { throw new Error(`Meta CAPI error: ${JSON.stringify(result)}`); } return result; } ``` Production requirements: - Use the Shopify order’s actual paid/confirmed status. - Use an idempotency table keyed by `event_id`. - Mark an event as sent only after a successful Meta response. - Safely retry transient failures without creating a new `event_id`. - Keep access tokens in server-side secrets management. - Ensure the server event uses the same value, currency, content IDs, and event ID as the browser event. --- ## 6. End-to-end validation before scaling spend Run validation in a test environment or with a low-risk test order before launching campaigns. ### A. Validate the storefront For each event: - Open the Arc Clip Lamp product page. - Confirm one `ViewContent` event. - Add one lamp to cart. - Confirm one `AddToCart` event. - Start checkout. - Confirm one `InitiateCheckout` event. - Complete a test purchase. - Confirm one `Purchase` event. Use browser developer tools to inspect: - `fbevents.js` activity - Pixel requests - Event name - Event ID - Value - Currency - Content IDs ### B. Validate Meta Events Manager In **Events Manager**: 1. Select the correct Pixel/dataset. 2. Open **Test Events**. 3. Perform the storefront actions in a test browser session. 4. Confirm browser and server events arrive. 5. For the purchase, verify that Meta reports the browser and server transmissions as one deduplicated event rather than two purchases. 6. Review Diagnostics and Event Match Quality warnings. If using CAPI’s `test_event_code`, include it only for testing and remove it from production requests. ### C. Validate payload consistency For the same event, compare browser and server payloads: | Field | Browser and server should agree | |---|---| | `event_name` | Yes | | `event_id` | Yes | | `value` | Yes | | `currency` | Yes | | `content_ids` | Yes | | `order_id` for Purchase | Yes | | Event occurrence | One real action/order | ### D. Test edge cases At minimum, test: - Desktop browser - Mobile browser - Safari or another privacy-restrictive browser - Ad blocker enabled - Customer declines marketing cookies - Failed payment - Refreshing the thank-you page - Reloading or revisiting an order confirmation page - Shopify webhook retry - Multiple quantities or multiple line items - Discounted order - Different supported currencies, if applicable Expected outcomes: - A failed payment does not create `Purchase`. - Refreshing the confirmation page does not create another purchase. - A retried webhook reuses the same event ID and does not create another conversion. - Consent-denied sessions do not send unauthorized marketing events. - Product and order values match Shopify. ### E. Monitor after launch For the first several days, monitor: - Event volumes by event type - Browser/server event overlap - Purchase count against Shopify orders - Revenue and currency values - Duplicate-event diagnostics - Missing or malformed `content_ids` - CAPI request errors and retry rates - Changes after Shopify theme, checkout, or app updates Use Shopify’s order data as the operational source of truth for actual sales. Meta reporting is an advertising measurement view and may differ because of consent, identity matching, attribution settings, reporting delays, and platform modeling. --- ## 7. Consent and compliance note Before sending Meta Pixel or CAPI data, Cedar & Coil should determine its applicable privacy requirements and configure consent accordingly. Requirements can vary by location, including the EU, UK, California, Canada, and other jurisdictions. Implementation principles: - Load or activate marketing tracking only after the required consent. - Honor consent withdrawal and browser privacy signals where applicable. - Do not send hashed customer information to Meta when the underlying collection or marketing use is not permitted. - Do not treat hashing as anonymization; hashed email and phone numbers remain personal-data-derived identifiers. - Publish or update the privacy notice to describe Meta Pixel, CAPI, purposes, data categories, and opt-out choices. - Restrict access to Meta access tokens and customer data. - Provide deletion and data-access processes where required. - Retain only the data and event history necessary for the stated purposes. - Confirm data-processing terms and settings with Shopify and Meta. CAPI should make tracking more resilient to technical signal loss, not serve as a way to bypass consent, ad blockers, or user privacy choices.
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.
✓The guide explicitly recommends Pixel plus CAPI, explains Pixel gives browser context while CAPI is 'less dependent on browser cookie restrictions, ad blockers, ITP, JavaScript failures' and states 'Neither method is complete by itself.'
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓All four events (ViewContent, AddToCart, InitiateCheckout, Purchase) are given code examples with value, currency, and content_ids, with Purchase also including order_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 Node.js sendPurchaseToMeta function includes event_name: 'Purchase', event_time, event_id, action_source: 'website', and a user_data object.
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 instructs using Meta's Test Events in Events Manager and to 'verify that Meta reports the browser and server transmissions as one deduplicated 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 guide states to 'Treat the Shopify order record or paid-order webhook as the authoritative source for Purchase' and distinguishes browser vs server firing throughout sections 2, 3, and 5.
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 percentage is promised, and the compliance note states requirements vary by jurisdiction and that CAPI should not 'bypass consent, ad blockers, or user privacy choices.'
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 explicitly states deduplication requires same pixel/dataset, same event_name, and same event_id so 'Meta can then recognize them as two transmissions of one conversion rather than two purchases.'
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 code comment states 'This must be stable across webhook retries and match the browser event ID' and uses a deterministic ID derived from the Shopify order id (`purchase_shopify_${order.id}`).
event_time_stable
The server Purchase event uses the purchase/order occurrence timestamp in Unix seconds and preserves it across retries; using the current send or retry time fails.
✗The code sketch sets `event_time: Math.floor(Date.now() / 1000)`, using the current send time rather than the actual order/purchase occurrence timestamp, which violates the retry-stability requirement.
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, lowercasing, and SHA-256 hashing of email/phone before inclusion in user_data, with an explicit normalization example.
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, numbered setup path via Shopify's native Meta sales channel and explicitly recommends it for Cedar & Coil's store: 'use the native integration unless there is a specific requirement it cannot satisfy.'

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.096 · 80.2s · 7.6k tok
# Cedar & Coil: Shopify → Meta Conversion Tracking Implementation Guide ## Goal Implement reliable Meta conversion tracking for the Arc Clip Lamp store using: - **Browser-side Meta Pixel** for on-site behavior and ad-click context. - **Server-side Meta Conversions API (CAPI)** for resilient event delivery when browser tracking is limited. - **Event deduplication** so Meta counts each action once rather than once from the browser and again from the server. Primary paid-social funnel events: 1. `ViewContent` 2. `AddToCart` 3. `InitiateCheckout` 4. `Purchase` Use the data to evaluate Meta campaigns, optimize toward purchases, build retargeting audiences where consent permits, and diagnose funnel drop-off. --- # 1. Recommended Architecture: Meta Pixel + Conversions API ## Recommended setup ```text Meta ad click ↓ Shopify storefront ├─ Browser Meta Pixel │ ├─ ViewContent │ ├─ AddToCart │ ├─ InitiateCheckout │ └─ Purchase │ └─ Server-side Conversions API ├─ ViewContent / AddToCart / InitiateCheckout where feasible └─ Purchase from the confirmed Shopify order record ``` For a small DTC Shopify store, the preferred implementation is normally: > **Shopify’s Facebook & Instagram by Meta sales channel app, configured for Maximum data sharing**, rather than a fully custom browser Pixel and CAPI implementation. The native integration is the quickest route to a supported Pixel + CAPI configuration. A custom implementation is appropriate only when Cedar & Coil needs event logic, identity handling, order enrichment, consent orchestration, or cross-platform routing that the native integration cannot support. ## Why send events from both browser and server? ### Browser Pixel strengths The Meta Pixel runs in the customer’s browser and can capture: - Page and product interactions as they happen. - Page URL and referrer. - Meta browser identifiers, including `_fbp`. - Ad-click identifiers such as `fbclid`, often represented server-side as `_fbc`. - On-site events before an order exists, such as product views and cart additions. Browser events are especially useful for top- and mid-funnel activity. ### Browser Pixel limitations Browser tracking can be reduced or blocked by: - Ad blockers and tracking protection. - Safari Intelligent Tracking Prevention and similar browser privacy controls. - Cookie deletion or cookie restrictions. - Script loading failures. - Customers declining marketing cookies. - Network-level tracking prevention. ### Conversions API strengths CAPI sends events from Cedar & Coil’s server or a trusted platform integration to Meta’s server. It is more durable for events based on Shopify records, especially `Purchase`. Server-side events can include privacy-safe matching information, when consent permits, such as hashed email or phone number. This can improve Meta’s ability to match an event to a Meta account, but it does not override consent requirements or make tracking immune to every measurement limitation. ### Why the hybrid approach is best Use both sources because each carries information the other may miss: | Source | Best use | Main limitation | |---|---|---| | Browser Meta Pixel | On-site behavior, landing-page context, browser/ad-click identifiers | Can be blocked or restricted | | Server-side CAPI | Confirmed orders, resilient delivery, customer match data | May lack browser context unless identifiers are passed through | The server-side event is **not** a license to bypass a customer’s consent choice. If a customer has not consented to marketing tracking where consent is required, do not send marketing measurement data through Pixel or CAPI unless your legal basis and consent configuration explicitly permit it. --- # 2. Standard Event Plan and Required Parameters Use Meta standard event names exactly: - `ViewContent` - `AddToCart` - `InitiateCheckout` - `Purchase` For product events, ensure the `content_ids` value matches the product ID used in the connected Meta catalog. This is essential if Cedar & Coil later uses catalog sales campaigns or dynamic ads. ## Event tracking plan | Meta event | Trigger | Primary purpose | |---|---|---| | `ViewContent` | Customer views the Arc Clip Lamp product page | Product interest and retargeting | | `AddToCart` | Customer adds the lamp to cart | High-intent audience and funnel optimization | | `InitiateCheckout` | Customer starts Shopify checkout | Checkout-funnel measurement | | `Purchase` | A Shopify order is successfully paid/confirmed | Revenue measurement and campaign optimization | ## Common parameters Send these consistently whenever applicable: | Parameter | Format | Notes | |---|---|---| | `event_name` | Meta standard event name | Example: `Purchase` | | `event_time` | Unix timestamp in seconds | Event occurrence time, not retry time | | `event_id` | Stable unique string | Required for browser/server deduplication | | `action_source` | `website` | Required for web events | | `event_source_url` | Full page URL | Useful for browser and website CAPI events | | `value` | Number | Use actual transaction/product value, not a formatted string | | `currency` | ISO currency code | Example: `USD` | | `content_ids` | Array of strings | Must align with Meta catalog item IDs | | `content_type` | Usually `product` | Use consistently | | `contents` | Array of item objects | Include item ID, quantity, and item price where supported | Do not hard-code the Arc Clip Lamp’s $68 list price into events. Send the actual product/cart/order amount at the time of the event, including any applicable discount logic. For `Purchase`, use the actual completed-order value according to Cedar & Coil’s selected convention. Choose and document one Purchase value convention: - **Recommended:** product subtotal after discounts, excluding shipping and tax; or - Total paid including tax and shipping. Either can work, but the implementation must use the same convention consistently across browser events, CAPI events, Shopify reporting, and campaign analysis. ## `ViewContent` **Trigger:** The Arc Clip Lamp product-detail page loads and the product data is available. **Recommended parameters:** ```javascript fbq('track', 'ViewContent', { content_ids: ['arc-clip-lamp'], content_type: 'product', contents: [ { id: 'arc-clip-lamp', quantity: 1, item_price: 68.00 } ], value: 68.00, currency: 'USD' }, { eventID: 'vc_<unique-id>' }); ``` **Key requirements:** - `content_ids`: `['arc-clip-lamp']`, or the exact catalog ID selected by the Shopify/Meta catalog connection. - `value`: Current displayed product price. - `currency`: `USD`. - Include variant-level IDs if the catalog uses variant IDs rather than product handles. ## `AddToCart` **Trigger:** The cart add action succeeds, not merely when the customer clicks the button. **Recommended parameters:** ```javascript fbq('track', 'AddToCart', { content_ids: ['arc-clip-lamp'], content_type: 'product', contents: [ { id: 'arc-clip-lamp', quantity: 1, item_price: 68.00 } ], value: 68.00, currency: 'USD' }, { eventID: 'atc_<unique-id>' }); ``` **Key requirements:** - Use the quantity actually added. - Use the price actually added to cart, including the relevant discount logic. - Avoid firing twice because of theme JavaScript, AJAX cart behavior, or both a button-click and cart-update trigger. ## `InitiateCheckout` **Trigger:** The customer begins Shopify checkout successfully. **Recommended parameters:** ```javascript fbq('track', 'InitiateCheckout', { content_ids: ['arc-clip-lamp'], content_type: 'product', contents: [ { id: 'arc-clip-lamp', quantity: 1, item_price: 68.00 } ], num_items: 1, value: 68.00, currency: 'USD' }, { eventID: 'ic_<unique-id>' }); ``` **Key requirements:** - Send all cart line items, not only the first item, if the cart can contain multiple products. - `num_items` should represent total item quantity in the checkout. - `value` should reflect the checkout value under Cedar & Coil’s documented valuation convention. ## `Purchase` **Trigger:** A Shopify order is confirmed as paid/successful. For a custom CAPI implementation, use a trusted order/payment status from Shopify—not a thank-you-page visit alone. **Recommended parameters:** ```javascript fbq('track', 'Purchase', { content_ids: ['arc-clip-lamp'], content_type: 'product', contents: [ { id: 'arc-clip-lamp', quantity: 1, item_price: 68.00 } ], num_items: 1, value: 68.00, currency: 'USD' }, { eventID: 'purchase_<stable-order-id>' }); ``` **Purchase requirements:** - `value`: Actual completed order value. - `currency`: `USD`. - `content_ids`: Required for catalog alignment; include all purchased item IDs. - `contents`: Include each line item, quantity, and item-level price. - `event_id`: Must be stable for the order. A retry must use the same ID. - Send one Purchase event per completed order, not one per payment attempt. - Do not use a browser thank-you page alone as the authoritative order record; customers may close the page, revisit it, or have scripts blocked. --- # 3. Exactly How Pixel/CAPI Deduplication Works ## The rule Meta deduplicates a browser Pixel event and a server-side CAPI event when both have: 1. The same **Pixel ID**. 2. The same `event_name`. 3. The same `event_id`. 4. Closely corresponding event timing. The important implementation pattern is: ```text Browser Pixel event: event_name = Purchase event_id = purchase_123456789 Server CAPI event: event_name = Purchase event_id = purchase_123456789 ``` Meta recognizes these as two delivery paths for one conversion and should count one event. ## Browser implementation For the Pixel, send the identifier in the Pixel options object as `eventID`: ```javascript fbq('track', 'Purchase', purchaseParameters, { eventID: 'purchase_123456789' }); ``` ## Server-side CAPI implementation For CAPI, send the same value as `event_id`: ```json { "event_name": "Purchase", "event_time": 1735689600, "event_id": "purchase_123456789", "action_source": "website" } ``` ## Event ID design Use an opaque and stable naming convention: | Event | Suggested event ID pattern | |---|---| | `ViewContent` | `vc_<uuid>` | | `AddToCart` | `atc_<uuid>` | | `InitiateCheckout` | `ic_<checkout-token-or-uuid>` | | `Purchase` | `purchase_<internal-order-id>` | For Purchase events, use a stable non-customer identifier derived from the Shopify order record. Do not use email address, phone number, or another customer identifier in the event ID. ## Important deduplication rules ### 1. Same event name is required These will **not** deduplicate: ```text Pixel: Purchase / purchase_123 CAPI: purchase / purchase_123 ``` Meta event naming is case-sensitive in practice; use the exact standard event name, `Purchase`, in both places. ### 2. The event ID must be identical These will **not** deduplicate: ```text Pixel: Purchase / purchase_123 CAPI: Purchase / server_purchase_123 ``` ### 3. Do not generate a new ID during retries If a server request fails and is retried, resend the original Purchase event with the original `event_id`. Correct: ```text First attempt: purchase_123456 Retry: purchase_123456 ``` Incorrect: ```text First attempt: purchase_123456 Retry: purchase_123456_retry_2 ``` ### 4. Avoid multiple Pixel installations A common source of double counting is installing the Meta Pixel through: - Shopify’s Facebook & Instagram by Meta app, - Theme code, - Google Tag Manager, - A third-party tracking app, at the same time. For Cedar & Coil, select one implementation owner. If using Shopify’s native Meta integration, remove or disable manually installed duplicate Meta base code and duplicate event scripts unless a technical review confirms they are required and properly deduplicated. ### 5. CAPI-only events do not need browser deduplication If a Purchase event is intentionally sent only server-side, it does not need a browser counterpart. It should still have a unique, stable `event_id` to prevent duplicate delivery during retries. --- # 4. Preparing Customer Information for Server-Side CAPI CAPI’s `user_data` improves event matching when it contains correctly prepared, consented customer data. ## Data minimization principle Send only data that is: 1. Necessary for measurement. 2. Permitted under Cedar & Coil’s privacy policy and applicable law. 3. Covered by the visitor’s consent choice where consent is required. 4. Available from the event/order record. Do not put customer PII in: - `event_id` - Product names - URLs - Custom event parameters - Internal notes - Debug logs Use the dedicated CAPI `user_data` object. ## Recommended `user_data` fields Where legally permitted and available, CAPI can use: | Field | Preparation | |---|---| | `em` | Normalize and SHA-256 hash email | | `ph` | Normalize and SHA-256 hash phone number | | `fn` | Normalize and SHA-256 hash first name | | `ln` | Normalize and SHA-256 hash last name | | `ct` | Normalize and SHA-256 hash city | | `st` | Normalize and SHA-256 hash state/region | | `zp` | Normalize and SHA-256 hash ZIP/postal code | | `country` | Normalize and SHA-256 hash two-letter country code | | `external_id` | Normalize and SHA-256 hash a stable first-party ID, if used | | `fbp` | Send Meta browser ID as plain text; do not hash | | `fbc` | Send Meta click ID as plain text; do not hash | | `client_ip_address` | Send as plain text from the actual request context; do not hash | | `client_user_agent` | Send as plain text; do not hash | Use the Meta-supported fields and their current requirements for the selected Graph API version. ## Normalization before hashing For fields Meta expects to be hashed: 1. Convert to lowercase. 2. Remove leading and trailing whitespace. 3. Apply field-specific normalization. 4. SHA-256 hash the normalized value. 5. Send the lower-case hexadecimal hash. ### Email example ```text Raw: " Customer@Example.com " Normalized: "customer@example.com" SHA-256: <sha256 hash of customer@example.com> ``` ### Phone example Normalize to digits with country code, typically E.164-style without punctuation: ```text Raw: "(415) 555-0123" Normalized: "14155550123" SHA-256: <sha256 hash of 14155550123> ``` ### Names, city, and state Normalize by lowercasing and removing extra spacing and punctuation as appropriate before hashing. ```text Raw: " Ana-María " Normalized: "ana-maría" SHA-256: <hash> ``` Retain Unicode characters where appropriate rather than stripping meaningful characters indiscriminately. ## `_fbp` and `_fbc` These identifiers improve continuity between browser and server events. - `_fbp`: Meta browser identifier cookie. - `_fbc`: Meta click identifier, typically derived from the `fbclid` query parameter after an ad click. For a custom setup: 1. Read `_fbp` from the browser, where consent allows. 2. Capture the landing-page `fbclid` parameter. 3. Persist the relevant identifiers in a first-party store or checkout/session context consistent with the consent policy. 4. Pass them to the server with the cart or checkout request. 5. Include them in CAPI `user_data`. Do not fabricate `_fbp` or `_fbc` values. If the customer did not arrive through a Meta ad or the identifiers are unavailable, omit them. ## Never hash these fields Do not SHA-256 hash: - `fbp` - `fbc` - `client_ip_address` - `client_user_agent` Meta expects them in their original relevant formats. --- # 5. Concrete Shopify Setup Path ## Option A: Shopify’s Facebook & Instagram by Meta sales channel app ### What it provides Shopify’s official Meta integration generally provides: - Meta Pixel connection. - Server-side data sharing through Meta CAPI. - Product catalog sync. - Standard ecommerce events. - Simplified connection between Shopify, Meta Business Manager, and Ads Manager. The current Shopify user interface can change, but the typical path is: ```text Shopify Admin → Sales channels → Facebook & Instagram by Meta → Settings / Data sharing settings → Connect Meta Business Manager → Connect or create Meta Pixel → Choose customer data-sharing level → Select Maximum, subject to consent configuration ``` Also connect: ```text Facebook & Instagram by Meta → Product catalog / Commerce account → Sync Shopify products ``` Confirm that the Arc Clip Lamp is active and that its Shopify product/variant identifiers map correctly to the Meta catalog item IDs. ### Recommended configuration for Cedar & Coil For a small DTC store, use the official Shopify Meta app and: 1. Connect the correct Meta Business Portfolio/Business Manager. 2. Connect one production Meta Pixel. 3. Enable the highest supported data-sharing setting that is lawful for the store’s markets and consent configuration. 4. Sync the Shopify catalog. 5. Configure a consent banner and Shopify customer privacy settings before enabling marketing tracking in regulated regions. 6. Remove duplicate hard-coded Meta Pixel scripts from the Shopify theme. 7. Test the default standard events in Meta Events Manager. ### Strengths - Faster implementation. - Lower maintenance burden. - Shopify-aware checkout and order tracking. - Supported catalog synchronization. - Built-in server-side signal handling. - Lower risk of sending malformed payloads. ### Limitations - Less control over custom event logic and payload fields. - Less flexibility around bespoke data routing. - Implementation details may be abstracted by Shopify. - Custom event-level debugging can be less transparent than a fully owned server integration. ## Option B: Custom Pixel + custom CAPI integration A custom implementation usually includes: ```text Shopify theme or Web Pixels extension → browser Meta Pixel events → sends event_id and permitted identifiers to Cedar & Coil endpoint Shopify webhooks or Admin API order process → Cedar & Coil server → Meta Conversions API ``` For Purchase, use a server-side Shopify event such as a confirmed/paid order workflow appropriate to the store’s payment configuration. Verify webhook authenticity before processing. ### Strengths - Complete control over event timing and payloads. - Ability to enrich events with internal data. - More sophisticated consent, identity, and retry logic. - Easier to route events through a CDP or first-party tracking service if needed. ### Risks and costs - More engineering work. - Webhook handling, secure secret storage, retries, and monitoring are required. - Greater risk of duplicate Purchase events. - More responsibility for catalog ID alignment. - More responsibility for data retention, consent controls, and deletion workflows. - Shopify checkout restrictions can limit custom browser logic depending on the plan and checkout extensibility setup. ## Recommendation for Cedar & Coil > **Use Shopify’s Facebook & Instagram by Meta sales channel app as the production foundation.** Cedar & Coil is a small DTC store preparing its first Meta campaign. The native integration should cover the needed ecommerce funnel with less maintenance and less opportunity for implementation errors. Do **not** add a separate custom Purchase CAPI sender on top of the native integration unless there is a deliberate plan to control deduplication and avoid sending two independent server-side Purchase events. Consider a custom implementation later if Cedar & Coil needs: - Custom subscription, pre-order, lead, or quiz events. - A first-party event gateway. - Advanced server-side identity resolution. - Warehouse or CRM event enrichment. - Custom post-purchase lifecycle measurement. - A unified server-side event pipeline for Meta, Google, TikTok, and analytics tools. ## Custom CAPI Purchase request: code sketch This example is illustrative for a custom server integration. Keep the Meta access token in server-side environment variables only. Never expose it in Shopify theme code, browser JavaScript, or a public repository. ```javascript import crypto from "node:crypto"; const META_PIXEL_ID = process.env.META_PIXEL_ID; const META_CAPI_TOKEN = process.env.META_CAPI_TOKEN; const META_GRAPH_API_VERSION = process.env.META_GRAPH_API_VERSION || "vXX.X"; function sha256(value) { if (!value) return undefined; return crypto .createHash("sha256") .update(value.trim().toLowerCase(), "utf8") .digest("hex"); } function normalizePhone(phone) { if (!phone) return undefined; // Production code should use a phone parsing library and retain country code. return phone.replace(/[^\d]/g, ""); } async function sendMetaPurchase(order, requestContext = {}) { const eventId = `purchase_${order.id}`; // Stable across all retries. const contents = order.line_items.map((item) => ({ // Must match the connected Meta catalog ID convention. id: String(item.variant_id || item.product_id), quantity: item.quantity, item_price: Number(item.price) })); const contentIds = contents.map((item) => item.id); const userData = { em: sha256(order.email), ph: sha256(normalizePhone(order.phone)), fn: sha256(order.customer?.first_name), ln: sha256(order.customer?.last_name), ct: sha256(order.billing_address?.city), st: sha256(order.billing_address?.province_code), zp: sha256(order.billing_address?.zip), country: sha256(order.billing_address?.country_code), // Do not hash these fields. fbp: requestContext.fbp, fbc: requestContext.fbc, client_ip_address: requestContext.ip, client_user_agent: requestContext.userAgent }; // Remove fields not present; do not send undefined/null values. Object.keys(userData).forEach((key) => { if (!userData[key]) delete userData[key]; }); 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, user_data: userData, custom_data: { currency: order.currency || "USD", // Choose and document this convention. // This example uses the completed order total. value: Number(order.total_price), content_type: "product", content_ids: contentIds, contents, num_items: order.line_items.reduce( (total, item) => total + item.quantity, 0 ), // Not customer PII; useful for internal troubleshooting. order_id: String(order.order_number || order.id) } } ] // Add test_event_code only during controlled testing: // test_event_code: process.env.META_TEST_EVENT_CODE }; const endpoint = `https://graph.facebook.com/${META_GRAPH_API_VERSION}/` + `${META_PIXEL_ID}/events?access_token=${META_CAPI_TOKEN}`; const response = await fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }); const result = await response.json(); if (!response.ok) { throw new Error(`Meta CAPI request failed: ${JSON.stringify(result)}`); } return result; } ``` ### Production requirements omitted from the sketch Before using custom code in production, add: - Shopify webhook HMAC validation. - Idempotency storage keyed by Shopify order ID and Meta event ID. - Retry queue with exponential backoff. - Error monitoring and alerts. - Access-token secret management and rotation. - Consent-status enforcement before payload construction. - A documented event payload schema. - Data retention and deletion procedures. - Catalog-ID mapping tests. - A mechanism to carry consented `_fbp`, `_fbc`, URL, IP, and user-agent context into the order event where permissible. --- # 6. End-to-End Validation Before Scaling Spend Do not scale Meta spend until event delivery, parameter quality, deduplication, and consent behavior are validated. ## Step 1: Confirm there is one production Pixel In Shopify: - Confirm the production Pixel is connected through the selected implementation. - Search the Shopify theme, Google Tag Manager, and installed apps for duplicate `fbq(` code or duplicate Pixel IDs. - Remove obsolete or test Pixel IDs. In Meta Events Manager: - Confirm the Pixel ID matches the Pixel selected in Shopify. - Confirm the data source is receiving browser and server events if using CAPI. ## Step 2: Validate browser events with Meta Pixel Helper Use Meta Pixel Helper in a test browser session. Perform the normal Arc Clip Lamp purchase path: 1. Visit the Arc Clip Lamp product page. 2. Add the lamp to cart. 3. Begin checkout. 4. Complete a test order or a controlled real order/refund flow. Confirm: | Action | Expected browser event | |---|---| | Product page view | `ViewContent` | | Successful cart addition | `AddToCart` | | Checkout begins | `InitiateCheckout` | | Order confirmation page, if browser Purchase is implemented | `Purchase` | For each event, inspect: - Correct Pixel ID. - Correct event name. - `value` is numeric. - `currency` is `USD`. - `content_ids` is populated. - `contents` contains the expected item ID, quantity, and price. - No unexpected duplicate fires. ## Step 3: Validate server events in Meta Events Manager In Meta Events Manager: ```text Data Sources → Select Cedar & Coil’s Pixel → Test Events ``` Use Meta’s test-event workflow for controlled validation. For a custom CAPI request, include the provided `test_event_code` in the request payload temporarily. Confirm that Meta receives: - The expected event name. - `action_source: website`. - Correct `custom_data`. - Correctly formatted server-side `user_data`. - Event source URL where applicable. Never leave a test event code in production requests. ## Step 4: Test deduplication explicitly The essential test is to create one Purchase from both browser and server with the same event ID. Example: ```text Browser: Purchase eventID = purchase_987654 Server: Purchase event_id = purchase_987654 ``` Then inspect Meta Events Manager diagnostics/event details for deduplication status. Expected outcome: - Meta receives both browser and server versions. - Meta recognizes them as duplicates. - Reporting counts one Purchase, not two. Repeat for any funnel events sent through both paths. ## Step 5: Verify catalog ID alignment Compare the IDs sent in `content_ids` to IDs in Meta Commerce Manager. Check whether the catalog uses: - Shopify product IDs, - Shopify variant IDs, - SKU values, - Product handles, - A feed-generated retailer ID. The event must use the same identifier convention. For a store with variants, variant-level IDs are often the safest choice when the catalog is variant-based. A mismatch can cause: - Weak catalog matching. - Missing dynamic-ad product associations. - Incomplete event diagnostics. ## Step 6: Test common real-world scenarios Test at least the following: | Scenario | Expected behavior | |---|---| | Standard desktop browser | Browser and server events work | | Mobile browser | Events and checkout behavior remain correct | | Safari/private browsing | Server Purchase can still be delivered where consented and data is available | | Ad blocker enabled | Browser event may be blocked; server event behavior follows consent and implementation | | Customer declines marketing cookies | Marketing Pixel/CAPI behavior follows Cedar & Coil’s consent configuration | | Discount code applied | Purchase value reflects the documented valuation convention | | Quantity of two lamps | `contents` and `num_items` reflect quantity 2 | | Failed payment | No successful `Purchase` event | | Order confirmation page refresh | No second Purchase event | | Webhook retry | Same server-side Purchase `event_id`, not a new one | | Refund/cancellation | Does not create another Purchase; define separate financial reconciliation process if needed | ## Step 7: Monitor after launch For the first several days after launch, review: - Meta Events Manager Diagnostics. - Event Match Quality indicators as directional diagnostics, not a sole success metric. - Browser versus server event receipt patterns. - Event volume trends by event type. - Purchase values against Shopify completed orders. - Duplicate-event warnings. - Missing parameter warnings. - Unexpected currency or catalog-ID mismatches. Do not expect Meta-attributed purchases to equal Shopify total orders exactly. Attribution windows, consent choices, channel overlap, view-through attribution, time zones, event processing, and browser restrictions all affect differences. Use Shopify order data as the commerce system of record. --- # 7. Consent and Compliance Note ## Consent must control tracking Meta Pixel and CAPI are marketing measurement tools. Cedar & Coil should configure them in accordance with applicable privacy, cookie, and marketing laws in every market served. In many jurisdictions, including the EU and UK, marketing cookies and comparable identifiers generally require opt-in consent before they are set or used. Requirements may also apply in Canadian provinces and certain US states. Before activating broad tracking: 1. Publish a privacy policy that explains marketing and measurement data use. 2. Implement a consent management solution appropriate to Cedar & Coil’s markets. 3. Configure Shopify Customer Privacy settings and the Meta integration to respect consent choices. 4. Do not fire the browser Pixel before marketing consent where opt-in consent is required. 5. Do not send CAPI user data, `_fbp`, `_fbc`, IP address, or user-agent data where the customer has declined marketing measurement and no other valid legal basis applies. 6. Maintain a record of consent choices where required. 7. Provide mechanisms for access, deletion, and opt-out requests as required by law. 8. Ensure Meta Business Tools terms, data-use terms, and customer-data permissions are reviewed and accepted by the appropriate business owner. ## Do not treat CAPI as a consent bypass Server-side event delivery may be more technically durable than browser-only tracking, but it does not remove Cedar & Coil’s obligations to: - Obtain consent where required. - Honor opt-outs. - Minimize data. - Protect customer information. - Use customer data only for disclosed purposes. ## Security requirements - Keep Meta access tokens server-side and in a secrets manager/environment variable. - Restrict access to Shopify webhooks, Admin API credentials, and Meta tokens. - Validate Shopify webhook authenticity. - Do not log raw email, phone, address, IP address, or access tokens in application logs. - Define retention periods for event payload data and delete data no longer needed. --- # Launch Checklist ## Shopify and Meta connection - [ ] Facebook & Instagram by Meta sales channel installed. - [ ] Correct Meta Business account connected. - [ ] One production Meta Pixel connected. - [ ] Data sharing configured appropriately for Cedar & Coil’s consent model. - [ ] Arc Clip Lamp catalog item synced and active. - [ ] Catalog IDs confirmed against event `content_ids`. ## Event quality - [ ] `ViewContent` fires once per relevant product-page view. - [ ] `AddToCart` fires only after a successful cart addition. - [ ] `InitiateCheckout` fires once when checkout begins. - [ ] `Purchase` fires only for a successful/paid order. - [ ] `value` is numeric and follows the documented value convention. - [ ] `currency` is consistently `USD`. - [ ] Purchase includes `content_ids`, `contents`, and `num_items`. - [ ] No customer PII appears in event IDs, URLs, custom parameters, or logs. ## CAPI and deduplication - [ ] Server Purchase events use a stable order-based `event_id`. - [ ] Browser and server versions of the same event share the exact same event ID. - [ ] Retries reuse the original event ID. - [ ] Deduplication verified in Meta Events Manager. - [ ] No duplicate Pixel installation exists through theme code, GTM, or another app. ## Privacy and readiness - [ ] Consent banner and Shopify privacy settings tested. - [ ] Tracking behavior tested for consent accepted and consent declined. - [ ] Privacy policy reflects Meta marketing measurement use. - [ ] Team has access to Meta Events Manager and Shopify order reporting. - [ ] A test purchase has been completed and reconciled end to end.
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 browser Pixel + server-side CAPI with deduplication and explains why both are needed given browser tracking blocks/limits.
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 parameters, and Purchase explicitly includes 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, event_time, event_id, action_source, and a user_data block 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 details using Meta Events Manager's Test Events tool and Step 4 explicitly tests that browser/server Purchase events with the same event_id are deduplicated.
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 trigger 'from the confirmed Shopify order record' and explicitly warns 'Do not use a browser thank-you page alone as the authoritative order record.'
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 never promises attribution-recovery percentages and repeatedly ties data sending to consent ('Do not send CAPI user data... where the customer has declined marketing measurement').
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 specifies deduplication requires 'the same Pixel ID... same event_name... same event_id' with matched code examples showing identical event_id on Pixel and CAPI.
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 code sets `const eventId = \`purchase_${order.id}\`; // Stable across all retries` and text states 'If a server request fails and is retried, resend the original Purchase event with the original event_id.'
event_time_stable
The server Purchase event uses the purchase/order occurrence timestamp in Unix seconds and preserves it across retries; using the current send or retry time fails.
✓event_time is computed as `Math.floor(new Date(order.processed_at || order.created_at).getTime() / 1000)`, using the order's occurrence timestamp rather than send time, and text notes 'Event occurrence time, not 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 sha256 function normalizes via `.trim().toLowerCase()` before hashing, applied to email, phone, name, and address fields for user_data.
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 ('Use Shopify’s Facebook & Instagram by Meta sales channel app as the production foundation') with concrete numbered setup steps for a small DTC store.

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.19 · 81.7s · 5.8k tok
# Cedar & Coil: Shopify-to-Meta Conversion Tracking Guide ## 1. Recommended architecture Use two complementary event sources connected to the **same Meta dataset/Pixel**: 1. **Browser-side Meta Pixel** 2. **Server-side Meta Conversions API (CAPI)** 3. **Shared event IDs for deduplication** ### Why both are needed **Meta Pixel** records activity directly in the shopper’s browser. It can capture page context, Meta click/browser identifiers such as `_fbc` and `_fbp`, and events that occur before checkout. However, browser tracking can be limited by: - Browser privacy protections - Ad and content blockers - Cookie restrictions - Network interruptions - Users leaving before the browser confirms a purchase **Conversions API** sends events from Shopify or Cedar & Coil’s server to Meta. It is less dependent on browser scripts and provides a more reliable path for confirmed transactions. It is not a way to bypass consent requirements, and it does not make tracking immune to privacy limits. Together, Pixel and CAPI provide better event coverage and matching than either alone. When the same conversion is sent through both channels, Meta must receive a matching `event_name` and `event_id` so it counts the conversion once. ### Target event flow ```text Shopper browser └── Meta Pixel ├── ViewContent ├── AddToCart ├── InitiateCheckout └── Purchase \ > Same Meta dataset + same event_id → deduplicated event / Shopify/server └── Conversions API └── Purchase, and optionally other supported events ``` For a small DTC Shopify store, use Shopify’s native Meta integration rather than maintaining this architecture manually. --- ## 2. Standard events and parameters Use Meta’s standard event names exactly as written. Keep product identifiers consistent across: - Pixel events - CAPI events - The Meta product catalog - Every stage of the funnel For example, if the catalog uses Shopify variant IDs, send variant IDs everywhere rather than switching between product IDs and variant IDs. | Event | Trigger | Important parameters | |---|---|---| | `ViewContent` | A shopper views the Arc Clip Lamp product page | `content_ids`, `content_type`, `contents`, `value`, `currency` | | `AddToCart` | Shopify confirms the product was added to the cart | `content_ids`, `content_type`, `contents`, `value`, `currency` | | `InitiateCheckout` | The shopper enters checkout, not merely views the cart | `content_ids`, `content_type`, `contents`, `value`, `currency`, `num_items` | | `Purchase` | The order is successfully created or paid, according to the chosen accounting rule | `content_ids`, `content_type`, `contents`, `value`, `currency`, `order_id` | ### `ViewContent` Fire once when the Arc Clip Lamp product detail page is viewed. ```json { "content_ids": ["SHOPIFY_VARIANT_ID"], "content_type": "product", "contents": [ { "id": "SHOPIFY_VARIANT_ID", "quantity": 1, "item_price": 68.00 } ], "value": 68.00, "currency": "USD" } ``` Do not fire `ViewContent` for every general page view. ### `AddToCart` Fire only after Shopify confirms that the cart addition succeeded. ```json { "content_ids": ["SHOPIFY_VARIANT_ID"], "content_type": "product", "contents": [ { "id": "SHOPIFY_VARIANT_ID", "quantity": 1, "item_price": 68.00 } ], "value": 68.00, "currency": "USD" } ``` For multiple units, `value` should reflect the total value added and `quantity` should reflect the actual quantity. ### `InitiateCheckout` Fire when the checkout process begins. ```json { "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 } ``` Use the cart value at checkout initiation, after applicable discounts if Shopify supplies that value. ### `Purchase` Fire only for a confirmed order. Decide whether `value` represents revenue including or excluding tax and shipping, document that decision, and use it consistently. A common DTC choice is the final order total after discounts, including tax and shipping. If Cedar & Coil uses a different finance definition, align Meta reporting to that definition before launch. ```json { "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" } ``` Requirements: - `value` must be numeric, not `"$68.00"`. - `currency` should be the ISO 4217 code, such as `USD`. - `content_ids` must contain the purchased catalog identifiers. - `contents` should contain every purchased line item. - `order_id` helps with auditing, but it does **not** replace `event_id` for Pixel/CAPI deduplication. - Exclude gift cards, shipping lines, or other non-catalog items from `content_ids` unless the catalog and reporting plan intentionally include them. --- ## 3. Exactly how Pixel/CAPI deduplication works Meta deduplicates browser and server events when all of the following are true: 1. They are sent to the same Meta Pixel/dataset. 2. They use the same standard `event_name`, such as `Purchase`. 3. They carry the exact same `event_id`. 4. They arrive within Meta’s deduplication window. The browser Pixel sends the identifier as `eventID`: ```html <script> fbq( 'track', 'Purchase', { value: 68.00, currency: 'USD', content_ids: ['SHOPIFY_VARIANT_ID'], content_type: 'product' }, { eventID: 'shopify_order_123456789_purchase' } ); </script> ``` The server sends the same identifier as `event_id`: ```json { "event_name": "Purchase", "event_id": "shopify_order_123456789_purchase" } ``` Meta recognizes these as two delivery paths for one business event and retains one conversion rather than counting two. ### Event ID rules - Generate the ID from a stable business object, such as the Shopify order ID. - Include the event type if the same object can generate several events. - Never generate independent random IDs in the browser and server for the same action. - Never reuse one ID across different orders or different event names. - Store or deterministically recreate the ID for webhook retries. Recommended Purchase format: ```text shopify_order_{order_id}_purchase ``` For example: ```text shopify_order_123456789_purchase ``` `event_time`, `order_id`, or matching customer information alone do not provide deterministic event-ID deduplication. The key pairing is `event_name` plus `event_id`. ### Preventing duplicate server events Shopify webhooks can be retried. The CAPI sender should therefore maintain idempotency: 1. Receive the order or payment webhook. 2. Verify the Shopify webhook HMAC. 3. Build the deterministic `event_id`. 4. Check whether that event was already successfully sent. 5. Send it if needed. 6. Store Meta’s response and the successful event ID. Meta’s deduplication is useful, but it should not replace application-level retry and idempotency controls. --- ## 4. Preparing customer information for server-side events CAPI customer information belongs in `user_data`. Meta uses it to match the event to an account. Only send fields Cedar & Coil is permitted to process and that were genuinely supplied by the shopper. Do not invent missing values. ### Fields that must be normalized and SHA-256 hashed Common fields include: - `em`: email - `ph`: phone - `fn`: first name - `ln`: last name - `ct`: city - `st`: state or region - `zp`: postal code - `country`: two-letter country code - `external_id`: Cedar & Coil or Shopify customer ID Send hashed values as arrays where expected: ```json { "em": ["HASHED_EMAIL"], "ph": ["HASHED_PHONE"], "external_id": ["HASHED_CUSTOMER_ID"] } ``` ### Normalization before hashing Apply normalization first, then SHA-256 hash the UTF-8 value: - **Email:** trim surrounding whitespace and lowercase. - **Phone:** remove punctuation and spaces; retain digits, including the country code. - **Names:** trim and lowercase; follow Meta’s current normalization requirements for punctuation and character handling. - **City/state:** trim, lowercase, and normalize according to Meta’s current specification. - **Postal code:** trim, lowercase, and remove formatting characters where required. - **Country:** lowercase ISO two-letter code, such as `us`. - **External ID:** trim and normalize consistently before hashing. Do not hash an already hashed value. ### Fields that should not be hashed Send these in their original forms when available and permitted: - `client_ip_address` - `client_user_agent` - `fbp` - `fbc` Example: ```json { "em": ["...sha256..."], "ph": ["...sha256..."], "client_ip_address": "203.0.113.10", "client_user_agent": "Mozilla/5.0 ...", "fbp": "fb.1.1700000000000.123456789", "fbc": "fb.1.1700000000000.AbCdEfGh" } ``` `fbc` is generally derived from the Meta click identifier, while `fbp` identifies the browser. Do not fabricate either value. Preserve them from the browser into checkout/order data only where Shopify’s platform, consent state, and applicable law allow it. ### Data-handling controls - Keep the Meta access token only on the server. - Never put email, phone, or access tokens into page URLs. - Do not place raw customer information in `custom_data`. - Restrict logs so they do not retain raw checkout data unnecessarily. - Ensure any custom Shopify app has the required protected customer-data access. - Define retention and deletion procedures for event logs. --- ## 5. Shopify setup path ## Option A: Native Facebook & Instagram by Meta sales channel This is the recommended option for Cedar & Coil. Exact labels can change, but the typical path is: 1. In Shopify Admin, open **Settings → Apps and sales channels**. 2. Install or open **Facebook & Instagram by Meta**. 3. Connect the correct: - Meta business portfolio - Facebook Page - Ad account - Commerce/catalog assets - Meta Pixel/dataset 4. Under the channel’s data-sharing settings, select **Maximum** data sharing. 5. Confirm that the intended Pixel/dataset—not an old test asset—is connected. 6. Confirm the Shopify product catalog is syncing the Arc Clip Lamp and note which identifier format Meta receives. 7. Configure Shopify’s customer privacy and consent settings for the markets where Cedar & Coil sells. 8. Remove any old theme-installed Meta Pixel or GTM Meta tag that would send the same events separately. 9. Test the event flow before publishing campaigns. Shopify’s **Maximum** data-sharing setting is intended to use browser and server-side data sharing, including Conversions API. The integration also manages much of the event mapping and deduplication. ### Why this is recommended For a small DTC store, the native integration offers: - Lower implementation and maintenance cost - Compatibility with Shopify checkout changes - Built-in Pixel/CAPI coordination - Catalog integration - Less risk of exposing access tokens - Less custom handling of protected customer data - Fewer opportunities for duplicate Purchase events Do not install a second Meta Pixel through the theme or Google Tag Manager unless there is a documented reason and a deduplication design. ## Option B: Custom implementation A custom implementation is justified when Cedar & Coil needs: - A nonstandard revenue definition - A specialized consent workflow - Custom event enrichment - Control over event retry queues - Multiple storefront or backend sources - Data routing through an existing server-side platform A custom build generally needs: - Shopify Web Pixels or Customer Events for browser events - A secure app or endpoint for Shopify webhooks - HMAC verification - Access to permitted Shopify order/customer fields - CAPI token storage - Hashing and normalization - Stable event-ID generation - Retry handling and idempotency - Consent enforcement - Monitoring and alerting Checkout tracking should use Shopify’s supported Customer Events/Web Pixels mechanisms rather than unsupported checkout-script or theme workarounds. ### Server-side Purchase request sketch The following Node.js sketch illustrates a custom server-side Purchase event. It assumes the Shopify webhook has already been authenticated and consent eligibility has been evaluated. ```javascript import crypto from "node:crypto"; const sha256 = (value) => crypto .createHash("sha256") .update(String(value), "utf8") .digest("hex"); const normalizeEmail = (value) => value.trim().toLowerCase(); const normalizePhone = (value) => value.replace(/\D/g, ""); // Include country code in the source value. const normalizeText = (value) => value.trim().toLowerCase(); function hashIfPresent(value, normalize = normalizeText) { if (value === null || value === undefined || value === "") return undefined; return sha256(normalize(String(value))); } export async function sendPurchaseToMeta(order, testEventCode) { const pixelId = process.env.META_PIXEL_ID; const accessToken = process.env.META_CAPI_ACCESS_TOKEN; const graphVersion = process.env.META_GRAPH_API_VERSION; if (!pixelId || !accessToken || !graphVersion) { throw new Error("Missing Meta CAPI configuration"); } const eventId = `shopify_order_${order.id}_purchase`; const contents = order.line_items.map((item) => ({ // This must match the identifier used by the Meta catalog. id: String(item.variant_id ?? item.product_id), quantity: Number(item.quantity), item_price: Number(item.price) })); const contentIds = contents.map((item) => item.id); const userData = { em: order.email ? [hashIfPresent(order.email, normalizeEmail)] : undefined, ph: order.phone ? [hashIfPresent(order.phone, normalizePhone)] : undefined, fn: order.billing_address?.first_name ? [hashIfPresent(order.billing_address.first_name)] : undefined, ln: order.billing_address?.last_name ? [hashIfPresent(order.billing_address.last_name)] : undefined, ct: order.billing_address?.city ? [hashIfPresent(order.billing_address.city)] : undefined, st: order.billing_address?.province_code ? [hashIfPresent(order.billing_address.province_code)] : undefined, zp: order.billing_address?.zip ? [hashIfPresent(order.billing_address.zip)] : undefined, country: order.billing_address?.country_code ? [hashIfPresent(order.billing_address.country_code)] : undefined, external_id: order.customer?.id ? [hashIfPresent(order.customer.id)] : undefined, // These values are not hashed. client_ip_address: order.client_details?.browser_ip, client_user_agent: order.client_details?.user_agent, // Populate only if legitimately captured and consent permits. fbp: order.meta_tracking?.fbp, fbc: order.meta_tracking?.fbc }; // Remove absent values rather than sending nulls or empty arrays. Object.keys(userData).forEach((key) => { const value = userData[key]; if ( value === undefined || value === null || value === "" || (Array.isArray(value) && value.some((item) => !item)) ) { delete userData[key]; } }); 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: order.checkout_url, user_data: userData, custom_data: { currency: order.currency.toUpperCase(), value: Number(order.total_price), content_type: "product", content_ids: contentIds, contents, order_id: String(order.id) } } ], access_token: accessToken }; if (testEventCode) { payload.test_event_code = testEventCode; } const response = await fetch( `https://graph.facebook.com/${graphVersion}/${pixelId}/events`, { 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 { eventId, result }; } ``` Production additions should include: - Shopify webhook HMAC verification - A durable queue - Retry logic with backoff - Idempotency storage keyed by `event_id` - Structured response logging without raw customer data - Alerts for repeated API failures - Refund and cancellation policy decisions - Token rotation - Meta’s current Graph API version and current parameter requirements If using the native Meta sales channel, do **not** deploy this custom Purchase sender in parallel unless the native Purchase event is disabled or both implementations intentionally share the same event ID. Otherwise, duplicate purchases are likely. --- ## 6. End-to-end validation before scaling spend ## A. Configuration audit Confirm: - [ ] Only one intended Meta Pixel/dataset is connected - [ ] The ad account uses that same dataset - [ ] The Arc Clip Lamp appears in the Meta catalog - [ ] Event `content_ids` match catalog item identifiers exactly - [ ] There is no legacy theme Pixel firing duplicate events - [ ] There is no additional GTM Meta tag duplicating Shopify’s integration - [ ] Shopify data sharing is set to the intended level - [ ] Consent settings are configured by market ## B. Browser testing Use Meta Events Manager’s **Test Events** view and browser developer tools. Complete a test journey: 1. Open the Arc Clip Lamp product page. 2. Confirm one `ViewContent`. 3. Add the item to cart. 4. Confirm one `AddToCart`. 5. Begin checkout. 6. Confirm one `InitiateCheckout`. 7. Complete a Shopify test order. 8. Confirm `Purchase`. For each event, inspect: - Event name - Browser or server source - `event_id` - `value` - `currency` - `content_ids` - `contents` - Product quantities - Event timestamp - URL where applicable ## C. Deduplication test For a test Purchase, verify that Events Manager receives both: - A browser Purchase - A server Purchase They must have: ```text event_name: Purchase event_id: shopify_order_{same_order_id}_purchase ``` Meta should report the event as deduplicated rather than as two purchases. If two purchases appear, inspect: - Different event IDs - Browser event missing `eventID` - Server event missing `event_id` - Two different Pixels/datasets - Multiple native or theme integrations - Thank-you-page reloads - Webhook retries generating new IDs ## D. Server payload testing For custom CAPI implementations: 1. Use Meta’s test event code. 2. Submit a controlled order. 3. Check the CAPI response for accepted events. 4. Confirm no raw email or phone appears in the outbound JSON. 5. Confirm `client_ip_address`, `client_user_agent`, `fbc`, and `fbp` are not hashed. 6. Retry the same webhook and verify the application does not create a new conversion ID. 7. Simulate a temporary Meta API failure and verify that the queue retries safely. Remove the test event code before production use. ## E. Reconciliation Before scaling spend, compare at least several days of stable production data: - Shopify paid orders - Meta received Purchase events - Meta deduplicated Purchase events - Total Purchase value - Currency - Product quantities - Failed or delayed server events These systems will not necessarily show identical attributed conversions because Shopify order reporting and Meta attribution answer different questions. The implementation check is whether confirmed orders and values are being delivered correctly—not whether every Shopify order is attributed to Meta. Also monitor Meta Events Manager for: - Diagnostics warnings - Missing Purchase parameters - Low or declining event match quality - Duplicate events - Invalid customer-information formatting - Server delays - Catalog/content ID mismatches Do not scale spend until test orders produce one logical Purchase each, with correct value, currency, and product identifiers. --- ## 7. Consent and compliance Conversions API is a transmission method, not a consent exemption. Server-side events must respect the same privacy choices and legal requirements as browser tracking. Cedar & Coil should: - Use Shopify’s customer privacy tools or a compatible consent management platform. - Prevent nonessential Meta browser tracking until required consent is obtained in applicable regions. - Apply the same consent decision to server-side CAPI events where required. - Avoid sending events for users who have opted out when the applicable law or Cedar & Coil’s policy requires suppression. - Disclose Meta Pixel and CAPI processing in the privacy notice. - Collect only the customer fields needed for measurement and matching. - Restrict access to raw customer and event data. - Establish retention and deletion procedures. - Ensure Meta’s contractual terms and data-processing settings are reviewed. - Obtain legal advice for the specific countries and states where the store operates. For a custom build, pass the shopper’s consent state into the server workflow. Do not assume that receiving an order webhook automatically authorizes sending that order and its customer information to Meta.
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 'Browser-side Meta Pixel' plus 'Server-side Meta Conversions API (CAPI)' with shared event IDs, and explains browser limits like ad blockers, cookie restrictions, and users leaving before confirmation.
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 detailed JSON examples for ViewContent, AddToCart, InitiateCheckout, and Purchase, each with value, currency, and content_ids (plus order_id) 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 Node.js sendPurchaseToMeta function includes event_name: 'Purchase', event_time computed from order timestamp, event_id, action_source: 'website', and a full user_data block.
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's 'Test Events' view and includes a dedicated 'Deduplication test' subsection verifying browser and server Purchase events are reported as deduplicated rather than double-counted.
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 architecture diagram places ViewContent/AddToCart/InitiateCheckout under Pixel and Purchase under both Pixel and server/CAPI, and the code sketch derives Purchase from the Shopify order webhook rather than a thank-you page script.
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 never states an attribution-recovery percentage and Section 7 explicitly frames consent/regional rules as constraints ('CAPI is a transmission method, not a consent exemption').
dedup_correct
Deduplication is technically correct: the same event_id and event_name sent on both the Pixel and CAPI event so Meta drops the duplicate; not a vague mention.
✓Section 3 states Meta deduplicates when events share the same 'event_name' and exact same 'event_id' sent to the same dataset, with concrete Pixel/CAPI examples using identical event_id values.
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 instructs to 'Store or deterministically recreate the ID for webhook retries' and to 'check whether that event was already successfully sent' before resending, explicitly warning against generating independent random IDs per send.
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 computes event_time as `Math.floor(new Date(order.processed_at ?? order.created_at).getTime() / 1000)`, deriving it from the stable order 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 specifies normalizing email (trim/lowercase) and phone before SHA-256 hashing, matched by normalizeEmail/normalizeText functions and sha256() calls 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 explicitly states 'This is the recommended option for Cedar & Coil' for the native Meta sales channel and lists a concrete 9-step setup path, contrasting it decisively with the custom Option B.

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.067 · 68.3s · 5.9k tok
# Meta Conversion Tracking Implementation Guide — Cedar & Coil / Arc Clip Lamp (Shopify) **Status:** Draft implementation plan. No campaigns are live and no performance data exists yet — this guide covers infrastructure only. --- ## 1. Recommended Architecture: Pixel + Conversions API with Deduplication Use **both** the browser-side Meta Pixel and the server-side **Conversions API (CAPI)**, sending the same events from each, deduplicated by a shared `event_id`. **Why both are needed:** - **Pixel alone is unreliable.** Safari ITP, Firefox ETP, ad blockers, and users declining cookie consent all break the browser pixel's ability to fire or persist identifiers (`_fbp`, `_fbc`). Data loss on iOS Safari in particular is significant. - **CAPI alone loses some signal.** Server-side events come from your backend (Shopify order data), so they can be highly reliable and complete, but they don't have access to browser-only click/browser IDs unless you capture and pass them through (e.g., `fbc` from the `fbclid` URL parameter, `fbp` from the pixel cookie). - **Together, they cover each other's gaps.** The pixel captures browser context and click IDs when available; CAPI guarantees the event still reaches Meta even if the browser call is blocked or delayed. Meta's own matching system merges duplicate signals into one event when correctly deduplicated, giving Meta the richest possible set of matching parameters per conversion. This is Meta's own recommended baseline architecture for any store running paid acquisition — not an optional enhancement. No specific improvement in attribution or reported conversions should be promised in advance; the intended outcome is more complete and reliable event delivery, not a guaranteed lift. --- ## 2. Standard Events to Send Send four standard events, all with `currency` and `value` populated, and Purchase always including `content_ids`. | Event | Trigger | Key Parameters | |---|---|---| | **ViewContent** | Arc Clip Lamp product page loads | `content_ids: ["<shopify_product_or_variant_id>"]`, `content_type: "product"`, `content_name: "Arc Clip Lamp"`, `currency: "USD"`, `value: 68.00` | | **AddToCart** | Item added to cart | Same as above, plus `contents: [{id, quantity, item_price}]` | | **InitiateCheckout** | Checkout begins | `content_ids`, `content_type`, `currency`, `value` (cart total), `num_items` | | **Purchase** | Order confirmed (thank-you page / order webhook) | `content_ids: [<line item ids>]`, `content_type: "product"`, `contents: [{id, quantity, item_price}]`, `currency: "USD"`, `value: <order total>`, `num_items`, plus `order_id` used to build `event_id` | Notes: - `value` and `currency` must be present on every event or Meta cannot optimize toward value-based bidding. - `content_ids` on Purchase should reflect actual Shopify product/variant IDs, not SKUs, unless your catalog feed uses SKUs consistently. - Use only real order and product data — do not fabricate test values in events that could reach the live ad account. --- ## 3. How Deduplication Works Between Pixel and CAPI Meta deduplicates when it receives two events that share the **same `event_name`** and the **same `event_id`**, one from the Pixel and one from CAPI, within its dedup window. Mechanics: 1. **Generate one `event_id` per real event.** For Purchase, derive it from something stable and unique to the order — e.g. the Shopify order ID or checkout token (`purchase_<order_id>`). 2. **Send that same `event_id` on both channels:** - Pixel: `fbq('track', 'Purchase', {...}, {eventID: 'purchase_1234567890'})` - CAPI: include `"event_id": "purchase_1234567890"` in the server event payload. 3. Meta matches on `event_name` + `event_id` (scoped to the pixel ID) and keeps one event for reporting, merging the parameter sets from both sources for matching purposes. 4. If the IDs don't match exactly (case-sensitive, byte-for-byte), Meta will count both events, inflating your reported conversions — this is the most common implementation error and should be explicitly checked during validation. 5. Timing doesn't need to be simultaneous, but sending both close in time (seconds to a few minutes apart) is best practice; avoid the CAPI event being wildly delayed relative to the browser event. --- ## 4. Preparing Customer Information for Server-Side Events Before sending `user_data` via CAPI, all personally identifiable fields must be normalized and hashed. Meta requires SHA-256 hashing for PII fields; a few fields are sent unhashed. **Normalize, then hash (SHA-256, lowercase hex output):** - `em` (email): lowercase, trim whitespace - `ph` (phone): strip all non-digits, include country code, no leading `+` or `00` - `fn` / `ln` (first/last name): lowercase, trim, remove punctuation - `ct` / `st` / `zp` / `country`: lowercase, trim; zip stripped to base 5-digit for US **Send unhashed:** - `client_ip_address` and `client_user_agent` — captured server-side at the time of the request - `fbp` — the `_fbp` browser cookie value, if present - `fbc` — derived from the `fbclid` URL parameter on click-through, or the `_fbc` cookie if already set - `external_id` — your internal customer or order-linked ID, hashed is optional but recommended **Rules:** - Never log or store raw hashed-input PII outside of the request itself. - Send as many matched identifiers as you legitimately have — match quality improves with more fields, but only send fields you actually collected as part of the transaction (don't infer or guess). - Do not send PII in `custom_data` — only in `user_data`. --- ## 5. Shopify Setup Path ### Option A — Native Meta / Facebook & Instagram Sales Channel App Shopify's official Meta channel handles Pixel + CAPI as one integrated setup: you connect your Meta Business Account, and Shopify fires both the browser pixel and server-side events (via Shopify's backend, using checkout and order data) with deduplication handled automatically. **Pros:** No custom code, maintained by Shopify/Meta as checkout and platform APIs evolve (important since Shopify has been deprecating `checkout.liquid` customizations), automatically includes standard events and reasonable parameter coverage, lower risk of breakage. **Cons:** Less control over exact parameter values, custom event definitions, or non-standard data enrichment. ### Option B — Custom Implementation Manually install the Pixel (via theme/Checkout UI extension) and build a server-side endpoint (Shopify app, Cloudflare Worker, or backend function) triggered by Shopify webhooks (`orders/create`, `checkouts/update`) that posts events directly to the Meta Graph API. **Pros:** Full control over event payloads, custom parameters, ability to combine with other systems (CRM, loyalty). **Cons:** You own maintenance as Shopify checkout APIs change, higher dev cost, more surface area for silent breakage. ### Recommendation For a small DTC store like Cedar & Coil selling a single hero product, **use the native Meta sales channel app with Conversions API enabled.** It covers all four standard events out of the box, requires no ongoing engineering maintenance, and is sufficient until there's a specific need (custom audiences beyond order data, multi-platform event fan-out, etc.) that the native app can't support. ### Code Sketch — Server-Side Purchase Event (for reference / custom path only) ```javascript // POST https://graph.facebook.com/v19.0/{pixel_id}/events?access_token={token} const crypto = require('crypto'); const hash = (v) => crypto.createHash('sha256').update(v.trim().toLowerCase()).digest('hex'); const payload = { data: [ { event_name: 'Purchase', event_time: Math.floor(Date.now() / 1000), event_id: `purchase_${order.id}`, // must match the pixel event_id action_source: 'website', event_source_url: order.order_status_url, user_data: { em: hash(order.email), ph: order.phone ? hash(order.phone.replace(/\D/g, '')) : undefined, fn: hash(order.customer.first_name), ln: hash(order.customer.last_name), client_ip_address: order.client_ip, client_user_agent: order.user_agent, fbp: order.fbp_cookie, fbc: order.fbc_cookie }, custom_data: { currency: 'USD', value: parseFloat(order.total_price), content_type: 'product', content_ids: order.line_items.map(li => String(li.product_id)), contents: order.line_items.map(li => ({ id: String(li.product_id), quantity: li.quantity, item_price: parseFloat(li.price) })) } } ] }; // send via fetch/axios POST to the Graph API endpoint above ``` Trigger this from the `orders/create` webhook so it fires once per confirmed order, with the same `event_id` scheme used by the browser pixel's Purchase event. --- ## 6. End-to-End Validation Before Scaling Spend Do not increase ad budgets until all of the following are confirmed: 1. **Events Manager > Test Events**: place test orders and confirm ViewContent, AddToCart, InitiateCheckout, and Purchase all appear from both Browser and Server sources. 2. **Deduplication check**: confirm Meta shows one combined event per action (labeled with both Browser and Server tags), not two separate counts. If duplicates appear, verify `event_id` generation and casing on both sides. 3. **Parameter check**: inspect a handful of real test events for correct `value`, `currency`, and `content_ids` — cross-reference against the actual Shopify order. 4. **Event Match Quality (EMQ)**: check the score in Events Manager for Purchase; identify which `user_data` fields are missing or low-coverage and address gaps in normalization/hashing. 5. **Diagnostics tab**: resolve any errors or warnings Meta surfaces for the pixel or CAPI integration. 6. **Reconciliation**: over a short window of real orders, compare Shopify's order count/revenue to Meta's reported Purchase count/value for the same period. Investigate material discrepancies before trusting the numbers for optimization. 7. **Cross-browser/device spot check**: verify Purchase still lands via CAPI even when tested in Safari with tracking protections on and the pixel blocked. Only once dedup is clean, EMQ is stable, and Shopify/Meta numbers reconcile within a reasonable margin should ad spend be scaled. --- ## 7. Consent and Compliance Note - Events (both Pixel and CAPI) must respect visitor consent status. Integrate with Shopify's Customer Privacy API / your cookie consent banner so that tracking is suppressed or adjusted for visitors who haven't consented, particularly for EU/UK/CA traffic under GDPR and similar frameworks. - Do not send raw, unhashed PII to Meta under any circumstances — only the normalized/hashed fields specified in Section 4. - If relying on Meta's Limited Data Use (LDU) flag for CCPA-relevant traffic, configure it consistently across both Pixel and CAPI. - Maintain a record of what customer data is collected, why, and how it flows to Meta, and keep retention/deletion processes aligned with Shopify's own customer data policies. - This is an operational compliance checklist, not legal advice — confirm final consent and data-handling requirements with counsel before launch.
Score the judge's verdict, criterion by criterion9/11 criteria passed · failed: sources_defined, 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 explicitly recommends 'both the browser-side Meta Pixel and the server-side Conversions API (CAPI)' and explains browser limitations (ITP, ETP, ad blockers) and CAPI reliability gaps.
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 table lists ViewContent, AddToCart, InitiateCheckout, and Purchase with value, currency, and content_ids specified for each, including content_ids 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 JS code sketch in Section 5 includes event_name, event_time, event_id, action_source, and a user_data block as required.
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 'Events Manager > Test Events' and explicitly checks that 'Meta shows one combined event per action ... not two separate 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).
✗While Purchase's server source (orders/create webhook) is clarified in Section 5, the guide never explicitly states where ViewContent, AddToCart, and InitiateCheckout fire (browser vs server) or their source of truth, leaving that ambiguous.
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 states 'No specific improvement in attribution or reported conversions should be promised in advance' and Section 7 notes consent/regional constraints (GDPR, CCPA/LDU) 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 explains Meta 'deduplicates when it receives two events that share the same event_name and the same event_id, one from the Pixel and one from CAPI' with concrete fbq/eventID and payload 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 `purchase_${order.id}`, ensuring the same ID is reused across the pixel and server sends and would remain stable on repeated triggers since it's tied to the order ID rather than randomly generated.
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: Math.floor(Date.now() / 1000)`, using the current send time rather than the order's occurrence timestamp, which would not be stable across webhook retries.
pii_hashing
Customer data handling is correct: personally identifiable fields (e.g. email) are normalized (trimmed, lowercased) and SHA-256 hashed before sending in user_data.
✓Section 4 specifies normalizing (lowercase, trim) email/phone/name fields and hashing them with SHA-256 before sending in user_data, and the code sketch applies a hash() function using SHA-256.
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 with Conversions API enabled' for a small DTC store, with concrete pros/cons and setup guidance.

Claude Opus 5 default

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.24 · 118.7s · 8.6k tok
# Cedar & Coil — Meta Conversion Tracking Implementation Guide **Scope:** Shopify store → Meta (Pixel + Conversions API) for the Arc Clip Lamp ($68 USD) **Status:** Draft implementation spec. No campaign has launched and no performance data exists, so this document contains no benchmarks, projections, or expected lift figures. --- ## 1. Recommended Architecture **Send every conversion event twice — once from the browser (Meta Pixel), once from a server (Conversions API) — with a shared `event_id` so Meta collapses the pair into one event.** ``` ┌──────────────────────────────┐ Shopper's │ Shopify storefront + checkout │ browser ───────▶│ Web Pixel (Customer Events) │──── Pixel event ────▶ Meta └──────────────────────────────┘ (event_id: X) Events │ Manager │ order created │ ▼ dedup on ┌──────────────────────────────┐ (event_name │ Server: Shopify webhook → │─── CAPI event ────▶ + event_id) │ CAPI relay (or Meta channel) │ (event_id: X) └──────────────────────────────┘ ``` **Why both, not one:** | Signal path | Strengths | Fails when | |---|---|---| | Browser Pixel | Rich automatic context (`fbp`, `fbc`, referrer, user agent), easy to debug, needed for click-ID capture | Ad blockers, ITP/ETP cookie lifetime limits, script blocked or slow, tab closed before fire, iOS/ATT constraints | | Conversions API | Fires from your infrastructure, not affected by browser blocking; carries hashed customer data for matching; can fire on delayed/backend truth (order created, refund) | Missing browser-only identifiers unless you pass them through; only as good as the data you attach | The browser path is the *only* place where `fbc` (the click ID from `fbclid`) and `fbp` (the browser ID) are naturally created. The server path is the only path that survives when the browser one is blocked. Deduplication is what lets you run both without double-counting. **Do not** treat CAPI as a replacement for the Pixel — Meta's matching quality is highest when both arrive for the same event. --- ## 2. Events and Parameters Four standard events. Keep the set small — each one has to earn its place in the funnel report and in Aggregated Event Measurement (AEM) prioritization. | Event | Trigger | Required params | Recommended params | |---|---|---|---| | `ViewContent` | Arc Clip Lamp PDP loads | `content_ids`, `content_type: "product"` | `value: 68.00`, `currency: "USD"`, `content_name: "Arc Clip Lamp"`, `content_category` | | `AddToCart` | Add-to-cart succeeds (not click) | `content_ids`, `content_type` | `value`, `currency`, `contents: [{id, quantity, item_price}]` | | `InitiateCheckout` | Checkout started | `value`, `currency` | `content_ids`, `contents`, `num_items` | | `Purchase` | Order created / thank-you page | **`value`, `currency`, `content_ids`** | `content_type`, `contents`, `num_items`, `order_id` | **Rules that prevent most downstream mess:** - **`value`** is a number, not a string, not currency-formatted. `68.00`, never `"$68.00"`. - **`currency`** is ISO-4217 uppercase — `"USD"`. Always send it alongside `value`; a value without currency is unusable for ROAS. - **`content_ids`** must match the IDs in your Meta product catalog feed exactly, or dynamic ads and catalog reporting break. If you use Shopify's Meta catalog sync, that is typically the variant-based ID (e.g. `shopify_US_<product_id>_<variant_id>`). Pick one ID scheme, document it, use it on all four events. - **Value definition:** choose product subtotal *or* order total (incl. shipping/tax) and apply it everywhere. Recommended for Cedar & Coil: **product subtotal, excluding shipping and tax** — cleaner for judging creative and product-level ROAS. Write it down so nobody "fixes" it later. - **Every event needs** `event_id`, `event_time`, `action_source` (`"website"`), and `event_source_url`. - Single-SKU catalog today (lamp, padded clamp, USB-C cable, storage sleeve in one box = one purchasable item), so `num_items` is usually the lamp quantity. Structure it properly now anyway; it costs nothing and survives a second product. Example Purchase payload shape (custom_data): ```json { "value": 68.00, "currency": "USD", "content_ids": ["shopify_US_8123456789_45678901234"], "content_type": "product", "contents": [{ "id": "shopify_US_8123456789_45678901234", "quantity": 1, "item_price": 68.00 }], "num_items": 1, "order_id": "5501234567890" } ``` --- ## 3. How Deduplication Works Meta deduplicates when **both** of these match across a browser event and a server event: 1. **`event_name`** — identical string (`Purchase` = `Purchase`; `purchase` will not match). 2. **`event_id`** — identical string you generate. If both match and the events arrive within Meta's dedup window (roughly 48 hours; treat the practical window as much shorter), Meta keeps one — generally the first received — and discards the duplicate. `fbp` + `event_name` can serve as a secondary fallback signal, but **do not rely on it**. Always set `event_id` explicitly. **How to generate `event_id`:** | Event | ID strategy | |---|---| | `Purchase` | Use the Shopify **order ID** (stable, available on both browser and server). This is the single most important one to get right. | | `ViewContent`, `AddToCart`, `InitiateCheckout` | Generate a UUID client-side, stash it in the event payload, and pass the same UUID to your server call for that same interaction. | **Critical failure modes to avoid:** - Generating the ID independently on client and server (e.g., two `uuid()` calls) → two IDs → double-counted conversions and inflated ROAS. - Sending the event twice from the *same* source with the same ID — dedup is designed for cross-source pairs; same-source repeats can still register. - Mismatched case or type: `order_id` as integer server-side and string client-side. Cast both to string. - Firing `Purchase` on thank-you page refresh without an order-ID-based `event_id` → the same order counts repeatedly. --- ## 4. Preparing Customer Information (Server-Side) Server events carry `user_data` — the matching signal. Meta requires customer identifiers to be **normalized, then SHA-256 hashed, hex-encoded, lowercase**. **Normalize before hashing:** | Field | Key | Normalization | |---|---|---| | Email | `em` | Trim, lowercase. `Sam@Example.COM ` → `sam@example.com` | | Phone | `ph` | Digits only, include country code, no `+`, no spaces/dashes. `(415) 555-0132` US → `14155550132` | | First / last name | `fn`, `ln` | Trim, lowercase, strip punctuation and titles | | City | `ct` | Lowercase, remove spaces and punctuation. `San Francisco` → `sanfrancisco` | | State | `st` | Two-letter lowercase (`ca`) | | Zip | `zp` | Lowercase; US: first 5 digits only | | Country | `country` | Two-letter ISO lowercase (`us`) | | External ID | `external_id` | Your stable customer/user ID; hash it (recommended) and use consistently | **Send these fields raw — hashing them breaks matching:** - `client_ip_address` — the shopper's IP, not your server's - `client_user_agent` — the shopper's browser UA string - `fbc` — from the `_fbc` cookie, or built as `fb.1.<timestamp_ms>.<fbclid>` when you capture `fbclid` from the landing URL - `fbp` — from the `_fbp` cookie **Operational requirements:** - Capture `_fbp`, `_fbc`, IP, and UA **in the browser at checkout** and persist them onto the order (Shopify cart/order attributes or your own datastore) so the server event can attach them. A server webhook has none of this on its own — this is the most commonly skipped step and the one that most degrades match quality. - Never send unhashed email, phone, or name to Meta. Never log unhashed values in your webhook logs. - Hash on your server, not in the browser. - More correctly-populated fields → higher Event Match Quality. Send everything you legitimately hold and are permitted to send (see §7). --- ## 5. Shopify Setup Path ### Option A — Native Meta sales channel app ("Facebook & Instagram" by Meta) | | | |---|---| | **Setup** | Install app → connect Business Manager, Page, ad account, pixel/dataset → set data sharing to **Maximum** → verify domain → configure AEM event priority | | **You get** | Pixel via Shopify's Customer Events sandbox, server-side events for the standard funnel, deduplication handled by Meta/Shopify, catalog sync for dynamic ads | | **Limits** | Little control over payload shape, value definition, or custom parameters; debugging is opaque when something drifts; you inherit whatever schema the app ships | ### Option B — Custom implementation | | | |---|---| | **Setup** | Shopify **Web Pixel Extension** (Customer Events API) for browser events, since `checkout.liquid` script injection is no longer available; plus a server (Cloudflare Worker, Vercel function, small Node service) receiving the `orders/create` webhook and calling the Meta Graph API | | **You get** | Full control of `event_id`, value definition, `content_ids`, `user_data`, consent gating, retries, logging | | **Costs** | Engineering time, hosting, secret management, ongoing maintenance against Meta API version bumps | ### Recommendation for Cedar & Coil **Start with Option A — the native Meta sales channel with Maximum data sharing.** One product, one price, no subscriptions, no complex bundles. The native app covers all four events with correct deduplication and zero maintenance, and it keeps the catalog in sync for dynamic ads. Spending engineering time on a bespoke relay before a single campaign has run is premature. **Escalate to a custom server-side Purchase only if** validation (§6) shows a persistent gap between Shopify order count and Meta-reported Purchases, or you need a value definition the app can't express (e.g., excluding shipping). If you add one, **you must set `event_id` to the Shopify order ID on both paths** or you will double-count. ### Code sketch — server-side Purchase from a Shopify `orders/create` webhook ```js // Node / Express. Illustrative — add retries, structured logging, and error alerting. import crypto from "node:crypto"; const PIXEL_ID = process.env.META_PIXEL_ID; const ACCESS_TOKEN = process.env.META_CAPI_TOKEN; // system user token, server-side only const API_VERSION = "v21.0"; const sha256 = (v) => v ? crypto.createHash("sha256").update(String(v)).digest("hex") : undefined; const normEmail = (v) => v?.trim().toLowerCase(); const normPhone = (v) => v?.replace(/\D/g, ""); // digits only, incl. country code const normText = (v) => v?.trim().toLowerCase().replace(/[^a-z0-9]/g, ""); app.post("/webhooks/shopify/orders-create", verifyShopifyHmac, async (req, res) => { res.sendStatus(200); // ack fast; process async const order = req.body; // Consent gate — see §7. Set on the order at checkout from Shopify's Customer Privacy API. const attrs = Object.fromEntries((order.note_attributes || []).map(a => [a.name, a.value])); if (attrs.marketing_consent !== "true") return; const c = order.customer || {}; const addr = order.shipping_address || order.billing_address || {}; const payload = { data: [{ event_name: "Purchase", event_time: Math.floor(new Date(order.created_at).getTime() / 1000), event_id: String(order.id), // MUST match the browser Pixel event_id event_source_url: attrs.landing_url || "https://cedarandcoil.com/products/arc-clip-lamp", action_source: "website", user_data: { em: [sha256(normEmail(order.email))], ph: [sha256(normPhone(order.phone || c.phone))], fn: [sha256(normText(addr.first_name || c.first_name))], ln: [sha256(normText(addr.last_name || c.last_name))], ct: [sha256(normText(addr.city))], st: [sha256(normText(addr.province_code))], zp: [sha256(normText(addr.zip)?.slice(0, 5))], country: [sha256(normText(addr.country_code))], external_id: [sha256(c.id)], // NOT hashed — captured in-browser at checkout, persisted onto the order: client_ip_address: attrs.client_ip, client_user_agent: attrs.client_user_agent, fbp: attrs.fbp, fbc: attrs.fbc }, custom_data: { currency: order.currency, // "USD" value: Number(order.current_subtotal_price), // product subtotal, per §2 content_type: "product", content_ids: order.line_items.map(li => `shopify_US_${li.product_id}_${li.variant_id}`), contents: order.line_items.map(li => ({ id: `shopify_US_${li.product_id}_${li.variant_id}`, quantity: li.quantity, item_price: Number(li.price) })), num_items: order.line_items.reduce((n, li) => n + li.quantity, 0), order_id: String(order.id) } }] // , test_event_code: "TEST12345" // ONLY while validating; remove before production }; const r = await fetch( `https://graph.facebook.com/${API_VERSION}/${PIXEL_ID}/events?access_token=${ACCESS_TOKEN}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) } ); if (!r.ok) console.error("CAPI error", r.status, await r.text()); // never log raw PII }); ``` Undefined hashed fields are dropped by `JSON.stringify` — that's intentional. Send only what you actually have. --- ## 6. End-to-End Validation (Before Scaling Spend) Run this checklist on a real test order before any meaningful budget goes live. **A. Pre-flight** - [ ] Domain verified in Business Manager (`cedarandcoil.com`). - [ ] AEM event priority configured, `Purchase` ranked first. - [ ] Catalog connected and `content_ids` in events match feed IDs exactly. **B. Browser layer** - [ ] Meta Pixel Helper on the PDP: `PageView` + `ViewContent` fire once each, correct `content_ids`, `value: 68.00`, `currency: "USD"`. - [ ] Add to cart → `AddToCart` fires once on success, not on button click. - [ ] Begin checkout → `InitiateCheckout` once. - [ ] `_fbp` and `_fbc` cookies present; land on the site with a `?fbclid=test123` and confirm `_fbc` is created. **C. Server layer** - [ ] In Events Manager → **Test Events**, add `test_event_code` to your server payload and place a $68 test order. Confirm the Purchase arrives with correct `value`, `currency`, `content_ids`, `order_id`. - [ ] Confirm hashed fields are recognized (they appear as matched parameters, not errors). - [ ] Remove `test_event_code` before going live. **D. Deduplication proof — the one that matters** - [ ] Place a live (non-test) order. In Events Manager → your dataset → **Events** → open `Purchase` → check the *Received from* breakdown: it should show both Browser and Server, with a **deduplicated** count of 1 for that order. - [ ] Confirm `event_id` on the browser event equals the Shopify order ID. - [ ] After 24h: Meta `Purchase` count vs. Shopify order count for the same day should be close to 1:1. A count materially above your order count means dedup is failing — fix before spending. **E. Data quality** - [ ] **Event Match Quality** score visible for `Purchase`; note the baseline and which parameters are missing. - [ ] **Diagnostics** tab shows no active errors (invalid parameters, missing currency, unhashed PII warnings, deprecated API version). - [ ] Sum of Meta `Purchase` value for a test day ≈ Shopify subtotal for the same orders (per your §2 value definition). - [ ] Repeat once on mobile Safari and once with an ad blocker enabled — confirm the server event still lands and the order still counts exactly once. - [ ] Refresh the thank-you page twice; confirm no extra Purchases. **F. Ongoing** - [ ] Weekly for the first month: order count vs. Meta Purchase count, EMQ trend, Diagnostics tab. - [ ] Alert on webhook handler non-2xx responses from the Graph API. --- ## 7. Consent and Compliance - **Consent gates both paths.** A server webhook fires whether or not the shopper consented — that is exactly why it must check consent explicitly. Capture consent state at checkout via Shopify's **Customer Privacy API**, persist it onto the order (a note attribute or metafield), and have the CAPI handler read it before sending, as sketched above. Deploying CAPI as a way around a consent banner is not a legitimate use. - **Regional obligations.** EU/UK/Switzerland (GDPR/ePrivacy), Canada, and an expanding set of US state laws require notice and, in several cases, opt-in before setting marketing cookies or sharing identifiers. Use a consent management platform integrated with Shopify's customer privacy settings and Meta's consent signals rather than hand-rolling it. For California opt-outs, Meta supports Limited Data Use via `data_processing_options: ["LDU"]` with `data_processing_options_country: 1` and `data_processing_options_state: 1000`. - **Hash everything hashable.** Email, phone, name, address components, and external IDs must be SHA-256 hashed before leaving your server. Raw PII must never appear in Pixel payloads, URL parameters, event names, `content_ids`, or application logs. - **Data minimization.** Send fields that improve matching and that you have a lawful basis to send. Don't append data from other systems just because you can. - **Deletion and access requests.** Have a documented path for honoring deletion requests — Meta provides a deletion endpoint keyed on `external_id`; make sure your customer IDs are traceable. - **Access control.** The CAPI access token is a server-side secret. Store it in environment variables or a secrets manager, scope it to the dataset, and rotate it on staff changes. Never expose it in client code or a Shopify theme file. - **Substantiation.** Whatever the pixel measures, ad copy stays inside approved claims: three brightness settings, two color temperatures, up to eight hours on the lowest brightness, clamps surfaces up to 2.25 inches thick, $68, includes lamp, padded clamp, USB-C cable, and storage sleeve. No reviews, awards, scarcity, environmental, or performance claims. Approved CTA: **Explore the Arc Clip Lamp.** **A note on expectations:** correctly deduplicated Pixel + CAPI gives Meta more complete and better-matched signal than the Pixel alone, which generally improves reporting completeness and optimization inputs. The size of that difference depends on your traffic mix, browser and device distribution, consent rates, and match quality — it is not a fixed number, and this guide deliberately does not forecast one. Establish your own baseline from the validation steps in §6, then measure changes against it.
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 with a shared event_id for dedup and a table explaining why each is needed under browser privacy limits.
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 table lists ViewContent, AddToCart, InitiateCheckout, and Purchase with required/recommended params, and Purchase explicitly requires value, currency, and content_ids.
code_sketch
A concrete server-side Purchase event code sketch or request example is included showing event_name, event_time, event_id, action_source, and a user_data block.
✓The Node.js webhook handler sets event_name, event_time, event_id, action_source, and a fully populated user_data block.
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 Events Manager Test Events with a test_event_code and explicitly checks the 'Received from' breakdown for a deduplicated count of 1.
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).
✓Section 5 clarifies Purchase should be sourced from the Shopify orders/create webhook (server truth) rather than relying solely on the thank-you page, while browser events are described as firing on PDP/cart/checkout actions.
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 closing note explicitly avoids promising a fixed attribution-recovery number ('it is not a fixed number, and this guide deliberately does not forecast one') and Section 7 frames consent/regional rules as constraints on what 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 states dedup requires identical event_name and event_id across browser and server events, which Meta uses to drop the duplicate.
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 instructs using the stable Shopify order ID as event_id for Purchase, reused identically on both paths, avoiding per-send random 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.
✓event_time is computed from order.created_at (`Math.floor(new Date(order.created_at).getTime() / 1000)`) 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 and the code sketch normalize (trim/lowercase) and SHA-256 hash email, phone, name, and address fields before sending in user_data.
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, decisive recommendation ('Start with Option A — the native Meta sales channel with Maximum data sharing') with concrete setup steps and escalation criteria.

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.050 · 80.1s · 9.4k tok
# Meta Conversion Tracking Implementation Guide ## Cedar & Coil Arc Clip Lamp – Shopify Store --- ## (1) Recommended Architecture: Browser Pixel + Server-Side CAPI with Deduplication ### Why Both Are Required **Browser Meta Pixel (client-side)** - Captures user behavior in real time as it happens on your site - Fires events like `ViewContent` and `AddToCart` before checkout begins - Enables real-time audience building for retargeting - Resilient during network delays or redirects to payment processors - Limitation: browsers increasingly block or delay third-party cookies; iOS Safari and Firefox restrict tracking; users may clear cookies between sessions **Conversions API (server-side)** - Fires from your Shopify backend directly to Meta after events occur (no browser required) - Survives ad blockers, Safari ITP, Firefox ETP, and cookie deletion - Allows you to send hashed customer information (email, phone, address) for better match rates - Critical for Purchase events: server-side confirmation is more reliable than client-side - Limitation: requires development effort and careful data hygiene **Deduplication prevents counting the same conversion twice** — once when the browser pixel fires and again when your server sends the same event to Meta. This keeps your conversion counts honest and your ROAS calculations accurate. ### Architecture Diagram ``` User visits site ↓ Browser Meta Pixel fires (ViewContent, AddToCart, InitiateCheckout) ↓ User completes purchase ↓ Shopify webhook triggers ↓ Server-side code hashes customer data + sends Purchase to CAPI ↓ Meta deduplicates browser Purchase event (if it fired) against server Purchase ↓ Single, deduplicated Purchase event recorded ``` ### Result For Cedar & Coil: You'll see conversions survive iOS, Firefox, and ad blockers; you'll have better match rates on retargeting audiences because you're sending hashed email; and your attribution won't double-count purchases. --- ## (2) Standard Events to Send: ViewContent, AddToCart, InitiateCheckout, Purchase ### ViewContent **When:** User lands on the Arc Clip Lamp product page or detail page **Trigger:** Browser pixel (client-side) **Required parameters:** - `value` – Product price (68 for Arc Clip Lamp) - `currency` – "USD" - `content_name` – "Arc Clip Lamp" - `content_id` – Your internal SKU or product ID (e.g., `arc-clip-lamp-001`) - `content_type` – "product" **Example (browser):** ```javascript fbq('track', 'ViewContent', { value: 68, currency: 'USD', content_name: 'Arc Clip Lamp', content_id: 'arc-clip-lamp-001', content_type: 'product' }); ``` --- ### AddToCart **When:** Customer clicks "Add to Cart" button **Trigger:** Browser pixel (client-side) **Required parameters:** - `value` – Product price (68) - `currency` – "USD" - `content_name` – "Arc Clip Lamp" - `content_id` – SKU/product ID - `content_type` – "product" **Example (browser):** ```javascript fbq('track', 'AddToCart', { value: 68, currency: 'USD', content_name: 'Arc Clip Lamp', content_id: 'arc-clip-lamp-001', content_type: 'product' }); ``` --- ### InitiateCheckout **When:** Customer clicks "Proceed to Checkout" or lands on checkout page **Trigger:** Browser pixel (client-side) **Required parameters:** - `value` – Total cart value (may be >68 if multiple items or discounts applied) - `currency` – "USD" - `content_name` – "Arc Clip Lamp" (or comma-separated if multiple SKUs) - `content_id` – SKU or array of SKUs - `content_type` – "product" or "product_group" - `num_items` – Total items in cart **Example (browser):** ```javascript fbq('track', 'InitiateCheckout', { value: 68, currency: 'USD', content_name: 'Arc Clip Lamp', content_id: 'arc-clip-lamp-001', content_type: 'product', num_items: 1 }); ``` --- ### Purchase (Browser + Server-Side) **When:** Order is confirmed **Trigger:** Browser pixel + server-side CAPI (both, with deduplication) #### Browser Version (fires immediately on order confirmation page) **Required parameters:** - `value` – Total order value (including any applied discounts but before shipping/tax if your model separates them) - `currency` – "USD" - `content_name` – "Arc Clip Lamp" - `content_id` – SKU - `content_type` – "product" - `num_items` – Quantity purchased - `transaction_id` – Unique order/transaction ID (e.g., Shopify order ID) — **critical for deduplication** **Example (browser):** ```javascript fbq('track', 'Purchase', { value: 68, currency: 'USD', content_name: 'Arc Clip Lamp', content_id: 'arc-clip-lamp-001', content_type: 'product', num_items: 1, transaction_id: 'order-123456789' }); ``` #### Server-Side Version (fires from Shopify backend via webhook) Same parameters as browser, but you also send: - **Hashed customer data** (email, phone, address) - **eventID** matching the browser pixel's eventID — **this is how deduplication works** See section (5) for code sketch. --- ## (3) How Deduplication Works Between Pixel and CAPI ### The Deduplication Mechanism Meta matches a browser pixel event to a server-side CAPI event using two fields: 1. **`eventID`** – A unique identifier you generate and attach to both the browser pixel event and the server-side CAPI request for the same action 2. **Timestamp** – Events fired within a short window (typically seconds to a few minutes) are considered the same event ### Browser Pixel Side: Attach `eventID` ```javascript // Generate or retrieve a unique event ID (e.g., UUID) const eventID = generateUUID(); // e.g., "a1b2c3d4-e5f6-7890-abcd-ef1234567890" fbq('track', 'Purchase', { value: 68, currency: 'USD', content_name: 'Arc Clip Lamp', content_id: 'arc-clip-lamp-001', content_type: 'product', num_items: 1, transaction_id: 'order-123456789', eventID: eventID // Send to Meta Pixel }); // Store eventID in localStorage or session for server-side retrieval sessionStorage.setItem('purchase_eventID', eventID); ``` ### Server-Side CAPI: Send Same `eventID` When your Shopify webhook fires and you send to CAPI: ```javascript // Retrieve or regenerate the same eventID // (If this is a webhook-only flow, you'll generate a new eventID server-side, // but if you embedded the eventID in the order metadata from the browser, // retrieve it from the Shopify order object) const eventID = order.metafields?.find(m => m.key === 'purchase_event_id')?.value || generateUUID(); const payload = { data: [ { event_name: 'Purchase', event_time: Math.floor(Date.now() / 1000), // Unix timestamp event_id: eventID, // Same eventID as browser pixel action_source: 'website', user_data: { em: hashEmail(order.email), // Hashed SHA-256 ph: hashPhone(order.phone), // Hashed SHA-256 fn: hashFirstName(order.firstName), ln: hashLastName(order.lastName), ct: hashCity(order.shippingAddress.city), st: hashState(order.shippingAddress.province), zp: hashZip(order.shippingAddress.zip), country: hashCountry(order.shippingAddress.countryCode) }, custom_data: { value: order.total, currency: 'USD', content_name: 'Arc Clip Lamp', content_ids: ['arc-clip-lamp-001'], content_type: 'product', num_items: order.lineItems.length } } ], access_token: META_ACCESS_TOKEN }; // POST to Meta Conversions API fetch('https://graph.facebook.com/v18.0/{PIXEL_ID}/events', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); ``` ### How Meta Deduplicates 1. Meta receives the browser pixel event with `eventID: "a1b2c3d4-..."` and timestamp `T` 2. Meta receives the server-side CAPI event with the same `eventID: "a1b2c3d4-..."` and timestamp close to `T` 3. Meta recognizes these as the same event and counts it once (not twice) 4. If only the browser event arrived, it's counted 5. If only the server event arrived, it's counted 6. Both arriving: counted once; credit goes to the server event (because it includes hashed customer data) ### Best Practice for Cedar & Coil - Use **Shopify's built-in webhooks** (order/created) to trigger server-side CAPI calls - Store the browser `eventID` in the Shopify order's metafields before checkout completes, so the webhook can retrieve it - If you can't retrieve the browser `eventID`, generate a consistent `eventID` server-side based on the order ID and timestamp (e.g., `sha256(order_id + timestamp)`) — Meta will still deduplicate if the times are very close - Always include `event_id` in server-side calls; never rely on browser pixel alone for Purchase events --- ## (4) Customer Information: Preparation Before Sending Server-Side ### Data You Need from the Order Capture these fields from the Shopify order object and hash them before sending to Meta: | Field | Source | Hash Algorithm | Notes | |-------|--------|-----------------|-------| | Email | `order.email` | SHA-256 (lowercase before hash) | Primary identifier | | Phone | `order.phone` | SHA-256 (E.164 format: +1XXXXXXXXXX, remove non-digits, then hash) | Secondary identifier | | First Name | `order.shippingAddress.firstName` or `order.billingAddress.firstName` | SHA-256 (lowercase before hash) | Optional but improves matching | | Last Name | `order.shippingAddress.lastName` | SHA-256 (lowercase before hash) | Optional | | City | `order.shippingAddress.city` | SHA-256 (lowercase before hash) | Optional | | State/Province | `order.shippingAddress.province` | SHA-256 (2-letter code, lowercase) | Optional; use province code for Canada | | Zip/Postal Code | `order.shippingAddress.zip` | SHA-256 (remove spaces, lowercase) | Optional | | Country | `order.shippingAddress.countryCode` | SHA-256 (ISO 2-letter code, lowercase) | Optional | ### Hashing Function (Node.js / JavaScript) ```javascript const crypto = require('crypto'); function hashField(value) { if (!value) return null; return crypto .createHash('sha256') .update(String(value).toLowerCase().trim()) .digest('hex'); } function hashEmail(email) { if (!email) return null; return hashField(email); } function hashPhone(phone) { if (!phone) return null; // Normalize to E.164: +1 country code, 10 digits const digitsOnly = String(phone).replace(/\D/g, ''); const formatted = digitsOnly.startsWith('1') ? digitsOnly.slice(-10) : digitsOnly; return hashField(formatted); } function prepareCustomerData(order) { return { em: hashEmail(order.email), ph: hashPhone(order.phone), fn: hashField(order.shippingAddress.firstName), ln: hashField(order.shippingAddress.lastName), ct: hashField(order.shippingAddress.city), st: hashField(order.shippingAddress.province), zp: hashField(order.shippingAddress.zip), country: hashField(order.shippingAddress.countryCode) }; } ``` ### Data Quality Rules - **Remove whitespace** before hashing: `" john@example.com "` → `"john@example.com"` → hash - **Lowercase everything** before hashing - **Skip null/empty fields** — send only fields you have - **Never send raw (unhashed) PII** to Meta in any request - **Validate email format** before hashing (optional but recommended) - **Phone number normalization**: strip punctuation, convert to digits, ensure country code is valid ### Example: Prepared Customer Data Object ```javascript { em: 'a1f2c3b4d5e6f7a8b9c0d1e2f3a4b5c6', // hashed email ph: 'e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6', // hashed phone fn: 'b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9', // hashed first name ln: 'c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2', // hashed last name ct: 'd0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5', // hashed city st: 'e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8', // hashed state (2-letter) zp: 'f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1', // hashed zip country: 'a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4' // hashed country code } ``` --- ## (5) Shopify Setup Path: Native Meta Sales Channel vs. Custom Implementation ### Option A: Native Meta Sales Channel App (Built-in to Shopify) **Pros:** - Installed directly from Shopify App Store; no coding required - Meta Pixel automatically injected into your store - Basic Conversions API integration included - Automatic product catalog sync to Meta - Minimal ongoing maintenance **Cons:** - Limited customization; harder to control which events fire and when - Deduplication configuration is opaque; you must trust Shopify's implementation - Less granular control over customer data hashing - Server-side CAPI integration is simplified but may not handle all edge cases (e.g., complex discount structures) - Debugging is harder if events stop firing **Best for:** Non-technical teams, simple product catalogs, want "set and forget" tracking --- ### Option B: Custom Implementation (Recommended for Cedar & Coil) **Pros:** - Full control over event firing logic; you decide what gets tracked and when - Explicit deduplication: you manage event IDs and know exactly how data flows - Custom server-side logic: handle Shopify order workflows, custom discounts, bundle products - Better debugging and monitoring; you own the code - Easier to adapt as your product line grows (e.g., add new SKUs, handle variants) **Cons:** - Requires developer time to build and test - Ongoing maintenance if Shopify or Meta APIs change - Your team must monitor and fix issues **Best for:** DTC brands that want clean, auditable tracking and plan to scale; Cedar & Coil fits here --- ### Recommendation: Custom Implementation for Cedar & Coil Given that: - Cedar & Coil is building a DTC brand with one flagship product initially - Precision in conversion tracking directly impacts paid media spend decisions - You need reliable deduplication to avoid inflated ROAS claims - You may add variants and new products soon (custom logic scales better) **→ Use custom implementation.** It takes 1–2 weeks for a developer to set up and test, but you'll have transparent, reliable tracking that you fully own. --- ### Concrete Shopify Setup: Custom Implementation Code Sketch #### Step 1: Install Meta Pixel in the store (browser-side) In your Shopify theme's `theme.liquid` or via Google Tag Manager: ```html <!-- Meta Pixel Code --> <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> ``` Replace `YOUR_PIXEL_ID` with your Meta Pixel ID. #### Step 2: Track ViewContent on product page In your product template (e.g., `product.liquid`): ```javascript <script> const productData = { value: {{ product.price | divided_by: 100.0 }}, currency: 'USD', content_name: '{{ product.title | escape_javascript }}', content_id: '{{ product.id }}', content_type: 'product' }; fbq('track', 'ViewContent', productData); </script> ``` #### Step 3: Track AddToCart In your cart/add-to-cart handler (JavaScript in your theme or via GTM): ```javascript document.addEventListener('submit', function(event) { const form = event.target; if (form.classList.contains('product-form')) { // Get product data from page (or form hidden fields) const productPrice = parseFloat(form.dataset.price); const productId = form.dataset.productId; fbq('track', 'AddToCart', { value: productPrice, currency: 'USD', content_name: form.dataset.productName, content_id: productId, content_type: 'product' }); } }); ``` #### Step 4: Track InitiateCheckout In your checkout button or cart page: ```javascript document.getElementById('checkout-button').addEventListener('click', function() { const cartTotal = parseFloat(document.getElementById('cart-total').innerText); fbq('track', 'InitiateCheckout', { value: cartTotal, currency: 'USD', content_name: 'Arc Clip Lamp', content_id: 'arc-clip-lamp-001', content_type: 'product', num_items: 1 }); }); ``` #### Step 5: Browser-Side Purchase Event + Generate eventID On your order confirmation page (Shopify post-purchase): ```javascript <script> // Generate and store eventID for deduplication function generateUUID() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } const eventID = generateUUID(); sessionStorage.setItem('purchase_eventID', eventID); fbq('track', 'Purchase', { value: {{ order.total | divided_by: 100.0 }}, currency: 'USD', content_name: 'Arc Clip Lamp', content_id: 'arc-clip-lamp-001', content_type: 'product', num_items: {{ order.line_items | size }}, transaction_id: '{{ order.id }}', eventID: eventID }); </script> ``` #### Step 6: Server-Side CAPI Purchase Event (Node.js + Shopify Webhooks) Set up a webhook endpoint on your backend that listens to `order/created` or `order/paid` events. **Express.js Example:** ```javascript const express = require('express'); const crypto = require('crypto'); const axios = require('axios'); const app = express(); app.use(express.json()); // Your Meta Pixel ID and Access Token const META_PIXEL_ID = 'YOUR_PIXEL_ID'; const META_ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN'; // Hashing function function hashField(value) { if (!value) return null; return crypto .createHash('sha256') .update(String(value).toLowerCase().trim()) .digest('hex'); } // Shopify webhook handler app.post('/webhooks/orders/create', async (req, res) => { const order = req.body; try { // Prepare customer data const userData = { em: hashField(order.email), ph: hashField(order.phone), fn: hashField(order.shipping_address.first_name), ln: hashField(order.shipping_address.last_name), ct: hashField(order.shipping_address.city), st: hashField(order.shipping_address.province_code), zp: hashField(order.shipping_address.zip), country: hashField(order.shipping_address.country_code) }; // Remove null values Object.keys(userData).forEach(key => userData[key] === null && delete userData[key] ); // Generate or retrieve eventID // (In production, you'd retrieve this from order metafields if stored there) const eventID = crypto .createHash('sha256') .update(`${order.id}-${order.created_at}`) .digest('hex'); // Prepare CAPI payload const payload = { data: [ { event_name: 'Purchase', event_time: Math.floor(new Date(order.created_at).getTime() / 1000), event_id: eventID, action_source: 'website', user_data: userData, custom_data: { value: parseFloat(order.total_price), currency: 'USD', content_name: 'Arc Clip Lamp', content_ids: order.line_items.map(item => String(item.product_id)), content_type: 'product', num_items: order.line_items.reduce((sum, item) => sum + item.quantity, 0) } } ], access_token: META_ACCESS_TOKEN }; // Send to Meta Conversions API const response = await axios.post( `https://graph.facebook.com/v18.0/${META_PIXEL_ID}/events`, payload ); console.log('Meta CAPI Purchase event sent:', response.data); res.status(200).json({ success: true, meta_response: response.data }); } catch (error) { console.error('Error sending to Meta CAPI:', error.response?.data || error.message); res.status(500).json({ error: 'Failed to send to Meta CAPI' }); } }); app.listen(3000, () => console.log('Webhook server running on port 3000')); ``` **Shopify Setup:** 1. Go to **Settings > Apps and integrations > Webhooks** 2. Create a new webhook for **Order creation** → POST to your endpoint (e.g., `https://yourserver.com/webhooks/orders/create`) 3. Shopify will send order data when a new order is created 4. Your code hashes PII, calls Meta's Conversions API, and deduplicates --- ## (6) Validation: End-to-End Testing Before Scaling Spend ### Pre-Launch Checklist #### Browser Pixel Validation - [ ] **Meta Pixel fires on page load** - Use Meta's Pixel Helper browser extension or your browser's Network tab - Confirm: `fbq.js` loads, init event fires with correct Pixel ID - [ ] **ViewContent fires on product page** - Navigate to Arc Clip Lamp product page - Open browser console → type `fbq` to confirm library is loaded - Check Network tab for POST to `facebook.com` with event type `ViewContent` - Confirm parameters: `value`, `currency`, `content_id`, `content_name` are present and correct - [ ] **AddToCart fires when item is added** - Add product to cart - Check Network tab for `AddToCart` event - Verify `transaction_id` is NOT present (it's only for Purchase) - [ ] **InitiateCheckout fires on checkout** - Click "Checkout" - Confirm `InitiateCheckout` event fires with cart total value - [ ] **Purchase fires on order confirmation** - Complete a test purchase (use Shopify test gateway) - Confirm Purchase event fires with `transaction_id` (order ID) and `eventID` - Check that value, currency, content_id, and num_items are correct **Testing Tools:** - [Meta Pixel Helper](https://chrome.google.com/webstore/detail/meta-pixel-helper/fdgodglkcjdnfkhgbljbndfeejjhbmeg) (Chrome extension) - Browser DevTools → Network tab → filter for `facebook.com` - Shopify test payment gateway: [Shopify docs](https://help.shopify.com/en/manual/admin-api/development/testing) --- #### Server-Side CAPI Validation - [ ] **Webhook endpoint receives Shopify order** - Create a test order - Check server logs: confirm webhook POST is received with full order object - Verify `email`, `shipping_address`, `line_items`, `total_price` are present - [ ] **Customer data is hashed correctly** - Log the prepared `userData` object before sending to Meta - Confirm: all fields are either SHA-256 hashes (64 hex characters) or null - Verify: no raw emails, phone numbers, or names in logs or network traffic - [ ] **CAPI request payload is well-formed** - Log the full payload before sending - Confirm: `event_name`, `event_time`, `event_id`, `action_source`, `user_data`, `custom_data` are all present - Verify: no syntax errors (valid JSON) - [ ] **Meta CAPI accepts the request** - Check HTTP response: should be `200` with JSON like `{"events_received": 1, "fbtrace_id": "..."}` - If error: check Meta's [CAPI error codes](https://developers.facebook.com/docs/marketing-api/conversions-api/get-started) and fix (common: invalid access token, missing required fields) - [ ] **Deduplication works** - Place test order - Confirm both browser Purchase event and server CAPI event fire - Wait 2–3 minutes - Check Meta Ads Manager → Conversions: count should show **1 Purchase**, not 2 - (Deduplication takes a few minutes to settle; don't panic if you see 2 initially) **Testing Tools:** - Server logs: add `console.log()` or structured logging (Winston, Bunyan) - [Postman](https://www.postman.com/) or `curl` to manually test CAPI endpoint - Meta Conversions API [Test Events](https://developers.facebook.com/docs/marketing-api/conversions-api/get-started#test-events) — send test event to `test_event_code` instead of your real Pixel ID - Meta Ads Manager → Conversions: check event count and recent events (1–2 hour delay) --- #### Integration Testing (End-to-End) - [ ] **Consent mode is set up (if applicable)** - If you have a consent banner: confirm pixel fires only after user consents to analytics - Shopify + Privy/OneTrust: test that consent mode blocks pixel until consent is given - [ ] **Mobile and desktop both work** - Test on iPhone Safari, Android Chrome, desktop Chrome, Firefox - Confirm pixel and webhook both fire on all browsers - Verify: iOS doesn't break server-side (it won't; CAPI is backend-only) - [ ] **Test orders with discounts, tax, shipping** - Create order with promo code: confirm `value` sent to Meta is the final amount (post-discount or pre-discount, depending on your model — decide and document) - Create order with shipping: confirm `value` is consistent - Verify: tax handling is documented (Meta doesn't care if tax is included or not; just be consistent) - [ ] **Variant handling** - If Arc Clip Lamp has color/finish variants, confirm `content_id` in events matches your variant SKU, not just the product ID - Test order with variant: confirm CAPI receives correct content_id - [ ] **High-traffic dry run** - Enable pixel and CAPI on your live store for 48 hours *without* spending on ads - Monitor: no errors in logs, CAPI responses are all 200, conversions appear in Meta Ads Manager - Check deduplication: conversion count is reasonable (not double or suspiciously high) --- ### Monitoring After Launch - [ ] **Set up alerts** - Server logs: alert if webhook endpoint returns non-200 status - CAPI error rate: alert if >5% of requests fail - Event count: alert if daily Purchase events drop 50% vs. Shopify order count - [ ] **Daily sanity check (first 2 weeks)** - Manually verify 2–3 test purchases fire events in both pixel and CAPI - Spot-check Meta Conversions: count matches Shopify order count (roughly; 1–2 hour delay expected) - Review logs for any hashing or API errors - [ ] **Weekly audit (ongoing)** - Compare Shopify order count vs. Meta Purchase conversion count: should be similar (deduplication means you may see slightly fewer conversions in Meta if some users block pixel) - Check CAPI latency: average time between Shopify webhook and Meta receipt should be <5 seconds - Spot-check: are variants, discounts, and multi-item carts being tracked correctly? --- ## (7) Consent and Compliance ### GDPR, CCPA, and Privacy Regulations **You must:** 1. **Obtain explicit consent before firing Meta Pixel (browser)** - In EU/UK: Implement a consent banner (e.g., Privy, OneTrust, Shopify's built-in GDPR consent) - Pixel must not fire until user accepts "Marketing" or "Analytics" cookies - CCPA (California): Users have a right to opt-out; provide a link to Meta's Opt-Out 2. **Use Meta's Consent Mode (Google's standard)** - Enable `gtag('consent', 'default', {...})` to defer pixel until consent - Configure: `analytics_storage: 'denied'` by default, then enable after consent - This satisfies browser privacy (Safari ITP, Firefox ETP) and legal requirements 3. **Hash customer data server-side (CAPI)** - GDPR requires data minimization; Meta's CAPI requires hashes, not raw PII - Never send raw email, phone, or address to Meta - Hashing is cryptographic one-way; Meta cannot reverse it to identify individuals - Document your hashing process for GDPR Data Processing Agreement (DPA) 4. **Establish a Data Processing Agreement (DPA) with Meta** - Required if you're in EU/UK and using Meta Pixel + CAPI - Meta provides a template; sign it and keep on file - Confirms that you, not Meta, are responsible for obtaining consent 5. **Update your Privacy Policy** - Disclose: you use Meta Pixel for conversion tracking and retargeting - Mention: customer data (email, phone, address) is hashed before sent to Meta - Link to Meta's Data Privacy: https://www.facebook.com/policies/cookies/ - Clarify: user choice to opt-out (link to their Meta Ads Preferences) 6. **Don't send sensitive data to Meta** - Health data, financial info, SSN, etc.: do not send even hashed - Stick to: name, email, phone, postal address (for matching purposes only) ### Shopify + Meta Integration Compliance - **Shopify's built-in consent controls** handle most compliance if you use them: - Shopify → Settings → Customer Privacy → enable GDPR/CCPA - This auto-blocks pixel and CAPI until consent is given - **Meta's CAPI terms**: By sending data to CAPI, you confirm: - You have authorization to send customer data to Meta - You've obtained explicit consent (or have a legal basis) to do so - You will hash all PII - **Test compliance**: - Use a VPN set to EU IP → visit your store → confirm no pixel fires until you click "Accept" - Use an incognito browser → confirm consent banner appears on first visit - Verify: no raw PII in network requests (search for email, phone in Network tab; should find none) ### Cedar & Coil Specific Notes - Cedar & Coil is a US-based DTC brand; **CCPA (California) and CAN-SPAM (email marketing)** are primary concerns - If you operate in EU (selling to EU customers) or Canada: GDPR and PIPEDA apply as well - **Recommended approach for Cedar & Coil**: 1. Use Shopify's built-in customer privacy consent (free, GDPR/CCPA-ready) 2. Implement Meta Pixel + CAPI with consent gates (pixel defers, CAPI only fires after webhook, no browser block needed) 3. Draft a simple privacy policy update: "We use Meta Pixel and the Meta Conversions API for conversion tracking and retargeting. Customer email and phone are hashed before sent to Meta." 4. Request a DPA with Meta (free; go to Meta Business Account → Settings → Data Processing Terms) 5. Document: how you obtain consent (checkbox at checkout or banner), hashing method, and retention policy ### No Promises on Attribution Recovery - **Transparent statement to stakeholders**: "Server-side CAPI + browser pixel with deduplication improves conversion tracking resilience compared to browser-only. However, we do not claim to recover a specific percentage of lost conversions due to privacy restrictions (iOS Safari, Firefox, ad blockers). We measure real conversions; privacy regulations and user choice limit what we can see." - Track and compare: pre-CAPI vs. post-CAPI conversion count and ROAS, but attribute differences to improved tracking accuracy, not "recovery." --- ## Summary Checklist for Implementation - [ ] Install Meta Pixel on Shopify store (theme.liquid) - [ ] Implement browser events: ViewContent, AddToCart, InitiateCheckout, Purchase - [ ] Set up Shopify webhook for `order/created` → backend endpoint - [ ] Build server-side CAPI Purchase event with hashed customer data - [ ] Implement deduplication: generate and pass eventID in both browser and CAPI - [ ] Test browser pixel with Meta Pixel Helper - [ ] Test CAPI with Postman and server logs - [ ] Test deduplication: place order, confirm 1 conversion in Meta (not 2) - [ ] Implement consent mode (banner + Shopify privacy settings) - [ ] Update privacy policy - [ ] Request and sign Meta DPA - [ ] Validate on desktop, mobile, multiple browsers - [ ] Set up monitoring and alerts - [ ] Launch with 48-hour live test before scaling spend --- **Document Version:** 1.0 **Last Updated:** [Current Date] **Owner:** Technical Marketing Lead, Cedar & Coil
Score the judge's verdict, criterion by criterion10/11 criteria passed · failed: 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 explains browser Pixel and server-side CAPI need, citing iOS Safari, Firefox ETP, ad blockers as reasons both are required, with deduplication called out.
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 with value, currency, and content_id/content_ids parameters, including content_ids as an array in the server-side Purchase custom_data.
code_sketch
A concrete server-side Purchase event code sketch or request example is included showing event_name, event_time, event_id, action_source, and a user_data block.
✓The Express.js webhook handler in section 5 includes event_name: 'Purchase', event_time, event_id, action_source: 'website', and a full user_data block 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 instructs using Meta's Test Events (test_event_code) and Pixel Helper, and explicitly checks 'Meta Ads Manager → Conversions: count should show 1 Purchase, not 2' to confirm deduplication.
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).
✓Each event lists 'Trigger: Browser pixel (client-side)' except Purchase, which is explicitly 'Browser pixel + server-side CAPI' fired from a Shopify order webhook, with the guide stating to 'never rely on browser pixel alone for Purchase 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.
✓The guide explicitly states 'we do not claim to recover a specific percentage of lost conversions' and details GDPR/CCPA consent gating as constraints on what 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.
✓The guide states the same eventID must be attached to both the browser pixel Purchase call and the server_side event_id field so 'Meta recognizes these as the same event and counts it once (not twice).'
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 concrete webhook code independently derives event_id via `sha256(order.id + order.created_at)` rather than actually retrieving/sharing the browser's randomly generated UUID stored in sessionStorage, so the IDs would not match between Pixel and CAPI despite being stable 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 final server-side Purchase code sketch uses `Math.floor(new Date(order.created_at).getTime() / 1000)` for event_time, deriving from the order's own 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.
✓The hashField function normalizes input via `.toLowerCase().trim()` before applying SHA-256 hashing for all customer 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 directly recommends 'Use custom implementation' for Cedar & Coil with reasoning, followed by concrete numbered setup steps (theme.liquid pixel install, webhook creation, Express handler).