← Run 20260826-212336-e68672f4
Shopify to Meta ads conversion tracking implementation
task shopify-meta-capiAug 26, 2026skill analytics

Answers & verdicts

GPT-5.6 Sol high 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.83 · 195.0s · 10.4k tok
# Cedar & Coil: Shopify-to-Meta Conversion Tracking Guide ## 1. Recommended architecture: Meta Pixel + Conversions API Use one Meta dataset/pixel with two coordinated event paths: ```text Shopify storefront/checkout │ ├── Browser path: Meta Pixel │ └── Immediate storefront and checkout events │ └── Server path: Meta Conversions API └── Events sent by Shopify or Cedar & Coil’s server │ └── Meta deduplicates matching copies ``` ### Why both are needed **The browser Meta Pixel provides:** - Immediate, low-latency interaction signals. - Browser context such as the page URL, user agent, `_fbp`, and `_fbc`. - Straightforward coverage for product views, cart actions, and checkout starts. **Conversions API provides:** - A second path that is less dependent on the browser, thank-you page, ad blockers, or client-side script execution. - A reliable server-triggered `Purchase` from the Shopify order lifecycle. - Better access to permitted customer matching fields from the completed order. Shopify’s native Meta integration supports the Meta Pixel and Conversions API at its Enhanced and Maximum data-sharing levels. Shopify specifically notes that server-to-server events are not blocked by browser-based ad blockers. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) CAPI should **supplement, not replace, the Pixel**. The Pixel has useful browser and click context that an order webhook might not contain, while CAPI can still report a completed order when the browser event is unavailable. CAPI is not a mechanism for bypassing consent. ### Operating rule For any customer action sent through both paths: 1. Send the same Meta standard event name. 2. Send the same unique event ID. 3. Send both copies to the same Meta dataset/pixel. 4. Let Meta deduplicate them. --- ## 2. Events and required parameters Use Meta’s standard event names exactly as written: | Meta event | Shopify trigger | Recommended parameters | |---|---|---| | `ViewContent` | Product detail page for the Arc Clip Lamp | `content_ids`, `content_type`, `content_name`, `value`, `currency`, optionally `contents` | | `AddToCart` | Arc Clip Lamp is successfully added to the cart | `content_ids`, `content_type`, `value`, `currency`, `contents` | | `InitiateCheckout` | Customer begins Shopify checkout | `content_ids`, `content_type`, `value`, `currency`, `contents`, `num_items` | | `Purchase` | Completed or paid Shopify order, according to the chosen purchase definition | `content_ids`, `content_type`, `value`, `currency`, `contents`, `order_id` | Shopify exposes corresponding customer events named `product_viewed`, `product_added_to_cart`, `checkout_started`, and `checkout_completed`. The completed-checkout payload includes the order, line items, total price, currency, and customer information where the integration has the required protected-data access. ([shopify.dev](https://shopify.dev/docs/api/web-pixels-api/standard-events?utm_source=openai)) ### `ViewContent` Trigger when the Arc Clip Lamp product detail page is viewed. ```json { "content_ids": ["<META_CATALOG_ITEM_ID>"], "content_type": "product", "content_name": "Arc Clip Lamp", "value": 68.00, "currency": "USD", "contents": [ { "id": "<META_CATALOG_ITEM_ID>", "quantity": 1, "item_price": 68.00 } ] } ``` Use the live product or variant price rather than permanently hardcoding `$68` if discounts, markets, or product pricing can change. ### `AddToCart` Trigger only after Shopify confirms that the cart operation succeeded—not merely when the button is clicked. ```json { "content_ids": ["<META_CATALOG_ITEM_ID>"], "content_type": "product", "value": 68.00, "currency": "USD", "contents": [ { "id": "<META_CATALOG_ITEM_ID>", "quantity": 1, "item_price": 68.00 } ] } ``` If two lamps are added in one action, use quantity `2` and a value of `136.00`. ### `InitiateCheckout` Use the entire checkout, not just the Arc Clip Lamp line that led to it. ```json { "content_ids": ["<META_CATALOG_ITEM_ID>"], "content_type": "product", "value": 68.00, "currency": "USD", "num_items": 1, "contents": [ { "id": "<META_CATALOG_ITEM_ID>", "quantity": 1, "item_price": 68.00 } ] } ``` Meta’s server-side data model identifies `num_items` as an `InitiateCheckout` parameter. ([github.com](https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/src/objects/serverside/custom-data.js)) ### `Purchase` Build this from the actual Shopify order: ```json { "content_ids": ["<META_CATALOG_ITEM_ID>"], "content_type": "product", "value": 73.61, "currency": "USD", "order_id": "gid://shopify/Order/1234567890", "contents": [ { "id": "<META_CATALOG_ITEM_ID>", "quantity": 1, "item_price": 68.00 } ] } ``` Requirements: - **`value`:** Use the actual order/checkout total according to one documented rule. Shopify’s native integration uses the total including applicable duties, taxes, and discounts. Do not simply send `$68` if tax, shipping, discounts, or multiple quantities changed the final total. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) - **`currency`:** Use the order’s ISO currency, normally `USD`. - **`content_ids`:** Include every purchased catalog item ID. - **`contents`:** Include each item’s catalog ID, quantity, and item price. - **`order_id`:** Use Shopify’s stable order ID. - **`content_type`:** Usually `product` for product or variant-level catalog items. Meta supports `content_ids`, `contents`, `content_type`, `value`, `currency`, and `order_id` in CAPI custom data. ([github.com](https://github.com/facebookincubator/Facebook-Server-Side-API-Swagger/blob/main/server-side-api.yaml?utm_source=openai)) ### Critical catalog-ID rule `content_ids` must exactly match the item identifiers in Cedar & Coil’s Meta catalog. Do not mix: - Shopify product IDs, - Shopify variant IDs, - SKUs, - GraphQL GIDs, and - catalog-generated IDs. Choose the identifier format used by the synced Meta catalog and apply it consistently to all four events. Inspect an Arc Clip Lamp item in Commerce Manager to confirm the exact ID. --- ## 3. Exactly how Pixel–CAPI deduplication works Meta deduplicates browser and server copies using the combination of: - Browser `event` ↔ server `event_name` - Browser `eventID` ↔ server `event_id` Both values must match exactly. Meta’s documented deduplication window is 48 hours. ([github.com](https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/src/objects/serverside/server-event.js)) ### Example: one Purchase reported twice but counted once Browser: ```javascript fbq( 'track', 'Purchase', { value: 73.61, currency: 'USD', content_ids: ['<META_CATALOG_ITEM_ID>'], content_type: 'product' }, { eventID: 'purchase:gid://shopify/Order/1234567890' } ); ``` Server: ```json { "event_name": "Purchase", "event_id": "purchase:gid://shopify/Order/1234567890" } ``` Meta receives two transport copies of one business event and treats them as one conversion event. ### Recommended event-ID convention ```text view:<UUID> add_to_cart:<UUID> checkout:<SHOPIFY_CHECKOUT_TOKEN> purchase:<SHOPIFY_ORDER_GID> ``` For `Purchase`, Shopify’s `checkout_completed` event exposes `checkout.order.id`, while the order webhook exposes `admin_graphql_api_id`. Both represent the Shopify order GID, making it a suitable stable deduplication key. ([shopify.dev](https://shopify.dev/docs/api/web-pixels-api/standard-events/checkout_completed)) ### Implementation requirements - Generate one ID per actual customer action. - Reuse that ID on both browser and server copies. - Reuse the same ID on retries. - Never generate a new ID every time a server request is retried. - Do not reuse one ID across separate add-to-cart actions. - Do not use `fbclid`, `_fbc`, `_fbp`, or customer ID as the event ID. - The capitalization must match: `Purchase` does not match `purchase`. - Both copies must be sent to the same Meta pixel/dataset. ### Common failures | Failure | Result | |---|---| | Pixel has no `eventID` | Browser and server events can both be counted | | Server generates a fresh UUID | Deduplication fails | | Browser sends `Purchase`; server sends `purchase_web` | Deduplication fails | | Order number used in browser; numeric order ID used on server | Deduplication fails | | Native Meta app plus an additional manual Pixel installation | Events may fire more than twice | | Server retry creates a new ID | One order can produce multiple server events | --- ## 4. Preparing customer information for server-side transmission CAPI customer information belongs in `user_data`. ### Recommended fields Send only fields Cedar & Coil is permitted to process: | CAPI field | Source | |---|---| | `em` | Checkout/order email | | `ph` | Checkout/order phone | | `fn` | Billing or shipping first name | | `ln` | Billing or shipping last name | | `ct` | City | | `st` | State or province code | | `zp` | ZIP/postal code | | `country` | Two-letter country code | | `external_id` | Stable Shopify customer ID, if available | | `client_ip_address` | Captured browser/order IP | | `client_user_agent` | Captured browser user agent | | `fbp` | `_fbp` browser identifier | | `fbc` | `_fbc` click identifier | ### Normalize, then hash Before hashing: - Email: trim surrounding whitespace and lowercase. - Phone: include country code and digits only. - Country: use a lowercase two-letter code, such as `us`. - State: use a normalized state/province value. - Names and locality fields: normalize according to Meta’s field-specific rules. - External ID: use a stable, non-secret value. Then SHA-256 hash the normalized customer fields. Meta’s official SDK and parameter-builder utilities can perform normalization and hashing automatically, reducing the chance of a hand-built mismatch. ([github.com](https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md?utm_source=openai)) Example: ```javascript import crypto from 'node:crypto'; const sha256 = value => crypto .createHash('sha256') .update(value) .digest('hex'); const normalizeEmail = email => email?.trim().toLowerCase(); const normalizePhone = phone => phone?.replace(/\D/g, ''); const hashedEmail = sha256(normalizeEmail('Customer@Example.com ')); const hashedPhone = sha256(normalizePhone('+1 (415) 555-0100')); ``` ### Do not hash these fields Send the following in their prescribed, unhashed formats: - `client_ip_address` - `client_user_agent` - `fbc` - `fbp` The Meta SDK’s server-side model supports email, phone, names, address fields, external IDs, IP address, user agent, `fbc`, and `fbp`. ([github.com](https://github.com/facebook/facebook-ruby-business-sdk/blob/main/lib/facebook_ads/ad_objects/server_side/user_data.rb?utm_source=openai)) ### Custom implementation requirement for click IDs A Shopify order webhook will not necessarily contain `_fbp` or `_fbc`. A custom implementation should capture permitted click/browser identifiers before checkout and associate them with the checkout or order through: - A first-party server-side session record keyed by checkout token; or - An approved Shopify cart/order attribute strategy. Do not put raw email addresses, phone numbers, or other customer information into URLs, UTMs, cart attributes intended for display, event IDs, or `custom_data`. --- ## 5. Concrete Shopify setup path ### Option A: Native Facebook & Instagram by Meta sales channel **Recommended for Cedar & Coil as a small DTC store.** #### Setup 1. In Shopify, install or open **Facebook & Instagram by Meta**. 2. Connect the correct: - Meta Business Portfolio, - Facebook Page, - ad account, - commerce/catalog account, and - Meta pixel/dataset. 3. In Shopify admin, go to: - **Sales channels** - **Facebook & Instagram** - **Settings** - **Data sharing settings** 4. Activate customer data sharing. 5. Choose **Maximum**, subject to Cedar & Coil’s consent and legal configuration. 6. Connect the intended Meta pixel. 7. Confirm the Arc Clip Lamp is synchronized into the intended Meta catalog. 8. Remove any old theme-level, GTM, custom-pixel, or third-party Meta installation that sends the same events to the same dataset. Shopify documents Standard as browser Pixel only, Enhanced as Pixel plus CAPI, and Maximum as Pixel, CAPI, and Meta’s latest supported advertising technology. The native integration automatically tracks standard events including `ViewContent`, `AddToCart`, `InitiateCheckout`, and `Purchase`. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) #### Advantages - Fastest implementation. - Shopify and Meta maintain the integration. - Pixel and server-event coordination is handled by the partner integration. - No custom token storage, webhook queue, hashing implementation, or deduplication service. - Catalog and product IDs are less likely to drift apart. #### Limitations - Less control over event payloads and event-ID conventions. - Debugging is dependent on the visibility provided by Shopify and Meta. - Custom business rules—such as only counting captured payments—can be harder to implement. - Cedar & Coil must verify, rather than assume, which events are arriving from Browser, Server, or both. ### Option B: Custom implementation Choose this only if Cedar & Coil needs: - Custom purchase definitions. - Specialized checkout or subscription behavior. - A proprietary first-party event pipeline. - More detailed logging and replay. - Control over which permitted identifiers are sent. - Additional destinations from a shared server-side event service. A custom Shopify implementation normally requires: 1. A Shopify app web pixel or custom pixel subscribing to standard customer events. 2. Pixel mapping: - `product_viewed` → `ViewContent` - `product_added_to_cart` → `AddToCart` - `checkout_started` → `InitiateCheckout` - `checkout_completed` → browser `Purchase` 3. A secure server endpoint or queue. 4. An `orders/paid` webhook for confirmed server-side purchases. 5. Shopify webhook HMAC verification. 6. Idempotency storage keyed by Shopify order ID. 7. Customer-data normalization and hashing. 8. Storage of the Meta access token in a secret manager. 9. Consent state propagated to both browser and server processing. Shopify supports storefront and checkout customer events through its sandboxed Pixel Manager, and `orders/paid` webhooks are available for triggering server-side processing. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/pixels/overview?utm_source=openai)) ### Recommendation Start with the **native Meta sales channel at Maximum data sharing**, after configuring consent. For a single-product, small DTC store, the maintenance and data-quality risks of a custom CAPI implementation usually outweigh the additional control. Do not run native and custom implementations simultaneously against the same dataset unless there is a documented migration plan and every overlapping event shares the correct deduplication ID. ### Server-side Purchase request sketch The following illustrates a custom `orders/paid` worker. As of August 26, 2026, Meta’s current Business SDK generation is v26; pin and periodically update the Graph API version rather than using an unversioned endpoint. ([github.com](https://github.com/facebook/facebook-nodejs-business-sdk/releases?after=v3.0.0&utm_source=openai)) ```javascript import crypto from 'node:crypto'; const META_PIXEL_ID = process.env.META_PIXEL_ID; const META_ACCESS_TOKEN = process.env.META_ACCESS_TOKEN; const META_GRAPH_VERSION = 'v26.0'; const STORE_URL = 'https://cedar-and-coil.example'; function sha256(value) { return crypto .createHash('sha256') .update(value) .digest('hex'); } function hashed(value, normalizer = v => v.trim().toLowerCase()) { if (!value) return undefined; const normalized = normalizer(String(value)); return normalized ? [sha256(normalized)] : undefined; } function digitsOnly(value) { return value.trim().replace(/\D/g, ''); } // This must return the exact ID used by Cedar & Coil's Meta catalog. function mapToMetaCatalogId(lineItem) { // Example placeholder only. Confirm the real catalog ID format. return String(lineItem.variant_id ?? lineItem.product_id); } export async function sendMetaPurchase(order, attribution = {}) { const orderGid = order.admin_graphql_api_id ?? `gid://shopify/Order/${order.id}`; // Must exactly match the browser Pixel's eventID. const eventId = `purchase:${orderGid}`; const address = order.billing_address ?? order.shipping_address ?? {}; const contentIds = order.line_items.map(mapToMetaCatalogId); const contents = order.line_items.map(lineItem => ({ id: mapToMetaCatalogId(lineItem), quantity: Number(lineItem.quantity), item_price: Number(lineItem.price) })); const userData = { em: hashed(order.email ?? order.contact_email), ph: hashed( order.phone ?? address.phone, digitsOnly ), fn: hashed(address.first_name), ln: hashed(address.last_name), ct: hashed(address.city), st: hashed(address.province_code ?? address.province), zp: hashed(address.zip), country: hashed(address.country_code), external_id: hashed(order.customer?.id), // These fields are not SHA-256 hashed: client_ip_address: order.browser_ip, client_user_agent: order.client_details?.user_agent, fbp: attribution.fbp, fbc: attribution.fbc }; // Remove undefined fields before sending. Object.keys(userData).forEach(key => { if (userData[key] == null) delete userData[key]; }); const event = { event_name: 'Purchase', event_time: Math.floor( new Date( order.processed_at ?? order.updated_at ?? Date.now() ).getTime() / 1000 ), event_id: eventId, action_source: 'website', event_source_url: attribution.eventSourceUrl ?? STORE_URL, user_data: userData, custom_data: { value: Number(order.total_price), currency: order.currency, content_ids: contentIds, content_type: 'product', contents, order_id: orderGid, num_items: order.line_items.reduce( (sum, item) => sum + Number(item.quantity), 0 ) } }; const body = { data: [event] // Add only while using Meta Test Events: // test_event_code: process.env.META_TEST_EVENT_CODE }; const endpoint = `https://graph.facebook.com/${META_GRAPH_VERSION}/` + `${META_PIXEL_ID}/events?access_token=` + encodeURIComponent(META_ACCESS_TOKEN); const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const result = await response.json(); if (!response.ok) { throw new Error( `Meta CAPI failed: ${response.status} ${JSON.stringify(result)}` ); } return result; } ``` Production requirements omitted from the sketch: - Verify the Shopify webhook HMAC against the **raw request body**. - Return success to Shopify promptly and enqueue processing. - Store webhook and Meta delivery status. - Make the worker idempotent using `purchase:<order GID>`. - Retry transient failures with the same `event_id`. - Never log raw customer data or the Meta access token. - Use a secret manager rather than Shopify theme settings. - Prevent test orders from contaminating production optimization unless intentionally testing a controlled low-volume flow. - Decide how refunds, cancellations, and order edits will be handled separately. Meta also provides official server-side Business SDK classes for `ServerEvent`, `UserData`, `CustomData`, and `EventRequest`, including automatic normalization and hashing support. Using the SDK is preferable to maintaining normalization rules manually. ([github.com](https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md?utm_source=openai)) --- ## 6. End-to-end validation before scaling spend ### A. Configuration audit Confirm: - Only one intended Meta dataset/pixel is connected. - The ad account has access to it. - The correct domain is associated with the business. - The Arc Clip Lamp exists in the correct catalog. - Event `content_ids` match the catalog item ID exactly. - No legacy theme code or duplicate GTM tag remains. - The native app and any third-party Meta app are not both sending overlapping events. ### B. Test the funnel Run these actions individually: 1. View the Arc Clip Lamp product page. 2. Add one lamp to the cart. 3. Start checkout. 4. Complete a test order. 5. Repeat with quantity two. 6. Repeat with a discount. 7. If relevant, repeat with shipping and tax. 8. Test both guest and logged-in checkout. 9. Test desktop and mobile. 10. Test Safari/iOS and a browser with tracking protection or an ad blocker. Shopify supports simulated transactions through its test payment gateway or Shopify Payments test mode. Turn test mode off immediately after testing because customers cannot place normal live orders while the relevant provider is in test mode. ([help.shopify.com](https://help.shopify.com/en/manual/checkout-settings/test-orders?locale=en-US&utm_source=openai)) ### C. Inspect Meta Events Manager Use **Events Manager → Test Events** and check each event: - Correct standard event name. - Correct dataset/pixel. - Correct Browser or Server connection method. - `value` is numeric. - `currency` is `USD` for US orders. - `content_ids` are present and match the catalog. - `Purchase` contains the correct actual total. - `Purchase` contains `order_id`. - Browser and server `Purchase` copies have the same event ID. - Meta recognizes the browser/server pair as deduplicated. - No unexpected duplicate Pixel installations appear. For custom CAPI testing, add the Test Events code as `test_event_code`, then remove it before production. ### D. Compare against Shopify For the test window, create a reconciliation table: | Shopify order | Shopify total | Browser Purchase | Server Purchase | Deduplicated | Meta value | |---|---:|---:|---:|---:|---:| | Test order 1 | $73.61 | Yes | Yes | Yes | $73.61 | Investigate any case where: - Shopify has a paid order but Meta has no server event. - Meta has two counted purchases for one Shopify order. - Meta’s value differs from Shopify. - Browser and server event IDs differ. - `content_ids` do not resolve to catalog items. - Server events arrive with significant unexplained delay. Compare **received event ingestion** with Shopify orders during implementation. Do not expect Ads Manager’s attributed purchase count to equal Shopify’s total order count because attribution applies separate campaign, identity, and attribution-window rules. ### E. Failure-mode tests Deliberately test: - Browser event blocked, server event received. - Thank-you page closed quickly, server event received. - Server request temporarily fails, retry uses the same event ID. - Shopify webhook is delivered twice, only one logical Purchase is sent. - Missing phone but valid email. - Missing customer account ID. - Discounted and multi-quantity orders. - Consent denied: no prohibited browser or server marketing event is transmitted. ### F. Ongoing monitoring For at least the first weeks after launch, monitor: - Shopify paid orders versus unique CAPI `Purchase` event IDs. - CAPI response errors and latency. - Deduplication warnings. - Event Match Quality diagnostics. - Missing or invalid currency/value parameters. - Catalog content-ID match errors. - Sudden event-count changes after theme, checkout, consent-banner, or app updates. --- ## 7. Consent and compliance Hashing customer information does **not** make it anonymous. Hashed email, phone, address fields, IP addresses, browser identifiers, and purchase activity can still be regulated personal information. Cedar & Coil should: - Clearly disclose Meta Pixel and CAPI data sharing in its privacy policy. - Obtain consent where required before activating marketing tracking. - Honor applicable opt-outs of sale, sharing, or targeted advertising. - Apply the same consent decision to the server path; do not suppress the Pixel while continuing to send an unrestricted CAPI event. - Send only fields needed for matching and measurement. - Avoid collecting sensitive information in URLs or event parameters. - Restrict access to Meta tokens and customer data. - Define retention and deletion procedures. - Review Shopify’s Customer Privacy configuration and integrate its consent banner or a compatible consent-management platform. - Have counsel confirm requirements for the states and countries in which Cedar & Coil operates or markets. Shopify’s Pixel Manager can gate pixels based on required marketing and analytics permissions, and pixels configured as data sale/sharing should respect applicable customer opt-outs. Shopify also warns that custom code must not be used to bypass consent requirements. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/pixels/overview?utm_source=openai)) ## Final implementation recommendation For launch: 1. Install the native **Facebook & Instagram by Meta** sales channel. 2. Connect one correct Meta dataset and catalog. 3. Set data sharing to **Maximum**, subject to consent configuration. 4. Remove duplicate manual Meta tags. 5. Confirm the four standard events and their values in Test Events. 6. Complete at least one full Shopify test order. 7. Verify browser/server Purchase deduplication. 8. Reconcile the Meta event with the Shopify order. 9. Test consent-denied and browser-blocked scenarios. 10. Scale spend only after event names, totals, catalog IDs, and deduplication remain stable across repeated tests.
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 'Why both are needed' subsection covering browser blocking, ad blockers, and thank-you page dependency.
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 dedicated subsections for ViewContent, AddToCart, InitiateCheckout, and Purchase, with Purchase explicitly requiring value, currency, and content_ids.
code_sketch
A concrete server-side Purchase event code sketch or request example is included showing event_name, event_time, event_id, action_source, and a user_data block.
✓The sendMetaPurchase function builds an event object with event_name: 'Purchase', event_time, event_id, action_source: 'website', and a 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 6C instructs using Events Manager → Test Events and explicitly checks 'Meta recognizes the browser/server pair as 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 event table specifies Shopify triggers per event and the guide states Purchase should come from the 'orders/paid' webhook/order lifecycle rather than only the thank-you page.
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 anywhere, and Section 7 lays out consent/regional constraints (e.g., 'Honor applicable opt-outs', 'apply the same consent decision to the server path').
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 dedup relies on matching event name and event_id exactly, with a concrete browser fbq eventID and matching server event_id example.
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 states 'Reuse that ID on retries' and 'Never generate a new ID every time a server request is retried,' with event_id derived as purchase:<order GID>.
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.processed_at (falling back to updated_at) converted to Unix seconds, representing the order occurrence time rather than 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 normalizeEmail/normalizePhone functions trim/lowercase/strip non-digits before sha256 hashing, and IP/user-agent/fbc/fbp are explicitly left unhashed.
actionable_path
The recommended Shopify path is decisive and executable for a small DTC store (a clear recommendation with concrete setup steps, not an undifferentiated list of options).
✓The guide gives a decisive 'Recommended for Cedar & Coil as a small DTC store' call for the native Meta sales channel with a numbered concrete setup procedure.

Claude Opus 5 high 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.68 · 185.1s · 11.8k tok
I'll verify current Meta CAPI and Shopify integration specifics before writing the guide.# Meta Conversion Tracking Implementation Guide **Store:** Cedar & Coil (Shopify) · **Product:** Arc Clip Lamp, $68 USD · **Status:** Pre-launch, no campaign data exists yet **Scope note:** This is a measurement implementation plan, not a performance forecast. No campaign has launched, so there is no baseline to compare against — build the tracking first, then establish the baseline from your own data. Nothing in this document should be read as a guarantee of how much attribution any configuration will or won't capture. --- ## 1. Recommended architecture: Pixel + Conversions API with deduplication **Send every core event twice — once from the browser, once from your server — with a shared event ID so Meta collapses the pair into one conversion.** ``` ┌──────────────────────────────┐ Shopper's │ Storefront + Checkout │ browser ─────► │ Meta Pixel (fbq) │──► Meta (browser channel) │ event_id: evt_abc123 │ └──────────────────────────────┘ ┌──────────────┐ ┌──────────────────────────────┐ │ │ Shopify ─────►│ Server / app / Meta channel │──────►│ Meta dedupe │──► 1 event order data │ Conversions API (CAPI) │ │ engine │ │ event_id: evt_abc123 │ └──────────────┘ └──────────────────────────────┘ ``` **Why both channels are required:** | Channel | Strength | Failure mode it suffers | |---|---|---| | Browser Pixel | Carries browser identifiers (`_fbp`, `_fbc`), page context, and real-time click linkage | Blocked by ITP/ETP, ad blockers, tracking prevention, JS errors, users leaving before the tag fires, cookie lifetime truncation | | Conversions API | Fires from your infrastructure after the order is real; not blockable client-side; can include hashed CRM identifiers and late/offline events | Weaker identity signal on its own — no cookies unless you pass them through; can't see pre-checkout browsing without instrumentation | The two fail for **different reasons**, which is the whole point. The Pixel supplies identity quality; CAPI supplies delivery reliability. Deduplication is what lets you run both without double-counting purchases and inflating reported ROAS. **Do not** treat CAPI as a Pixel replacement. A server-only setup loses `_fbp`/`_fbc` continuity and typically produces a weaker Event Match Quality score, which affects optimization and reporting. --- ## 2. Standard events and required parameters Four events is the right scope for a one-product store. Resist adding more until these are clean. ### Event table | Event | Trigger | Sent from | |---|---|---| | `ViewContent` | Arc Clip Lamp product page view | Pixel + CAPI | | `AddToCart` | Add-to-cart action / cart line added | Pixel + CAPI | | `InitiateCheckout` | Checkout started | Pixel + CAPI | | `Purchase` | Order paid (authoritative: server) | Pixel + CAPI | ### Parameters **Common to all four (both channels):** - `event_name`, `event_time` (Unix seconds, UTC) - `event_id` — shared dedup key (Section 3) - `event_source_url` — full page URL - `action_source` — `website` - `user_data` — identifiers (Section 4); at minimum `client_ip_address`, `client_user_agent`, `fbp`, and `fbc` when present, server-side **Per-event custom data:** | Event | `value` | `currency` | `content_ids` | `contents` | Other | |---|---|---|---|---|---| | `ViewContent` | `68.00` | `USD` | `["<variant_id>"]` | — | `content_type: "product"`, `content_name: "Arc Clip Lamp"`, `content_category` | | `AddToCart` | line total (e.g. `68.00`) | `USD` | `["<variant_id>"]` | `[{id, quantity, item_price}]` | `content_type: "product"` | | `InitiateCheckout` | cart subtotal | `USD` | all variant IDs in cart | `[{id, quantity, item_price}]` | `num_items` | | `Purchase` | **order total actually charged** | `USD` | **all purchased variant IDs** | `[{id, quantity, item_price}]` | `order_id`, `num_items`, `content_type: "product"` | **Rules that matter more than they look:** 1. **`value` is a number, not a string, and never includes a currency symbol.** `68.00`, not `"$68.00"`. 2. **`currency` is always present** and is an ISO-4217 code (`USD`). Meta will drop or misvalue events without it. 3. **`content_ids` on `Purchase` must match your Meta catalog item IDs exactly.** If Shopify syncs the catalog via the Meta channel, the IDs are typically the Shopify variant ID (or a `shopify_<shop>_<product>_<variant>` composite, depending on feed). Mismatched IDs silently break catalog/Advantage+ ads and dynamic retargeting even while Purchase counts look fine. 4. **Pick one `value` definition for `Purchase` and document it.** Recommended: total the customer paid *excluding* tax and shipping, so ROAS reflects product revenue. Whatever you choose, browser and server must send the identical number — mismatched values on a deduped pair create confusing diagnostics. 5. **`order_id`** on Purchase gives Meta a second safety net against duplicate orders (e.g. webhook retries). --- ## 3. How deduplication actually works Meta deduplicates when a browser event and a server event share **both**: ``` event_name == event_name (e.g. "Purchase" == "Purchase") event_id == event_id (e.g. "order_5521234567" == "order_5521234567") ``` Whichever arrives first is kept; the later match is discarded. Matching is case-sensitive on `event_id`, so `Order_5521 ≠ order_5521`. **Implementation:** ```js // Browser (Meta Pixel) — third argument carries the ID fbq('track', 'Purchase', { value: 68.00, currency: 'USD', content_ids: ['44012345678901'], content_type: 'product', num_items: 1 }, { eventID: 'order_5521234567' } // note: camelCase eventID on the Pixel ); ``` ```json // Server (CAPI) — snake_case event_id, same string { "event_name": "Purchase", "event_id": "order_5521234567" } ``` **Choosing dedup keys:** | Event | Recommended `event_id` source | |---|---| | `Purchase` | Shopify order ID — stable, unique, available on both sides | | `InitiateCheckout` | Checkout token | | `AddToCart` | UUID generated client-side and passed to your server with the cart mutation | | `ViewContent` | UUID generated client-side, passed server-side in the same request | **Constraints to design around:** - Meta's dedup window is finite (commonly documented as ~48 hours between the two copies). Send the server copy promptly; a CAPI Purchase replayed days later will register as a *new* conversion, not a dedup. - If you cannot generate a shared ID for an event, Meta can fall back to matching on `fbp` + `event_name` + timing, but that is best-effort. Explicit `event_id` is the only reliable method. - **Never send the same `event_id` for two genuinely different events.** A retried webhook should reuse the ID (correct — it dedupes); two separate orders must not. - Only run **one** implementation per event. The most common real-world bug is the native Shopify Meta channel *and* a hand-rolled custom pixel both firing Purchase with different IDs. --- ## 4. Preparing customer information for server-side sends Server events carry identity in `user_data`. Anything personally identifying must be **normalized, then SHA-256 hashed, then hex-encoded (lowercase)** before it leaves your server. Meta never receives raw PII from you. ### Normalization rules (apply *before* hashing) | Field | Key | Normalization | Example → hashed input | |---|---|---|---| | Email | `em` | trim, lowercase | ` Sam@Example.COM ` → `sam@example.com` | | Phone | `ph` | digits only, include country code, drop `+`, spaces, dashes, parens | `+1 (503) 555-0142` → `15035550142` | | First name | `fn` | trim, lowercase, strip punctuation | `Sam` → `sam` | | Last name | `ln` | trim, lowercase | `O'Neil` → `oneil` | | City | `ct` | lowercase, remove spaces/punctuation | `Portland` → `portland` | | State | `st` | 2-letter code, lowercase (US) | `OR` → `or` | | Zip | `zp` | first 5 digits (US), lowercase | `97214-1234` → `97214` | | Country | `country` | 2-letter ISO, lowercase | `US` → `us` | | External ID | `external_id` | your stable customer/pseudonym ID; hash it and be consistent everywhere | — | ### Fields sent in the clear (do NOT hash) `fbp`, `fbc`, `client_ip_address`, `client_user_agent`, `subscription_id`, `lead_id`. Hashing these breaks matching. ### Capturing `fbp` and `fbc` - `_fbp` cookie format: `fb.1.<timestamp_ms>.<random>` - `_fbc` cookie: set by the Pixel from the `fbclid` URL parameter, format `fb.1.<timestamp_ms>.<fbclid>`. If the cookie is absent but `fbclid` is on the landing URL, construct `fbc` yourself in that format. - Persist both onto the Shopify cart/checkout (cart attributes or order note attributes) at the start of the session so your order webhook can read them at purchase time. **This is the single highest-leverage step** for server-event match quality — without it, your CAPI Purchase has no browser identity attached. ### Guardrails - **Never double-hash.** If you use Shopify's native Meta channel or a CAPI Gateway, it hashes for you — passing pre-hashed values into a system that hashes again produces garbage that matches nothing. - Send only what you legitimately hold: email, phone, name, city/state/zip from the order, plus `fbp`/`fbc`/IP/UA. Do not enrich or purchase identifiers. - Keep the access token server-side only — environment variable or secret manager. Never in theme code, never in a custom pixel, never in Git. Rotate in Events Manager if exposed. - Log hashed values only, or better, log nothing but event IDs and status codes. --- ## 5. Shopify setup path ### Option comparison | | **Native Meta sales channel** ("Facebook & Instagram by Meta") | **Custom implementation** (custom Web Pixel + server webhook → Graph API) | |---|---|---| | Effort | ~30 min, no code | Days of dev + ongoing maintenance | | Pixel + CAPI dedup | Handled by Shopify automatically | You own `event_id` generation and parity | | Checkout Purchase event | Works on all plans, including non-Plus | Must run through the Web Pixels API sandbox; `checkout.liquid` is no longer available | | `_fbp`/`_fbc` continuity | Handled internally by Shopify | Hard — custom pixels run in a sandboxed frame and can't read your storefront's first-party cookies directly; you must forward them via cart/order attributes | | Catalog ID alignment | Automatic with product sync | You must match feed ID format manually | | Consent integration | Wired to Shopify's Customer Privacy API | You must call the privacy API yourself | | Flexibility | Fixed event set and parameters | Full control: custom params, offline/CRM events, refunds, subscriptions | | Breaks when Meta changes API versions | Shopify maintains it | You maintain it | ### Recommendation for Cedar & Coil **Use the native Meta sales channel, with Customer Data Sharing set to Maximum.** One product, one currency, standard checkout, small team — a custom build adds failure surface without adding signal you'd actually use. The native channel handles the two hardest parts (checkout-sandbox Purchase events and Pixel/CAPI dedup) for free. Setup path: 1. Shopify admin → **Settings → Apps and sales channels → Add sales channel** → *Facebook & Instagram by Meta*. 2. Connect the correct Business portfolio, Page, Ad account, and **dataset/Pixel**. Create the Pixel in Events Manager first if it doesn't exist, so you control naming. 3. In the channel's **Data sharing / Customer events** settings, enable web *and* server events and set **Customer data sharing = Maximum**. This is what turns on CAPI. 4. Sync the product catalog (Arc Clip Lamp variants) so `content_ids` align with catalog items. 5. In Events Manager: **verify the cedarandcoil domain** and configure **Aggregated Event Measurement** — set `Purchase` as priority 1, then `InitiateCheckout`, `AddToCart`, `ViewContent`. You get eight slots; use four. 6. **Do not also install a custom pixel firing the same standard events.** Pick one owner per event. Add a custom layer later only if you hit a specific need: refund/return events, subscription renewals, CRM-sourced conversions, or a value definition the channel won't produce. ### Code sketch — server-side Purchase via Shopify `orders/paid` webhook Reference implementation if you go custom (Node, e.g. Cloudflare Worker or small Express service). This is a sketch, not production code — add retries with exponential backoff, dead-letter queueing, and structured logging. ```js import crypto from 'node:crypto'; const GRAPH_VERSION = 'v25.0'; // pin a version; check Meta's changelog before upgrading const DATASET_ID = process.env.META_DATASET_ID; const ACCESS_TOKEN = process.env.META_CAPI_ACCESS_TOKEN; // server-side secret only const sha256 = (v) => crypto.createHash('sha256').update(v).digest('hex'); const norm = { email: (v) => v?.trim().toLowerCase(), phone: (v) => v?.replace(/\D/g, ''), // digits only, incl. country code name: (v) => v?.trim().toLowerCase().replace(/[^a-z\u00C0-\u024F]/g, ''), city: (v) => v?.trim().toLowerCase().replace(/[^a-z]/g, ''), zip: (v) => v?.trim().toLowerCase().slice(0, 5), code: (v) => v?.trim().toLowerCase(), }; const hashIf = (v) => (v ? sha256(v) : undefined); function verifyShopifyHmac(rawBody, header) { const digest = crypto .createHmac('sha256', process.env.SHOPIFY_WEBHOOK_SECRET) .update(rawBody, 'utf8') .digest('base64'); return crypto.timingSafeEqual(Buffer.from(digest), Buffer.from(header)); } // Read _fbp/_fbc that the storefront stashed on the cart at session start. function attr(order, key) { return order.note_attributes?.find((a) => a.name === key)?.value || undefined; } export async function handleOrdersPaid(rawBody, headers) { if (!verifyShopifyHmac(rawBody, headers['x-shopify-hmac-sha256'])) { return { status: 401 }; } const order = JSON.parse(rawBody); // Consent gate: skip if the shopper declined marketing/analytics tracking. if (attr(order, 'meta_consent') === 'denied') return { status: 204 }; const addr = order.shipping_address || order.billing_address || {}; const contents = order.line_items.map((li) => ({ id: String(li.variant_id), // MUST match your Meta catalog item IDs quantity: li.quantity, item_price: Number(li.price), // 68.00 for the Arc Clip Lamp })); const payload = { data: [{ event_name: 'Purchase', event_time: Math.floor(new Date(order.processed_at || order.created_at).getTime() / 1000), event_id: `order_${order.id}`, // identical string the browser Pixel used event_source_url: `https://cedarandcoil.example/checkouts/thank-you`, action_source: 'website', user_data: { em: hashIf(norm.email(order.email)), ph: hashIf(norm.phone(order.phone || addr.phone)), fn: hashIf(norm.name(addr.first_name)), ln: hashIf(norm.name(addr.last_name)), ct: hashIf(norm.city(addr.city)), st: hashIf(norm.code(addr.province_code)), zp: hashIf(norm.zip(addr.zip)), country: hashIf(norm.code(addr.country_code)), external_id: hashIf(String(order.customer?.id ?? '')) || undefined, // NOT hashed: fbp: attr(order, 'fbp'), fbc: attr(order, 'fbc'), client_ip_address: attr(order, 'client_ip'), client_user_agent: attr(order, 'client_ua'), }, custom_data: { currency: order.currency, // 'USD' value: Number(order.current_subtotal_price), // documented definition: ex-tax, ex-shipping content_type: 'product', content_ids: contents.map((c) => c.id), contents, num_items: contents.reduce((n, c) => n + c.quantity, 0), order_id: String(order.id), }, }], // test_event_code: 'TEST12345', // ONLY while validating; remove before launch }; const res = await fetch( `https://graph.facebook.com/${GRAPH_VERSION}/${DATASET_ID}/events?access_token=${ACCESS_TOKEN}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) } ); const body = await res.json(); // Expect: { events_received: 1, messages: [], fbtrace_id: "..." } if (!res.ok || body.error) { console.error('capi_purchase_failed', { order_id: order.id, error: body.error }); throw new Error('CAPI send failed'); // let the queue retry — event_id makes retries safe } return { status: 200 }; } ``` Matching browser side, inside a Shopify custom pixel: ```js analytics.subscribe('checkout_completed', (event) => { const c = event.data.checkout; fbq('track', 'Purchase', { value: Number(c.subtotalPrice.amount), currency: c.currencyCode, content_ids: c.lineItems.map((li) => String(li.variant.id)), content_type: 'product', num_items: c.lineItems.reduce((n, li) => n + li.quantity, 0), }, { eventID: `order_${c.order.id}` }); // same key as the server }); ``` --- ## 6. End-to-end validation before scaling spend Work through this in order. Don't raise budget past a test level until every box is checked. ### A. Server payload correctness - [ ] Run a sample payload through Meta's **Payload Helper** in Events Manager — fix schema errors before sending live traffic. - [ ] Add `test_event_code` and fire a Purchase; confirm it appears in **Test Events** within ~30 seconds. - [ ] Confirm the response is `events_received: 1` with an empty `messages` array. Warnings in `messages` are real problems. ### B. Deduplication proof - [ ] Place a real end-to-end test order for the Arc Clip Lamp (discount code to $0.01, or refund after). - [ ] In Test Events, confirm you see the browser event and the server event, and that one is marked **deduplicated** — not two separate Purchases. - [ ] Copy the `event_id` from each side and diff them character by character. Case and prefix must match. - [ ] In Events Manager → **Overview**, the Purchase row should show connection method **"Browser and Server"**, not one or the other. ### C. Parameter integrity - [ ] `value` and `currency` present on all four events; `value` is numeric; currency is `USD`. - [ ] `content_ids` on Purchase resolve to real items in the connected catalog — check **Catalog → Events → Diagnostics** for "content_ids do not match catalog" warnings. - [ ] `Event Match Quality` is populating for Purchase. Treat this as a directional health score to improve over time, not a target to hit before launch. - [ ] **Diagnostics tab is clean** of: missing purchase value, redundant Pixel events, invalid parameter format, PII detected in raw form. "PII detected" means unhashed data reached Meta — fix immediately. ### D. Funnel and volume reconciliation - [ ] Walk the funnel manually with Meta Pixel Helper: product page → add to cart → checkout → purchase. Exactly one of each event, no doubles. - [ ] Repeat on mobile Safari and in an incognito window — this is where browser-only tracking degrades and where CAPI should be carrying the event. - [ ] After 7 days of any traffic, compare **Shopify order count and revenue** against **Meta Purchase count and value** for the same window. Investigate any gap in either direction; a Meta count *above* Shopify's is a dedup failure and the more urgent bug. - [ ] Confirm no Purchase events fire on page refresh of the thank-you page or on order-edit webhooks. ### E. Pre-launch configuration - [ ] Domain verified; Aggregated Event Measurement priorities set with Purchase first. - [ ] `test_event_code` **removed** from production code. - [ ] Webhook has retry + alerting; you'll know within an hour if CAPI sends start failing. - [ ] Record the date tracking went live. That timestamp is the start of your baseline — everything before it is unmeasured. --- ## 7. Consent and compliance **Consent gating.** Use Shopify's **Customer Privacy API** as the single source of truth. In custom pixels, query `init.customerPrivacy` and subscribe to consent changes rather than assuming consent. For visitors in the EU, UK, and other consent-required regions, do not fire the Pixel or send CAPI events for that visitor until marketing/analytics consent is granted. Server-side sending is *not* a workaround for a declined consent signal — the legal obligation attaches to the data, not the transport. Propagate the consent decision to the order (e.g. a cart attribute) so your webhook can honor it, as sketched above. **Regional signals to configure:** - Meta's **Limited Data Use** (`data_processing_options: ["LDU"]`) for applicable US state privacy laws — the native Shopify channel exposes this as a setting; a custom build must send it in the payload. - Shopify's **customer privacy / data sale** settings, including the "data sale" classification on any custom pixel. - A CMP that writes into Shopify's privacy API, so banner state and pixel behavior can't drift apart. **Data handling:** - Only hashed identifiers leave your server; never log or transmit raw email or phone to Meta. - Collect only what the order already contains — no enrichment, no appended third-party identifiers. - Access tokens live in secret storage, are scoped to the dataset, and are rotated on staff changes or suspected exposure. - Have a documented process for honoring deletion requests, including Meta's user-data deletion endpoints, and confirm a Data Processing Addendum is in place with Meta before running EU traffic. - Update the Cedar & Coil privacy policy to describe advertising measurement and server-side sharing before the first ad runs. **Marketing constraint carried from brand guidance:** all campaign work remains draft-only. This tracking spec supports measurement of the approved CTA path ("Explore the Arc Clip Lamp") and makes no claims about product performance, results, or outcomes.
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 details why each channel is needed under privacy limits (ITP/ad blockers vs. server reliability).
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 parameter table for ViewContent, AddToCart, InitiateCheckout, and Purchase, including value, currency, and content_ids for Purchase.
code_sketch
A concrete server-side Purchase event code sketch or request example is included showing event_name, event_time, event_id, action_source, and a user_data block.
✓The Node.js code sketch includes event_name: 'Purchase', event_time, event_id, action_source: 'website', and a full user_data block with hashed and unhashed 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.A references Meta's Test Events tool and 6.B explicitly checks that browser/server events are marked 'deduplicated' with matching event_ids.
sources_defined
For each event it is clear where it fires (browser vs server) and what the source of truth is (e.g. Purchase from the Shopify order webhook/server, not only the thank-you page).
✓The event table marks Purchase as 'Order paid (authoritative: server)' and the code sketch sources Purchase from the Shopify 'orders/paid' webhook rather than the thank-you page.
limits_stated
Limitations are stated honestly: no promised attribution-recovery percentages, and consent/regional rules are noted as constraints on what may be sent.
✓The scope note explicitly disclaims any attribution guarantee, and Section 7 treats consent/regional rules (EU/UK, LDU) as hard constraints on what may be sent.
dedup_correct
Deduplication is technically correct: the same event_id and event_name sent on both the Pixel and CAPI event so Meta drops the duplicate; not a vague mention.
✓Section 3 states Meta dedups when event_name and event_id match exactly (case-sensitive), with concrete examples on both Pixel and CAPI sides.
event_id_retry_stability
The event_id is generated or derived once per commerce event, shared by browser and server, and reused unchanged on webhook retries or order updates; a new random suffix per send or retry fails.
✓event_id is derived from the stable Shopify order_id (`order_${order.id}`) and the guide explicitly notes 'A retried webhook should reuse the ID (correct — it dedupes)'.
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 occurrence time rather than 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 trimming/lowercasing email and other fields before SHA-256 hashing, and the code implements `norm.email` then `sha256`/hex encoding.
actionable_path
The recommended Shopify path is decisive and executable for a small DTC store (a clear recommendation with concrete setup steps, not an undifferentiated list of options).
✓Section 5 gives a decisive recommendation ('Use the native Meta sales channel... Maximum data sharing') with a numbered concrete setup path for a small DTC store.