← Run 20260826-212341-34f65925
Shopify to Meta ads conversion tracking implementation
task shopify-meta-capiAug 26, 2026

Answers & verdicts

GPT-5.6 Sol high effort

Task passed
Task the exact prompt the model was given — assignment and source material
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.
Answer the model's full response$0.93 · 236.4s · 13.6k tok
# Draft implementation guide: Shopify → Meta conversion tracking *Checked against current Shopify and Meta implementation guidance on August 26, 2026.* ## 1. Recommended architecture: Meta Pixel + Conversions API Use one Meta data source/pixel with two delivery paths: ```text Shopify storefront ├─ Browser: Meta Pixel │ ViewContent, AddToCart, InitiateCheckout, Purchase │ └─ Server: Meta Conversions API Purchase at minimum; mirror other events when practical Browser event + server event └─ Same event_name + same event_id → Meta deduplicates ``` ### Why both are needed **Browser Meta Pixel** - Captures storefront behavior close to when it happens. - Has useful browser context, including page URL, user agent, `_fbp`, and `_fbc`/Meta click context. - Can be limited by browser privacy controls, consent choices, script failures, ad blockers, or a customer not loading the confirmation page. **Server-side Conversions API** - Sends events from Shopify or Cedar & Coil’s backend to Meta. - Is not blocked by browser-based ad blockers. - Can anchor `Purchase` to a paid Shopify order and use checkout information for matching. - Still requires lawful data collection and does not bypass consent requirements. Using both creates redundant event delivery while retaining browser context. Meta recommends redundant connection methods with deduplicated events, and Shopify’s Enhanced and Maximum data-sharing levels combine the Meta Pixel with Conversions API. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) **Recommended minimum:** Send all four funnel events through the browser and send `Purchase` through CAPI. A custom implementation can mirror all four through CAPI if Cedar & Coil needs complete control. --- ## 2. Standard events and parameters Shopify exposes `product_viewed`, `product_added_to_cart`, `checkout_started`, and `checkout_completed`, which map naturally to Meta’s four standard events. Shopify’s own custom-pixel example uses the same mapping. ([shopify.dev](https://shopify.dev/docs/api/web-pixels-api/standard-events?utm_source=openai)) | Shopify action | Meta event | Key parameters | |---|---|---| | Product page viewed | `ViewContent` | `content_ids`, `content_type`, `content_name`, `value`, `currency` | | Product added to cart | `AddToCart` | `content_ids`, `contents`, `content_type`, `value`, `currency` | | Checkout started | `InitiateCheckout` | `content_ids`, `contents`, `content_type`, `num_items`, `value`, `currency` | | Checkout completed/paid | `Purchase` | `content_ids`, `contents`, `content_type`, `num_items`, `value`, `currency`, `order_id` | ### `ViewContent` Send 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" } ``` ### `AddToCart` Send once for each successful add-to-cart action—not merely when the button is clicked. ```json { "content_ids": ["<META_CATALOG_ITEM_ID>"], "content_type": "product", "contents": [ { "id": "<META_CATALOG_ITEM_ID>", "quantity": 1, "item_price": 68.00 } ], "value": 68.00, "currency": "USD" } ``` If two lamps are added in one action, use `quantity: 2` and `value: 136.00`. ### `InitiateCheckout` Send when Shopify reports `checkout_started`. ```json { "content_ids": ["<META_CATALOG_ITEM_ID>"], "content_type": "product", "contents": [ { "id": "<META_CATALOG_ITEM_ID>", "quantity": 1, "item_price": 68.00 } ], "num_items": 1, "value": 68.00, "currency": "USD" } ``` Use the actual checkout total available at that stage rather than recalculating from the advertised product price. ### `Purchase` Send only for a completed purchase according to a documented business rule—normally a paid Shopify order. ```json { "content_ids": ["<META_CATALOG_ITEM_ID>"], "content_type": "product", "contents": [ { "id": "<META_CATALOG_ITEM_ID>", "quantity": 1, "item_price": 68.00 } ], "num_items": 1, "value": 73.42, "currency": "USD", "order_id": "1234567890" } ``` The sample `value` is illustrative. In production: - Use Shopify’s actual final checkout/order total. - Do not hardcode `$68` for `Purchase`; quantity, discounts, shipping, duties, and taxes can change the amount. - Use the transaction currency as an uppercase ISO-style code, such as `USD`. - Send every purchased item in `contents`. - Include every corresponding catalog ID in `content_ids`. Shopify defines checkout `totalPrice` as the checkout total including duties, taxes, and discounts. ([shopify.dev](https://shopify.dev/docs/api/web-pixels-api/standard-events/checkout_completed)) ### Critical catalog-ID rule `content_ids[].id` must use exactly the same identifier stored as the item’s ID or `retailer_id` in the connected Meta catalog. Do not mix Shopify product IDs, variant IDs, SKUs, and Meta-generated IDs. Choose one convention: - Shopify variant ID; - SKU; or - a defined transformation used by the catalog feed. The native Meta sales channel handles this mapping. A custom implementation must inspect the Meta catalog and reproduce its ID format exactly. --- ## 3. Exactly how Pixel/CAPI deduplication works Meta identifies a browser event and server event as the same customer action when they are sent to the same Meta pixel/data source and have: 1. The same exact event name, such as `Purchase`; and 2. The same exact event ID. Browser syntax: ```js fbq( "track", "Purchase", purchaseParameters, { eventID: "purchase:cedar-and-coil:1234567890" } ); ``` CAPI syntax: ```json { "event_name": "Purchase", "event_id": "purchase:cedar-and-coil:1234567890" } ``` Notice the naming difference: - Browser parameter: `eventID` - Server parameter: `event_id` Meta’s documented deduplication window is 48 hours. When matching events arrive close together, Meta documents that it favors the browser event; the pair is processed as one conversion rather than two. ([github.com](https://github.com/facebookincubator/Facebook-Server-Side-API-Swagger/blob/main/server-side-api.yaml?utm_source=openai)) ### Event-ID strategy For `Purchase`, use a deterministic ID based on the Shopify order ID: ```text purchase:<shop-domain>:<numeric-shopify-order-id> ``` Example: ```text purchase:cedar-and-coil.myshopify.com:1234567890 ``` Shopify makes the order ID available in the browser-side `checkout_completed` event. The webhook has the same underlying order ID, although one side may represent it as a Shopify GID. Normalize both to the numeric portion before constructing the event ID. ([shopify.dev](https://shopify.dev/docs/api/web-pixels-api/standard-events/checkout_completed)) For mirrored upper-funnel events, the easiest custom approach is: - Use Shopify’s customer-event `event.id`. - Pass it to Pixel as `eventID`. - Forward the same ID to the backend. - Use it as the CAPI `event_id`. ### Deduplication rules to enforce - IDs must be unique per actual action. - Two separate add-to-cart actions need two different IDs. - Retries of the same server event must reuse the original ID. - Names are case-sensitive in practice: use `Purchase`, not `purchase`. - Never generate independent random IDs in the browser and server. - Keep application-level idempotency as well; do not depend solely on Meta’s deduplication. Avoid running the native Shopify integration and a separate custom CAPI integration for the same events unless their deduplication IDs can be coordinated. Otherwise, double-counting is likely. --- ## 4. Preparing customer information for server-side transmission Meta uses customer information to match an event to a Meta account. Prepare it in this order: ```text Collect lawfully → normalize → SHA-256 hash → send over HTTPS ``` ### Normalize and hash | CAPI field | Source | Preparation | |---|---|---| | `em` | Checkout email | Trim and lowercase, then SHA-256 | | `ph` | Checkout phone | Convert to digits including country code, then SHA-256 | | `fn` | First name | Normalize and lowercase, then SHA-256 | | `ln` | Last name | Normalize and lowercase, then SHA-256 | | `ct` | City | Lowercase and remove spaces/punctuation as required, then SHA-256 | | `st` | State/province | Prefer normalized region code, then SHA-256 | | `zp` | ZIP/postal code | Normalize according to country, then SHA-256 | | `country` | Country | Lowercase two-letter country code, then SHA-256 | | `external_id` | Stable customer ID | Use a stable first-party customer ID and hash it | Meta’s specification describes these normalization and hashing requirements, including lowercase email, digits-only phone with country code, and normalized address fields. ([github.com](https://github.com/facebookincubator/Facebook-Server-Side-API-Swagger/blob/main/server-side-api.yaml?utm_source=openai)) Prefer Meta’s official Business SDK/Conversions API Parameter Builder over hand-written normalization where possible. The current SDK tooling can normalize and SHA-256-hash supported customer-information fields automatically. ([github.com](https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md?utm_source=openai)) ### Do not hash these fields Send these in their native form when available and permitted: - `fbp` - `fbc` - `client_ip_address` - `client_user_agent` - `event_id` - Product/catalog IDs `_fbp` and `_fbc` are browser identifiers. A custom system must capture them while the customer is browsing and persist them against a first-party key, such as the checkout token, so the order webhook can retrieve them later. ### Security requirements - Keep the CAPI access token in server-side secrets, never theme code or a web pixel. - Use HTTPS. - Do not log raw checkout PII. - Do not put email, phone, or order authentication keys in `event_source_url`. - Strip sensitive query parameters from stored URLs. - Restrict retention to what is operationally necessary. - Only request Shopify protected-customer-data scopes needed by the implementation. Shopify limits access to checkout email, phone, names, and addresses through protected-data scopes. ([shopify.dev](https://shopify.dev/docs/api/web-pixels-api/standard-events/checkout_completed)) Hashing is a transport and matching requirement; it is not a substitute for notice, consent, access controls, or other privacy obligations. --- ## 5. Concrete Shopify setup path ### Option A: Native Facebook and Instagram by Meta sales channel **Recommended for Cedar & Coil.** Shopify’s native integration is free for eligible stores and combines catalog synchronization, Meta Pixel setup, and Conversions API data sharing. ([help.shopify.com](https://help.shopify.com/en/manual/online-sales-channels/facebook-instagram-by-meta/orders?syclid=cuc0t7ktqicc73diu7v0&utm_source=openai)) #### Setup steps 1. In Shopify Admin, install **Facebook & Instagram by Meta**. 2. Complete the channel setup and connect: - The correct Meta business portfolio; - Facebook Page; - Meta ad account; - Product catalog; - Existing Meta pixel/data source. 3. Go to: ```text Shopify Admin → Sales channels → Facebook & Instagram → Settings → Share data settings / Data sharing settings ``` 4. Enable customer data sharing. 5. Choose **Maximum**. 6. Connect the intended Meta pixel. 7. Confirm the pixel ID matches the data source selected in Meta Events Manager. 8. Remove any Meta Pixel previously installed in: - `theme.liquid`; - Shopify theme preferences; - Customer Events custom pixels; - Google Tag Manager; or - Another tracking/CAPI app. Shopify states that Maximum uses both the Meta Pixel and Conversions API. Shopify also specifically warns that leaving old theme pixel code in place can produce duplicate or incorrect reporting. ([help.shopify.com](https://help.shopify.com/en/manual/promoting-marketing/analyze-marketing/meta-data-sharing?utm_source=openai)) #### Why this is the recommendation For a small DTC store with one Shopify storefront and a standard checkout, the native channel has the best balance of: - Lower implementation risk; - Managed catalog-ID consistency; - Managed deduplication; - Shopify customer-privacy integration; - No custom webhook infrastructure; - Lower ongoing API-version and checkout-maintenance burden. Verify actual browser/server coverage in Events Manager rather than assuming every funnel event is mirrored server-side. Shopify’s published documentation specifically calls out server-to-server `Purchase`; implementation details can evolve. If Cedar & Coil later needs all four events mirrored through CAPI, detailed delivery logs, or custom identity handling, reassess a custom build. ### Option B: Custom implementation Use a custom build only when there is a documented requirement the native channel cannot satisfy. | Area | Native channel | Custom implementation | |---|---|---| | Pixel and CAPI | Managed | Cedar & Coil owns both | | Deduplication | Managed | Must be designed and tested | | Catalog IDs | Managed | Must map IDs exactly | | Consent integration | Built into Shopify integration | Must be explicitly configured | | Logs and retries | Limited control | Full control | | Event schema | Limited control | Full control | | Maintenance | Low | Ongoing engineering work | | Best fit | Small/standard DTC store | Complex or specialized tracking | A robust custom build should use: 1. A **Shopify web pixel app extension** subscribing to: - `product_viewed` - `product_added_to_cart` - `checkout_started` - `checkout_completed` 2. A backend event endpoint or queue. 3. An `orders/paid` webhook for server-side purchases. 4. HMAC verification for Shopify webhooks. 5. A durable identity bridge for `_fbp`, `_fbc`, browser event ID, and checkout token. 6. A database idempotency key for each CAPI send. 7. Retry handling that preserves the original `event_id`. 8. A reconciliation job that finds paid Shopify orders missing a successful CAPI send. Shopify recommends web pixel app extensions for application integrations, and `orders/paid` fires when an order becomes paid. Shopify also recommends versioned, configuration-managed webhook subscriptions. ([shopify.dev](https://shopify.dev/docs/apps/build/marketing/build-web-pixels?utm_source=openai)) ### Server-side `Purchase` request sketch This Node.js sketch assumes: - The `orders/paid` webhook HMAC has already been verified. - The customer is eligible for this data processing under Cedar & Coil’s consent rules. - `lookupBrowserIdentity()` retrieves previously captured `_fbp`/`_fbc`. - Shopify variant IDs are the IDs used in the connected Meta catalog. Change `catalogIdFor()` if that is not true. ```js import crypto from "node:crypto"; const { META_PIXEL_ID, META_CAPI_ACCESS_TOKEN, META_GRAPH_API_VERSION = "v26.0" } = process.env; const sha256 = (value) => crypto .createHash("sha256") .update(value) .digest("hex"); const lower = (value) => value == null ? null : String(value).trim().toLowerCase(); const compact = (value) => { const normalized = lower(value); return normalized ? normalized.replace(/[^\p{L}\p{N}]/gu, "") : null; }; const phoneDigits = (value) => value == null ? null : String(value).replace(/\D/g, ""); const hashedArray = (value, normalizer = lower) => { const normalized = normalizer(value); return normalized ? [sha256(normalized)] : undefined; }; const setIfPresent = (object, key, value) => { if (value !== undefined && value !== null && value !== "") { object[key] = value; } }; // This must match the retailer_id/item ID used by the Meta catalog. const catalogIdFor = (lineItem) => String(lineItem.variant_id); export async function sendMetaPurchase({ order, shopDomain, identity = {}, testEventCode }) { const address = order.shipping_address || order.billing_address || {}; const numericOrderId = String(order.id); const eventId = `purchase:${shopDomain}:${numericOrderId}`; const userData = {}; setIfPresent( userData, "em", hashedArray(order.email || order.contact_email) ); setIfPresent( userData, "ph", hashedArray( order.phone || address.phone, phoneDigits ) ); setIfPresent(userData, "fn", hashedArray(address.first_name)); setIfPresent(userData, "ln", hashedArray(address.last_name)); setIfPresent(userData, "ct", hashedArray(address.city, compact)); setIfPresent( userData, "st", hashedArray(address.province_code || address.province, compact) ); setIfPresent(userData, "zp", hashedArray(address.zip, compact)); setIfPresent( userData, "country", hashedArray(address.country_code, compact) ); if (order.customer?.id) { userData.external_id = hashedArray(String(order.customer.id)); } // These fields are not hashed. setIfPresent(userData, "fbp", identity.fbp); setIfPresent(userData, "fbc", identity.fbc); setIfPresent(userData, "client_ip_address", order.browser_ip); setIfPresent( userData, "client_user_agent", identity.userAgent || order.client_details?.user_agent ); const contents = order.line_items .filter((item) => item.variant_id) .map((item) => ({ id: catalogIdFor(item), quantity: Number(item.quantity), item_price: Number(item.price) })); const value = Number( order.current_total_price ?? order.total_price ); const eventTime = Math.floor( new Date( order.processed_at || order.created_at ).getTime() / 1000 ); const payload = { data: [ { event_name: "Purchase", event_time: eventTime, event_id: eventId, action_source: "website", // Use a safe canonical URL; never send order_status_url. event_source_url: `https://${shopDomain}/checkout`, user_data: userData, custom_data: { currency: order.currency, value, content_type: "product", content_ids: contents.map((item) => item.id), contents, num_items: contents.reduce( (sum, item) => sum + item.quantity, 0 ), order_id: numericOrderId } } ] }; if (testEventCode) { payload.test_event_code = testEventCode; } const response = await fetch( `https://graph.facebook.com/${META_GRAPH_API_VERSION}` + `/${META_PIXEL_ID}/events`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${META_CAPI_ACCESS_TOKEN}` }, body: JSON.stringify(payload) } ); const result = await response.json(); if (!response.ok) { throw new Error( `Meta CAPI failed: ${JSON.stringify(result)}` ); } return { eventId, eventsReceived: result.events_received, fbtraceId: result.fbtrace_id }; } ``` For production, use Meta’s official SDK normalization utilities rather than treating the simplified helper functions above as a complete international-address normalizer. Meta’s official Business SDK provides server-event request support and current parameter-building functionality. ([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 Pixel implementation owns each event. - Only one CAPI implementation owns each event. - The native channel is connected to the intended Meta pixel. - Old theme, GTM, custom-pixel, and third-party CAPI installations are removed. - The Meta catalog contains the Arc Clip Lamp. - Event `content_ids` exactly match catalog IDs. - Store currency and event currency agree. ### B. Test the browser funnel In a clean browser session: 1. Open the Arc Clip Lamp product page. 2. Add it to the cart. 3. Begin checkout. 4. Complete a Shopify test order. Use Meta Events Manager and, where useful, Meta Pixel Helper to confirm: - `ViewContent` fires once. - `AddToCart` fires once per add action. - `InitiateCheckout` fires once when checkout begins. - `Purchase` fires once at completion. - Parameters have the correct types: - `value` is numeric; - `currency` is a three-letter string; - `content_ids` is an array of strings; - `contents[].quantity` is numeric. ### C. Test the server event For a custom implementation: 1. Open the data source’s **Test Events** section in Meta Events Manager. 2. Obtain the test event code. 3. Set it as `test_event_code`. 4. Trigger a paid Shopify test order. 5. Confirm Meta’s API responds successfully and reports an event received. Meta defines `test_event_code` specifically for validating server events in the Events Manager Test Events tool. ([github.com](https://github.com/facebookincubator/Facebook-Server-Side-API-Swagger/blob/main/server-side-api.yaml?utm_source=openai)) For the native channel, place a test order and inspect the event sources and processed events available for the connected data source. ### D. Verify deduplication For the same test purchase, record: - Browser `eventID`; - Server `event_id`; - Browser event name; - Server event name; - Pixel/data-source ID; - Shopify order ID; - Event timestamps. The expected result is: ```text Browser: Purchase / purchase:shop:1234567890 Server: Purchase / purchase:shop:1234567890 Meta: one processed/deduplicated purchase ``` If two purchases are processed, check: - ID formatting; - GID versus numeric Shopify order ID; - Uppercase/lowercase differences; - Different pixel IDs; - Multiple browser installations; - Multiple webhook/CAPI workers; - Retries generating new IDs. ### E. Reconcile data values Compare the event against the Shopify order: - `value` equals the chosen Shopify order-total field. - `currency` equals the order currency. - `num_items` equals the sum of quantities. - `content_ids` contains every purchased catalog item. - `order_id` equals the Shopify order ID. - `event_time` represents the actual purchase/paid time. - Customer-information fields are present when available and permitted. ### F. Test failure and privacy cases Test at least: - Browser with an ad blocker: browser event may be absent, but the permitted server purchase should still arrive. - Confirmation page closed before loading: server purchase should still arrive. - Duplicate webhook delivery: only one server purchase should be sent or processed. - Meta API temporary failure: the queue retries with the same `event_id`. - Consent rejected in an opt-in region: tracking follows the configured consent decision. - Data-sharing opt-out/GPC flow where applicable. - A refunded order: do not automatically send another `Purchase`; establish a separate refund/reporting policy if required. Shopify notes that `checkout_completed` normally fires once but might not fire if the relevant browser page fails to load, which is one reason the server path is valuable. ([shopify.dev](https://shopify.dev/docs/api/web-pixels-api/standard-events/checkout_completed)) ### G. Launch gate Before increasing spend, require: - No unresolved critical Events Manager diagnostics. - Correct browser/server source coverage. - Demonstrated Purchase deduplication. - Successful webhook retry and idempotency tests. - Correct catalog matching. - Correct consent behavior. - A daily reconciliation report comparing paid Shopify orders with successful CAPI sends. Do not expect Meta-attributed purchases to equal Shopify orders. Event receipt, event matching, and ad attribution are different stages. --- ## 7. Consent and compliance note Configure Shopify’s privacy controls at: ```text Shopify Admin → Settings → Customer privacy ``` Review and configure: - Privacy policy; - Cookie banner; - Regions requiring opt-in consent; - Data-sharing opt-out page; - Global Privacy Control handling; - Installed privacy applications. Shopify supports region-based cookie banners and data-sale/sharing opt-outs, and advises integrating any third-party consent platform with Shopify’s Customer Privacy API. ([help.shopify.com](https://help.shopify.com/en/manual/privacy-and-security/privacy/customer-privacy-settings/understanding-customer-privacy-settings?syclid=co6asfsh33ns73cm10lg&utm_source=openai)) The privacy policy should accurately disclose: - Use of the Meta Pixel and Conversions API; - Categories of data sent to Meta; - Advertising, measurement, and matching purposes; - Use of cookies and similar identifiers; - Customer choices and opt-out methods; - Applicable retention and deletion practices. For a custom web pixel, declare the appropriate Shopify privacy purposes—normally `marketing`, and potentially `analytics` and `sale_of_data` depending on counsel’s determination. Shopify pixels configured for consent-gated regions only run after the required permissions are granted. ([shopify.dev](https://shopify.dev/docs/apps/build/marketing/build-web-pixels?utm_source=openai)) Apply the same decision to the server path. **CAPI must not become a way to transmit data that the browser integration withheld because the customer declined consent or exercised an applicable opt-out.** Because requirements vary by customer location and business practices, Cedar & Coil should have qualified counsel review the final consent, disclosure, data-sharing, and retention configuration before launch.
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 deduplication and explains browser privacy limitations like ad blockers and consent as the reason both are needed.
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓Section 2 provides a table and code snippets for ViewContent, AddToCart, InitiateCheckout, and Purchase, with Purchase including value, currency, and content_ids.
code_sketch
A concrete server-side Purchase event code sketch or request example is included showing event_name, event_time, event_id, action_source, and a user_data block.
✓The Node.js sendMetaPurchase 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 6C references Meta Events Manager's Test Events tool and test_event_code, and 6D explicitly instructs recording browser/server event_ids to verify a single deduplicated purchase is processed.
sources_defined
For each event it is clear where it fires (browser vs server) and what the source of truth is (e.g. Purchase from the Shopify order webhook/server, not only the thank-you page).
✓The guide states Purchase should be anchored to the orders/paid webhook/server-side order data rather than only the thank-you page, noting checkout_completed 'might not fire if the relevant browser page fails to load'.
limits_stated
Limitations are stated honestly: no promised attribution-recovery percentages, and consent/regional rules are noted as constraints on what may be sent.
✓The guide states 'Do not expect Meta-attributed purchases to equal Shopify orders' without giving any percentage, and Section 7 treats consent/regional rules as hard constraints on what CAPI may send.
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 requires 'the same exact event name' and 'the same exact event ID' on both fbq (eventID) and CAPI (event_id) with concrete syntax 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 guide specifies a deterministic event_id derived from the Shopify order ID (purchase:<shop>:<order_id>) and states 'Retries of the same server event must reuse the original 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 computes eventTime from order.processed_at || order.created_at in Unix seconds, and validation step E checks 'event_time represents the actual purchase/paid 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 code normalizes email/phone/name fields (trim, lowercase, digits-only) then applies sha256 hashing before placing them 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 states 'Recommended for Cedar & Coil' for the native Facebook & Instagram by Meta sales channel and lists concrete numbered setup steps in Shopify Admin.

Claude Opus 5 high effort

Task passed
Task the exact prompt the model was given — assignment and source material
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.
Answer the model's full response$0.66 · 222.8s · 14.2k tok
I'll verify current Meta and Shopify implementation details before writing the guide.# Meta Conversion Tracking Implementation Guide ### Cedar & Coil — Arc Clip Lamp ($68 USD) — Shopify → Meta Pixel + Conversions API **Status:** Draft implementation plan. No campaign has launched and no performance data exists, so this document contains no benchmarks, forecasts, or claims about how much attribution any configuration will recover. **Audience:** A technical marketer with Shopify admin access, Meta Business Manager admin access, and the ability to deploy a small server-side service (or to work with a developer who can). --- ## 1. Recommended Architecture ### 1.1 The shape of it ``` ┌─────────────────────────────┐ Shopper's │ Shopify storefront + │ browser ───▶ │ Checkout (Web Pixel / │──▶ Meta Pixel (browser) │ custom pixel sandbox) │ event_id: purchase_5541 └─────────────┬───────────────┘ │ │ ├──▶ Meta │ order created/paid │ Events ┌─────────────▼───────────────┐ │ Manager Shopify ─────▶│ Your server (webhook │──▶ CAPI ────┘ (dedupe by webhook │ consumer + hashing + CAPI) │ /events event_name └─────────────────────────────┘ event_id: + event_id) purchase_5541 ``` Two independent transports send the **same logical event**, tagged with the **same identifier**, and Meta collapses them into one. ### 1.2 Why both are needed **The browser Pixel alone is fragile.** It depends on third-party-adjacent cookies, JavaScript execution, and the page actually loading long enough to fire. It is degraded or blocked by Safari ITP and Firefox ETP cookie lifetime caps, iOS App Tracking Transparency, content blockers and privacy extensions, ad-blocking DNS, network flakiness on mobile, and users who close the tab before the confirmation page finishes rendering. The loss is not random — it skews toward privacy-conscious and mobile-heavy segments, which for a renters/students/makers audience is likely a meaningful slice. **The Conversions API alone is also insufficient.** Server events originate from your infrastructure, so they carry no browser context unless you deliberately pass it. Without the `_fbp` browser cookie and the `_fbc` click identifier, match quality degrades and the server event can be harder to tie back to an ad click. The server also has no visibility into pre-purchase browsing behavior unless you instrument it, and it cannot observe a session that never reaches your backend. **Together they are complementary:** | | Browser Pixel | Conversions API | |---|---|---| | Rich browser identifiers (`_fbp`, `_fbc`, user agent, referrer) | Native | Only if you pass them through | | Survives ad blockers / ITP / tab closure | No | Yes | | Sees anonymous top-of-funnel browsing | Yes | Requires instrumentation | | Has verified purchase data (real order total, payment captured) | Approximate | Authoritative | | Can send late/corrected data (refunds, fraud cancellations) | No | Yes | The Pixel supplies identity and top-of-funnel signal; the server supplies reliability and truth about money. Deduplication is what keeps you from double-counting the overlap. ### 1.3 Non-negotiables before you build - **One Meta dataset (Pixel ID) for the store.** Multiple pixels firing on the same pages is the single most common cause of unexplainable event counts. - **Domain verification** for `cedarandcoil.com` in Business Manager Brand Safety settings. - **Aggregated Event Measurement:** configure and prioritize your 8 web events, with `Purchase` at priority 1. This governs what is measurable for iOS users who opted out of tracking. - **A system user access token**, not a personal one. Personal tokens die when the person leaves the business portfolio. Generate the CAPI token from a Business Manager system user with access to the dataset. - **The token lives in server environment variables only.** Never in theme code, never in a custom pixel, never in a repo. --- ## 2. Event Plan and Parameters Send four standard events. Resist the urge to add custom events before these four are clean — Meta's optimization and the AEM event prioritization both work best on standard events. ### 2.1 Parameters every event carries (browser and server) | Parameter | Notes | |---|---| | `event_name` | Exact standard casing: `ViewContent`, `AddToCart`, `InitiateCheckout`, `Purchase` | | `event_id` | Your deduplication key. See §3. Must be identical across Pixel and CAPI. | | `event_time` | Unix seconds. Server events must be within 7 days of now; aim for under a few minutes. | | `event_source_url` | The page URL where it happened. Must be on your verified domain. | | `action_source` | `"website"` for all four of these events | | `user_data.fbp` | The `_fbp` cookie value, sent raw (not hashed) | | `user_data.fbc` | Derived from the `fbclid` URL parameter or the `_fbc` cookie, sent raw | | `user_data.client_ip_address` | Server-side only, raw | | `user_data.client_user_agent` | Server-side only, raw. Must be the *shopper's* UA, not your server's. | | `user_data.external_id` | Hashed stable customer or anonymous ID | ### 2.2 Event-by-event **ViewContent** — fires on the Arc Clip Lamp product page. ``` content_type: "product" content_ids: ["<variant_id>"] // must match your catalog IDs content_name: "Arc Clip Lamp" value: 68.00 currency: "USD" ``` Include `value` and `currency` even though nothing has been purchased; it lets Meta learn the economic weight of the view. Fire once per product page view, not on scroll or re-render. **AddToCart** — fires on successful add-to-cart, after the cart mutation returns, not on button click. ``` content_type: "product" content_ids: ["<variant_id>"] contents: [{ id: "<variant_id>", quantity: 1, item_price: 68.00 }] value: 68.00 // quantity × item price currency: "USD" ``` **InitiateCheckout** — fires when the shopper enters checkout. ``` content_type: "product" content_ids: ["<variant_id>", ...] contents: [{ id: "<variant_id>", quantity: 1, item_price: 68.00 }] num_items: 1 value: 68.00 // cart subtotal currency: "USD" ``` **Purchase** — the event that funds your bidding. Send it from **both** transports. ``` content_type: "product" content_ids: ["<variant_id>", ...] // REQUIRED for catalog/DPA matching contents: [{ id: "<variant_id>", quantity: 1, item_price: 68.00 }] value: 68.00 // REQUIRED currency: "USD" // REQUIRED num_items: 1 order_id: "5541" // Shopify order id — secondary dedupe signal ``` ### 2.3 Rules that prevent silent breakage - **`value` is a number, not a string, and carries no currency symbol.** `68.00`, never `"$68.00"`. - **`currency` is a three-letter ISO 4217 code.** `"USD"`. If Cedar & Coil ever sells in multiple currencies, send the currency the customer was actually charged in — do not normalize to USD on your side. - **Decide once what `value` means on Purchase** — product subtotal, or subtotal plus shipping and tax — and apply it identically in Pixel and CAPI. A mismatch between the two transports is a classic cause of inflated revenue in Ads Manager. For a single-SKU DTC store, the cleanest definition is the net product revenue excluding shipping and tax. - **`content_ids` must match the IDs in your Meta product catalog exactly.** If the Shopify catalog feed publishes IDs like `shopify_US_8123456_44987654`, your events must send that string, not the bare variant ID. Mismatched IDs break dynamic ads and catalog attribution while still showing a "healthy" event count — which is why this fails quietly. Verify in Commerce Manager → Catalog → Diagnostics. - **Purchase fires once per order.** Confirmation pages get refreshed and bookmarked. Deterministic `event_id` (§3) protects you from this. --- ## 3. How Deduplication Actually Works ### 3.1 The mechanism Meta deduplicates when two received events share **both**: 1. the same `event_name`, and 2. the same `event_id` When that pair matches, Meta keeps one copy and discards the other. The retained event is generally the one that arrived first; the discarded one does not double-count in reporting, attribution, or optimization. Deduplication operates within a matching window — Meta documents roughly **48 hours** — so browser and server copies of the same event should be sent as close together as possible, ideally seconds apart. A server event delivered days later against a browser event will not reliably collapse. ### 3.2 Generating `event_id` correctly The critical constraint: **the browser and the server must independently arrive at the same string.** A random UUID generated in the browser is useless to your webhook consumer unless you deliberately transport it. Two workable patterns: **Pattern A — deterministic ID from a shared key (recommended for Purchase).** Derive the ID from something both sides already know: the Shopify order ID. ``` event_id = "purchase_" + order.id // e.g. "purchase_5541" ``` The browser reads the order ID on the confirmation page; the webhook receives it in the payload. No transport needed, both sides compute the same value, and repeated confirmation-page loads produce the same ID — so refreshes deduplicate against the original instead of inflating counts. **Pattern B — generate in browser, carry to server (for pre-purchase events).** Generate a UUID in the custom pixel, and persist it where the server can retrieve it — a cart attribute, a checkout note attribute, or a lightweight endpoint of your own. Use this for `InitiateCheckout` if you send it server-side; for `ViewContent` and `AddToCart` the pragmatic choice is browser-only, which sidesteps the problem entirely. ### 3.3 What not to do - **Do not send different `event_id` values and expect Meta to figure it out.** There is no fuzzy dedupe fallback you should rely on. `order_id` on Purchase provides an additional signal, but treat `event_id` parity as the mechanism and `order_id` as a backstop. - **Do not send only the server event "to be safe."** You lose browser identifiers and top-of-funnel signal. - **Do not suppress the Pixel when the server event succeeds.** Redundancy plus dedupe is the entire design; conditional firing recreates the fragility you are trying to remove. - **Do not reuse an `event_id` across different `event_name` values.** `purchase_5541` and `initiatecheckout_5541` are different strings for a reason. ### 3.4 A minimum-viable split | Event | Browser Pixel | Conversions API | |---|---|---| | ViewContent | ✅ | Optional | | AddToCart | ✅ | Optional | | InitiateCheckout | ✅ | Recommended | | **Purchase** | ✅ | **✅ Required** | Purchase is where server-side delivery matters most and where dedupe must be exactly right. Get Purchase correct first; extend upward afterward. --- ## 4. Preparing Customer Information for Server-Side Sending Server events carry no identity unless you attach it. Meta matches on hashed identifiers in `user_data`, and the quality of that preparation determines whether your events are attributable at all. ### 4.1 Hash these — SHA-256, hex-encoded, lowercase output | Field | Normalize before hashing | |---|---| | `em` (email) | Trim whitespace, lowercase. `Sam@Example.COM ` → `sam@example.com` | | `ph` (phone) | Digits only, include country code, strip `+`, spaces, dashes, parentheses. `(361) 234-5678` US → `13612345678` | | `fn` / `ln` | Trim, lowercase, remove punctuation. UTF-8 encoding. | | `ct` (city) | Lowercase, remove spaces and punctuation. `San Diego` → `sandiego` | | `st` (state) | Two-letter lowercase code. `California` → `ca` | | `zp` (zip) | Lowercase, first 5 digits for US; strip spaces for other formats | | `country` | Two-letter lowercase ISO 3166-1 alpha-2. `us` | | `db` (date of birth) | `YYYYMMDD`. Cedar & Coil has no reason to collect this — skip it. | | `external_id` | Your Shopify customer ID or a stable anonymous ID, hashed | ### 4.2 Do NOT hash these — send raw `fbp`, `fbc`, `client_ip_address`, `client_user_agent`, `subscription_id`, `lead_id`, `order_id`, and all event-level parameters (`value`, `currency`, `content_ids`, `contents`). Hashing a field that should be raw is a silent failure: the request returns HTTP 200 and the event is accepted, but the identifier never matches. ### 4.3 The rules that break implementations 1. **Normalize *then* hash. Always in that order.** `"Sam@Example.com "` and `"sam@example.com"` produce completely different hashes. A trailing space from a form field will quietly destroy match quality for that customer. 2. **Never send raw PII to the endpoint.** Hashing must happen on your server before the request is built. If you can read an email address in the outbound JSON, stop and fix it. 3. **Hash exactly once.** Double-hashing is a real and common bug in pipelines with multiple transformation layers. 4. **Omit empty fields; do not send hashes of empty strings.** A hash of `""` is a valid-looking 64-character string that matches nothing and can drag down your Event Match Quality. 5. **Capture `fbp` and `fbc` at the browser and carry them to the server.** This is the highest-leverage step for server-side match quality, because your backend cannot see cookies. Practical route on Shopify: read `_fbp` and `_fbc` in your custom pixel and write them into cart attributes so they arrive in the order payload. If a `fbclid` is present in the landing URL and no `_fbc` cookie exists yet, construct it as `fb.1.<timestamp_ms>.<fbclid>`. 6. **Pass the shopper's IP and user agent, not your server's.** If your webhook consumer sits behind a proxy or the data comes from a Shopify webhook, source these from the original browser context (captured client-side and carried through) rather than from the inbound webhook request. 7. **More identifiers is better than fewer — but only real ones.** Never synthesize, guess, or infer identity fields to raise a match-quality score. ### 4.4 What to send for the Arc Clip Lamp order flow Shopify's order payload gives you email, phone (if collected), billing/shipping name, city, province code, zip, country code, and customer ID. That is a strong `user_data` object. Add `fbp` and `fbc` from cart attributes, and `client_ip_address` / `client_user_agent` from the browser capture. Send `external_id` for both logged-in and guest checkouts (hash the Shopify customer ID for the former, a stable first-party cookie ID for the latter). --- ## 5. Concrete Shopify Setup Path ### 5.1 Option A — Native "Facebook & Instagram by Meta" sales channel Shopify's first-party Meta channel handles Pixel injection, server-side event forwarding, and catalog sync. Setup path: 1. Shopify admin → **Settings → Apps and sales channels → Shopify App Store** → add **Facebook & Instagram by Meta**. 2. Open the channel → **Settings → Data sharing**. Connect the correct Business portfolio, Page, Ad account, and Pixel/dataset. 3. Set **Customer data sharing** to **Maximum**. This is the level that turns on server-side event forwarding (Conversions API) in addition to browser events. "Standard" is browser-only. 4. Connect the product catalog so `content_ids` and catalog IDs align by construction. 5. **Remove any hardcoded Pixel snippet from `theme.liquid`, any legacy tracking app, and any duplicate custom pixel.** This is the step people skip, and it produces doubled events that will not deduplicate because the two sources generate different `event_id` values. **Strengths:** deduplication, hashing, normalization, and catalog ID alignment are handled by Shopify and Meta jointly. It survives Shopify checkout changes. It respects Shopify's Customer Privacy API automatically. Zero infrastructure and zero maintenance. **Limits:** you get the standard event set with standard parameters. You cannot easily add custom parameters, cannot send events from non-Shopify surfaces, cannot enrich with data from your CRM or subscription system, and you have limited visibility into the exact payloads being transmitted. Refund and cancellation handling is not under your control. ### 5.2 Option B — Custom implementation A Shopify **custom pixel** (in the pixel sandbox) for browser events, plus your own server consuming `orders/paid` webhooks and calling the Conversions API directly. **Strengths:** total control over payloads, `event_id` strategy, identity enrichment, and error handling. Extensible to future surfaces. **Costs:** you own a production service with a secret, webhook HMAC verification, retries, idempotency, monitoring, and ongoing compatibility with Meta's Graph API versioning. You also own every hashing bug you introduce. ### 5.3 Recommendation for Cedar & Coil **Start with Option A — the native Meta sales channel with Customer data sharing set to Maximum.** The reasoning for a small single-SKU DTC store: the native channel gets Pixel + CAPI + deduplication + catalog alignment working correctly with essentially no engineering surface area, and the failure modes it eliminates (bad hashing, mismatched `event_id`, misaligned catalog IDs, missing consent handling) are precisely the ones that cost the most time to diagnose. Cedar & Coil has one product, one currency, and no pre-launch performance data — there is nothing yet that requires custom payloads. **Adopt a hybrid later, when a specific need appears.** Concrete triggers to revisit: you need custom parameters for a segmentation strategy; you add subscriptions or a second sales surface; you need to send refunds or cancellations as negative signals; you need CRM-enriched identity. At that point, run the native channel for browser events and add your own server-side layer with deterministic `event_id` parity — or move fully custom. **If you do run both, discipline is mandatory:** every custom event you add must share `event_name` and `event_id` with its native counterpart, or you will double-count. ### 5.4 Code sketch — server-side Purchase (custom implementation) Illustrative Node/Express. Not production-hardened; treat as a structural reference. ```js import express from "express"; import crypto from "crypto"; const app = express(); 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 SHOPIFY_SECRET = process.env.SHOPIFY_WEBHOOK_SECRET; // --- normalize, then hash. Omit empties entirely. --- const sha256 = (v) => crypto.createHash("sha256").update(v, "utf8").digest("hex"); const hashEmail = (v) => v ? sha256(String(v).trim().toLowerCase()) : undefined; const hashText = (v) => v ? sha256(String(v).trim().toLowerCase().replace(/[^\p{L}\p{N}]/gu, "")) : undefined; const hashPhone = (v) => { const digits = String(v || "").replace(/\D/g, ""); // country code included, no '+' return digits ? sha256(digits) : undefined; }; const hashZip = (v) => v ? sha256(String(v).trim().toLowerCase().replace(/\s/g, "").slice(0, 5)) : undefined; const prune = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && v !== null && v !== "")); // --- Shopify webhook HMAC verification --- function verifyShopify(req, res, buf) { const sent = req.get("X-Shopify-Hmac-Sha256") || ""; const calc = crypto.createHmac("sha256", SHOPIFY_SECRET).update(buf).digest("base64"); const a = Buffer.from(sent), b = Buffer.from(calc); if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) throw new Error("bad hmac"); } app.post("/webhooks/orders-paid", express.raw({ type: "application/json", verify: verifyShopify }), async (req, res) => { res.sendStatus(200); // ack fast; Shopify retries on timeout const order = JSON.parse(req.body.toString("utf8")); // fbp / fbc / IP / UA captured by the custom pixel and written to cart attributes const attrs = Object.fromEntries((order.note_attributes || []).map(a => [a.name, a.value])); const ship = order.shipping_address || order.billing_address || {}; const user_data = prune({ em: hashEmail(order.email), ph: hashPhone(order.phone || ship.phone), fn: hashText(ship.first_name), ln: hashText(ship.last_name), ct: hashText(ship.city), st: hashText(ship.province_code), zp: hashZip(ship.zip), country: hashText(ship.country_code), external_id: order.customer?.id ? sha256(String(order.customer.id)) : undefined, fbp: attrs._fbp, // RAW — never hashed fbc: attrs._fbc, // RAW client_ip_address: attrs._client_ip, // RAW, shopper's IP client_user_agent: attrs._client_ua // RAW, shopper's UA }); const contents = order.line_items.map(li => ({ id: String(li.variant_id), // MUST match catalog IDs quantity: li.quantity, item_price: Number(li.price) })); const payload = { data: [{ event_name: "Purchase", // Deterministic: the custom pixel computes the identical string on the // confirmation page, so Meta collapses the browser and server copies. event_id: `purchase_${order.id}`, event_time: Math.floor(new Date(order.created_at).getTime() / 1000), event_source_url: attrs._event_source_url || "https://cedarandcoil.com/checkout/thank-you", action_source: "website", user_data, custom_data: { currency: order.currency, // "USD" value: Number(order.current_subtotal_price), // one definition, both transports 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) } // opt_out: true // set when marketing consent was not granted (see §7) }] // test_event_code: "TEST12345" // ONLY while validating; remove before launch }; const url = `https://graph.facebook.com/${API_VERSION}/${PIXEL_ID}/events` + `?access_token=${encodeURIComponent(ACCESS_TOKEN)}`; const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }); const body = await r.json(); if (!r.ok) console.error("CAPI error", r.status, body); // queue for retry with backoff else console.log("CAPI ok", body); // { events_received, messages, fbtrace_id } }); app.listen(3000); ``` **Operational notes on this sketch** - **Idempotency:** Shopify retries webhooks. Key on `order.id` in a short-lived store so you do not re-POST. Deterministic `event_id` protects reporting even if you do, but a resend is still wasted work. - **Retries:** treat 5xx and network errors as retryable with exponential backoff; treat 4xx as a payload bug to fix, not to retry. - **Never log the raw order payload** — it contains PII. Log hashes, IDs, and `fbtrace_id`. - **Graph API versions expire.** Pin the version, and put a calendar reminder to review it. - **Refunds:** send a `Purchase` with a negative `value` and the *original* `order_id`, using a distinct `event_id`, if you decide to feed refund signal back to Meta. --- ## 6. End-to-End Validation Before Scaling Spend Work through these gates in order. Do not increase budget past a small test until gates 1–6 pass. **Gate 1 — Test Events (browser).** Events Manager → your dataset → **Test Events**. Open the store in a clean browser profile with the test code appended. Walk the Arc Clip Lamp funnel: product page → add to cart → checkout → complete a real order using Shopify's Bogus Gateway or a test-mode payment. Confirm `ViewContent`, `AddToCart`, `InitiateCheckout`, `Purchase` each appear exactly once with the expected parameters. **Gate 2 — Test Events (server).** Confirm the same Purchase appears with source **Server**. If it does not, check webhook delivery in Shopify admin → Notifications → Webhooks, and check your server logs for the CAPI response body — `events_received: 1` with warnings in `messages` is a partial success worth reading carefully. **Gate 3 — Deduplication confirmed.** In Test Events, the browser and server Purchase should appear as one event showing both connection methods, or the server copy should be flagged as deduplicated. After 24–48 hours of live traffic, check the dataset **Overview → Purchase → Connection method / deduplication** indicator. If Meta reports duplicates rather than deduplication, your `event_id` strings are not matching — log both values side by side and compare them literally, character for character. **Gate 4 — Parameter and value integrity.** Verify on a real test order: - `value` is numeric and matches your chosen definition on **both** transports - `currency` is `USD` - `content_ids` are present on Purchase and identical to your catalog IDs - No raw email, phone, or name appears anywhere in the outbound payload - No hash of an empty string is being sent **Gate 5 — Catalog alignment.** Commerce Manager → Catalog → **Diagnostics**. Look specifically for content ID mismatch warnings. This can fail while every event count looks perfectly healthy. **Gate 6 — Event Match Quality and diagnostics.** Events Manager → dataset → **Diagnostics** tab. Resolve every error and every warning; several are severe but easy to miss (missing `event_source_url`, unverified domain, invalid parameter format, server event missing user data). Then check **Event Match Quality** per event. Treat EMQ as a diagnostic of your identifier pipeline, not as a performance metric and not as a target to game. If Purchase EMQ is low, the usual causes are missing `fbp`/`fbc`, a hashing normalization bug, or omitted email. **Gate 7 — Volume reconciliation.** After 3–7 days of live traffic, compare Shopify's order count for a fixed window against Meta's Purchase count for the same window (using Ads Manager with a matching date range and the dataset view, not attributed conversions). They will not match exactly — attribution windows, consent-denied events, and dedupe timing all create legitimate gaps. What you are looking for is a *stable, explainable* relationship, not a moving one. A Meta count materially **above** Shopify's order count is an alarm: it almost always means double-firing. **Gate 8 — Ongoing monitoring.** Set up, before you scale: - A weekly Diagnostics review - An alert on your server for CAPI non-200 rates - An alert if daily server Purchase count drops sharply or diverges from Shopify order count - A re-validation checklist to run after **any** theme change, app install, or Shopify checkout update — these are the events that silently break pixels **Also verify explicitly:** that no duplicate Pixel is firing (search the rendered page source for your Pixel ID and for `fbevents.js`; the Meta Pixel Helper extension will flag multiples), and that events still behave correctly in Safari with cross-site tracking prevention on and in a browser with an ad blocker enabled — the second case is exactly where your server events must carry the load. --- ## 7. Consent and Compliance **Consent gates collection; it is not something you retrofit.** Hashing is not consent. Server-side delivery is not a way around a user's choice — sending a hashed email from your backend after a shopper declined marketing cookies is still processing their personal data, and regulators treat it that way. **Use Shopify's Customer Privacy API as the single source of truth.** Shopify exposes consent state to pixels via `init.customerPrivacy` and the `visitorConsentCollected` event, with flags including `marketingAllowed`, `analyticsProcessingAllowed`, `preferencesProcessingAllowed`, and `saleOfDataAllowed`. Your custom pixel should read this state and gate firing on it, and your server-side path must receive the same signal — pass the consent state through cart attributes alongside `fbp`/`fbc` so the webhook consumer knows what it is allowed to do. **When marketing consent is absent or denied:** do not send identifying `user_data`. If you send the event at all for aggregate measurement, set `opt_out: true` on the payload, which tells Meta not to use it for ad personalization or retargeting. For US state privacy laws, use Meta's Limited Data Use via the `data_processing_options` fields (`["LDU"]`) rather than inventing your own suppression logic. **Deploy a consent management platform if Cedar & Coil serves the EU/UK.** Shopify's built-in banner can work for basic cases, but GDPR/ePrivacy generally require prior opt-in for advertising cookies, granular purposes, and equally easy withdrawal. Verify the CMP actually writes to Shopify's Customer Privacy API rather than only blocking scripts cosmetically. **Contractual and policy obligations.** Using the Conversions API means accepting Meta's Business Tools Terms and, where applicable, the Customer Data Terms — including representations that you have a lawful basis to share the data. Update Cedar & Coil's privacy policy to disclose advertising measurement, the categories of data shared, and the recipients, and provide a working opt-out and data-deletion path. If you have or need a DPA with Meta, get it in place before launch, not after. **Never send restricted or sensitive data.** Meta's terms prohibit health, financial account, sexual orientation, precise government identifiers, and similar special categories — including in hashed form, including in custom parameters. Nothing in the Arc Clip Lamp funnel should ever produce such data, so a simple allowlist of permitted `user_data` fields in your server code is cheap insurance. **Data minimization and retention.** Send the identifiers you actually need for matching, and nothing else. Do not persist raw PII in your CAPI service; hash in memory and discard. Do not log payloads containing personal data. Set short retention on webhook queues and logs. **Children and audience.** The stated audience is renters, students, and makers — confirm your targeting and any lookalike sourcing do not reach minors, and that no audience is built from a source lacking consent. **Cross-border transfers.** If EU/UK personal data is involved, confirm the transfer mechanism in your Meta agreements is current, and document it. --- ## Rollout Sequence 1. Consolidate to one Pixel ID; remove legacy snippets and duplicate apps. 2. Verify the domain; configure AEM with Purchase at priority 1. 3. Deploy the CMP and confirm it writes real consent state to Shopify's Customer Privacy API. 4. Install the Meta sales channel; set Customer data sharing to **Maximum**; connect the catalog. 5. Run Gates 1–6 with test orders. 6. Launch a small test budget. Run Gates 7–8 for a week. 7. Only then scale, and re-run the checklist after any theme, app, or checkout change. --- **Two closing cautions.** First, this guide deliberately makes no claim about how many conversions any configuration will recover, because that depends on your traffic mix, consent rates, and browser distribution — and Cedar & Coil has no campaign data to reason from. Measure your own baseline before and after. Second, verify each configuration step against Meta's current Conversions API documentation and Shopify's Web Pixels API documentation at implementation time; both platforms change their requirements, parameter sets, and API versions on their own schedule.
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 explains Pixel fragility (ITP, ETP, ATT, ad blockers) and CAPI's lack of browser context, concluding both are needed with a comparison table.
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.2 lists ViewContent, AddToCart, InitiateCheckout, and Purchase each with content_ids, value, and currency, with Purchase explicitly marking content_ids/value/currency as REQUIRED.
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/Express sketch in 5.4 includes event_name: 'Purchase', event_id, event_time, action_source: 'website', and a constructed 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 6 Gate 1/2 uses Events Manager Test Events for browser and server, and Gate 3 explicitly checks that browser/server Purchase events are shown 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).
✓Section 3.4's table specifies which events are browser-only vs server-required, and the code sketch sources Purchase from the Shopify 'orders-paid' webhook rather than the thank-you page alone.
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 section states 'this guide deliberately makes no claim about how many conversions any configuration will recover' and Section 7 treats consent as a hard gate 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.1 states Meta deduplicates when two events share both the same event_name and the same event_id, matching the correct mechanism rather than a vague mention.
event_id_retry_stability
The event_id is generated or derived once per commerce event, shared by browser and server, and reused unchanged on webhook retries or order updates; a new random suffix per send or retry fails.
✓The guide uses a deterministic event_id = 'purchase_' + order.id, explicitly noting 'repeated confirmation-page loads produce the same ID' and discussing idempotency on webhook retries.
event_time_stable
The server Purchase event uses the purchase/order occurrence timestamp in Unix seconds and preserves it across retries; using the current send or retry time fails.
✓The code sets event_time via Math.floor(new Date(order.created_at).getTime()/1000), deriving it from the order's actual creation time rather than the send/retry time.
pii_hashing
Customer data handling is correct: personally identifiable fields (e.g. email) are normalized (trimmed, lowercased) and SHA-256 hashed before sending in user_data.
✓Section 4.1 and the hashEmail function trim and lowercase the email before SHA-256 hashing, explicitly stating 'Normalize *then* hash. Always in that order.'
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.3 gives a decisive recommendation ('Start with Option A — the native Meta sales channel with Customer data sharing set to Maximum') with concrete numbered setup steps in 5.1.