← Run 20260825-234438-8373ba31
Shopify to Meta ads conversion tracking implementation
task shopify-meta-capiAug 25, 2026

Answers & verdicts

GPT-5.6 Luna medium 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.006 · 51.2s · 4.9k tok
# Meta Conversion Tracking Implementation Guide for Cedar & Coil ## 1. Recommended architecture Use both: 1. **Browser-side Meta Pixel** 2. **Server-side Meta Conversions API (CAPI)** The recommended flow is: ```text Shopify storefront ├─ Browser Pixel events └─ Shopify/server-side CAPI events ↓ Meta Pixel/Dataset ``` ### Why use both? **Browser Pixel** - Captures actions directly in the shopper’s browser. - Supports page and interaction events such as product views and add-to-cart. - Provides browser identifiers such as `_fbp` and, where available, `_fbc`. - Is relatively simple to implement through Shopify’s native Meta integration. **Conversions API** - Sends events from Shopify or a server directly to Meta. - Is less dependent on browser JavaScript, ad blockers, cookie restrictions, and browser tracking prevention. - Can use first-party order data for reliable Purchase events. - Can include server-observed information such as the order value, currency, customer email, phone, IP address, and user agent, subject to consent and applicable law. CAPI is not a way to bypass privacy requirements. Events and customer information should only be sent when Cedar & Coil has the appropriate legal basis and the shopper’s consent is required. ### Important design principle Send the same conversion through both channels when appropriate, but give the browser and server copies the **same `event_name` and `event_id`**. Meta then deduplicates them rather than counting two conversions. --- ## 2. Standard events and required parameters Use Meta standard events with consistent product identifiers. The `content_ids` values must match the IDs used in the Meta catalog. For Shopify, this is commonly a product or variant ID, depending on how the catalog is configured. For the Arc Clip Lamp, use the actual Shopify product or variant ID rather than a hand-written name such as `arc-clip-lamp`. ### `ViewContent` Fire when a shopper views the Arc Clip Lamp product page. Recommended parameters: ```js { content_ids: ["shopify_variant_or_product_id"], content_type: "product", value: 68.00, currency: "USD" } ``` Use the displayed or selected variant price. If the product has variants, use the selected variant’s ID and price. Example: ```js fbq("track", "ViewContent", { content_ids: ["arc-lamp-variant-001"], content_type: "product", value: 68.00, currency: "USD" }, { eventID: "viewcontent_<unique_event_id>" }); ``` ### `AddToCart` Fire after the shopper successfully adds the item to the cart. Recommended parameters: ```js { content_ids: ["shopify_variant_or_product_id"], content_type: "product", value: 68.00, currency: "USD", contents: [ { id: "shopify_variant_or_product_id", quantity: 1, item_price: 68.00 } ] } ``` For multiple items, include each line item in `contents` and use the cart subtotal or other consistently defined cart value. ### `InitiateCheckout` Fire when the shopper begins checkout, not merely when the cart page is viewed. Recommended parameters: ```js { content_ids: ["shopify_variant_or_product_id"], content_type: "product", value: 68.00, currency: "USD", num_items: 1, contents: [ { id: "shopify_variant_or_product_id", quantity: 1, item_price: 68.00 } ] } ``` For a multi-item cart: - `value`: checkout subtotal or the consistently selected checkout value - `num_items`: total quantity - `contents`: all line items ### `Purchase` Fire when the order is successfully completed or marked paid according to the chosen Shopify implementation. Required and recommended parameters: ```js { value: 68.00, currency: "USD", content_ids: ["shopify_variant_or_product_id"], content_type: "product", contents: [ { id: "shopify_variant_or_product_id", quantity: 1, item_price: 68.00 } ], order_id: "shopify_order_id" } ``` For Purchase, use: - The actual order value defined by the implementation, preferably consistently using the final transaction amount or subtotal. - The ISO currency code, such as `USD`. - Every purchased product or variant in `content_ids`. - `contents` with item IDs, quantities, and item prices. - A Shopify order identifier in `order_id` or an equivalent custom parameter for internal reconciliation. Do not hard-code `$68` for all purchases if discounts, multiple quantities, shipping, taxes, or future pricing can change the transaction value. --- ## 3. Exactly how deduplication works Meta deduplicates a browser event and a CAPI event when they have: 1. The same destination Pixel/Dataset 2. The same `event_name` 3. The same `event_id` For example, the browser and server copies of a Purchase should both contain: ```text event_name: Purchase event_id: purchase_987654 ``` The browser version: ```js fbq("track", "Purchase", { value: 68.00, currency: "USD", content_ids: ["arc-lamp-variant-001"], content_type: "product" }, { eventID: "purchase_987654" }); ``` The CAPI version: ```json { "event_name": "Purchase", "event_id": "purchase_987654" } ``` Meta uses the matching event name and event ID to treat the two submissions as one event rather than two Purchases. ### Purchase ID strategy For an order-based Purchase event, derive the ID deterministically from the Shopify order: ```text purchase_<shopify_order_id> ``` This allows: - The browser Purchase on the thank-you page to use the same ID. - The server webhook or order-processing job to use the same ID. - Retries to remain idempotent instead of generating additional Purchase IDs. For ViewContent, AddToCart, and InitiateCheckout, generate one unique event ID per user action and pass it to both channels if both channels send that event. Do not generate one random ID for the Pixel and a different random ID for CAPI. Meta will not know they represent the same event. Also avoid firing multiple browser Purchases on thank-you-page reloads. Use the order ID and a client-side guard, while retaining the server-side order-level idempotency check. --- ## 4. Preparing customer information for server-side events CAPI accepts `user_data` to help Meta match an event to an ad interaction. Prepare each field according to Meta’s requirements. ### Normalize before hashing For fields that Meta expects hashed: - Trim leading and trailing whitespace. - Convert email addresses to lowercase. - Normalize phone numbers to international E.164 format, such as `+14155550123`. - Normalize country codes to the expected two-letter format. - Normalize names and other fields according to Meta’s current CAPI specifications. - SHA-256 hash the normalized value. - Do not hash fields that Meta explicitly expects in plain form, such as IP address and user agent. Example email preparation: ```js const crypto = require("crypto"); function sha256(value) { return crypto .createHash("sha256") .update(value) .digest("hex"); } function normalizeEmail(email) { return email.trim().toLowerCase(); } const hashedEmail = sha256(normalizeEmail("Customer@example.com")); ``` ### Common `user_data` fields Potential fields include: - `em`: SHA-256 hash of normalized email - `ph`: SHA-256 hash of normalized phone - `fn`: SHA-256 hash of normalized first name - `ln`: SHA-256 hash of normalized last name - `ct`: SHA-256 hash of normalized city - `st`: SHA-256 hash of normalized state or region - `zp`: SHA-256 hash of normalized postal code - `country`: SHA-256 hash of the normalized country code - `external_id`: A stable, appropriately protected Shopify customer identifier - `client_ip_address`: The client IP address, when lawfully collected and available - `client_user_agent`: The browser user-agent string - `fbp`: The browser `_fbp` identifier - `fbc`: The browser `_fbc` identifier, when available from a valid Meta click identifier Do not send sensitive information such as passwords, payment card numbers, health information, or unnecessary free-form customer data. ### Browser identifiers Where permitted, preserve and pass: - `_fbp` as `fbp` - `_fbc` as `fbc` A browser event may have these values available in cookies. A server-side order event can receive them from the browser context, Shopify customer event data, checkout metadata, or another lawful first-party handoff. Do not fabricate them. ### Data quality rules - Send only fields that are actually available. - Do not substitute placeholder values. - Do not hash an already hashed value again. - Keep the same customer information consistent between events where appropriate. - Follow Meta’s current Conversions API schema because field names and requirements can change. --- ## 5. Concrete Shopify setup path ### Option A: Native Meta sales channel app For a small DTC store, this is the recommended starting point. Typical setup path: 1. In Shopify Admin, install or open **Facebook & Instagram by Meta** under **Sales channels**. 2. Connect the relevant: - Meta Business Portfolio - Ad account - Facebook Page, if used - Instagram account, if used - Meta Pixel/Dataset - Product catalog 3. In the data-sharing settings, select the highest level appropriate for Cedar & Coil’s consent and legal requirements. Shopify commonly presents options such as Standard, Enhanced, or Maximum; the exact labels may change. 4. Configure Shopify customer privacy and consent settings for the regions where the store operates. 5. Verify the website domain in Meta Business Settings. 6. Confirm that the Arc Clip Lamp product and its variant IDs are present in the Meta catalog. 7. Allow the native integration to install the browser and server-side tracking components. 8. In Meta Events Manager, confirm the selected Pixel/Dataset is receiving events. #### Advantages - Fastest implementation. - Shopify handles much of the browser/server event wiring. - Better compatibility with Shopify checkout than a theme-only script. - Less custom infrastructure and fewer secrets to manage. - Often supports automatic catalog and product-ID mapping. #### Limitations - Less control over event payloads and unusual business logic. - Shopify and Meta UI names or behavior can change. - Custom event timing and advanced order-processing workflows may require additional work. - Data-sharing settings still need to be configured correctly. For Cedar & Coil’s current size and single-product catalog, the native integration should generally be used first. A custom implementation is justified if the store needs custom server workflows, special consent routing, a data warehouse integration, or precise control over event payloads. ### Option B: Custom implementation A custom implementation generally consists of: 1. A Shopify Web Pixel or approved customer-event integration for browser events. 2. A secure backend service or serverless function for CAPI. 3. A Shopify webhook, such as an order-paid or order-created workflow, for Purchase. 4. A secure Meta access token stored only on the server. 5. A durable event log or idempotency table keyed by event ID. 6. Consent checks before forwarding events. 7. Product and variant ID mapping that matches the Meta catalog. Do not put the Meta access token in theme JavaScript, Liquid templates, or any browser-visible code. ### Server-side Purchase request code sketch The following is illustrative Node.js code. The exact Shopify webhook payload and Graph API version should be adapted to the current APIs. ```js 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_API_VERSION = process.env.META_API_VERSION || "vXX.X"; function sha256(value) { return crypto .createHash("sha256") .update(value) .digest("hex"); } function normalizedHash(value) { return value ? sha256(String(value).trim().toLowerCase()) : undefined; } function compact(obj) { return Object.fromEntries( Object.entries(obj).filter(([, value]) => value !== undefined && value !== null) ); } export async function sendPurchaseToMeta(order, requestContext = {}) { // Use a stable order identifier. Do not generate a new ID on retries. const eventId = `purchase_${order.id}`; const contents = order.line_items.map((line) => ({ id: String(line.variant_id || line.product_id), quantity: Number(line.quantity), item_price: Number(line.price) })); const contentIds = contents.map((item) => item.id); const userData = compact({ em: order.email ? [normalizedHash(order.email)] : undefined, ph: order.phone ? [normalizedHash(order.phone)] : undefined, // Pass these only if collected lawfully and normalized correctly. external_id: order.customer_id ? [normalizedHash(String(order.customer_id))] : undefined, client_ip_address: requestContext.clientIp, client_user_agent: requestContext.userAgent, fbp: requestContext.fbp, fbc: requestContext.fbc }); const event = { event_name: "Purchase", event_time: Math.floor( new Date(order.processed_at || Date.now()).getTime() / 1000 ), event_id: eventId, action_source: "website", event_source_url: requestContext.eventSourceUrl || "https://cedarandcoil.example/checkout/complete", user_data: userData, custom_data: { value: Number(order.total_price), currency: order.currency || "USD", content_ids: contentIds, content_type: "product", contents, order_id: String(order.id) } }; const endpoint = `https://graph.facebook.com/${META_API_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({ data: [event] // Add test_event_code here only during testing, not normal production traffic: // test_event_code: process.env.META_TEST_EVENT_CODE }) }); const result = await response.json(); if (!response.ok) { throw new Error(`Meta CAPI error: ${JSON.stringify(result)}`); } return result; } ``` Production implementation should also: - Verify Shopify webhook signatures. - Store the event ID before or while sending. - Retry transient failures without changing the event ID. - Prevent duplicate processing of the same Shopify order. - Monitor Meta API errors and response diagnostics. - Use the final order amount and correct currency according to the store’s accounting definition. --- ## 6. End-to-end validation before scaling spend Run a controlled test order before launching campaigns. ### A. Confirm the browser events Using Meta Events Manager’s **Test Events** tool and browser developer tools: 1. Open the Arc Clip Lamp product page. 2. Confirm one `ViewContent`. 3. Add the lamp to cart. 4. Confirm one `AddToCart`. 5. Begin checkout. 6. Confirm one `InitiateCheckout`. 7. Complete a test purchase. 8. Confirm one `Purchase`. Check each event for: - Correct event name. - Correct Pixel/Dataset. - Correct `value`. - Correct `currency`. - Correct `content_ids`. - Correct `contents`. - Correct `event_id`. - Correct `event source URL`. ### B. Confirm CAPI events For server events: 1. Use Meta Events Manager’s Test Events feature. 2. Send the test event with the current `test_event_code`. 3. Complete a test order or invoke the webhook in a controlled environment. 4. Confirm the server event appears. 5. Review warnings, match-quality feedback, and rejected parameters. 6. Remove the test code before production traffic. ### C. Confirm deduplication For the test Purchase, verify that: - Browser and server events use the same event name: `Purchase`. - Both use the same event ID, such as `purchase_123456`. - Events go to the same Pixel/Dataset. - Events Manager identifies the events as deduplicated or does not count two Purchases. - Reloading the confirmation page does not create another Purchase. - Retrying the webhook does not create another Purchase. ### D. Reconcile against Shopify Compare the test order with Meta’s received event: - Shopify order ID - Product or variant IDs - Quantity - Order value - Currency - Timestamp - Customer information fields sent - Consent status ### E. Check catalog matching In Commerce Manager, confirm that the IDs in `content_ids` match catalog item IDs. Incorrect IDs can prevent useful product-level reporting and retargeting even if the event itself is received. ### F. Test privacy states Repeat the test with: - Consent granted. - Consent declined. - A browser with cookies restricted. - An ad blocker enabled, where appropriate for testing. Confirm that the store’s consent behavior is intentional and that server-side sending is not being used to override a shopper’s opt-out. ### G. Monitor after launch Before increasing spend, monitor: - Event diagnostics in Events Manager. - Browser/server event volume. - Deduplication status. - Purchase count versus Shopify paid orders. - Value and currency consistency. - Catalog match quality. - Webhook failures and retries. Do not infer performance from a single test order, and do not assume that server-side tracking restores all otherwise-unavailable attribution. --- ## 7. Consent and compliance note Meta tracking must follow the laws and policies applicable to Cedar & Coil’s shoppers and business locations. At minimum: - Configure Shopify’s customer privacy and consent tools for the relevant regions. - Obtain consent where required before placing non-essential marketing cookies or sending marketing events. - Respect opt-outs and withdrawal of consent across both browser Pixel and CAPI. - Do not send server-side events merely because browser tracking was blocked. - Document the lawful basis, data flows, vendors, and retention practices. - Disclose Meta Pixel and Conversions API usage in the privacy and cookie notices. - Send only the minimum customer information needed for measurement. - Hash the fields Meta requires to be hashed, while recognizing that hashing is pseudonymization—not complete anonymization. - Never send payment card information, passwords, or other unnecessary sensitive data. - Keep the CAPI access token server-side. - Review Meta’s Business Tools Terms and current Conversions API documentation before production deployment. The native Shopify Meta sales channel is the preferred implementation for this small store, provided its data-sharing and consent settings are configured to match Cedar & Coil’s compliance requirements.
Score the judge's verdict, criterion by criterion11/11 criteria passed
RequirementVerdictEvidence
architecture
The guide recommends browser Pixel plus server-side Conversions API with deduplication and explains why both are needed under browser privacy limits.
✓The guide explains browser Pixel + CAPI need, citing ad blockers, cookie restrictions, and dedup design principle.
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓All four events (ViewContent, AddToCart, InitiateCheckout, Purchase) are given with value, currency, and content_ids parameters, including 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 sendPurchaseToMeta function includes event_name, event_time, event_id, action_source, 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 6 explicitly uses Meta Events Manager's Test Events tool and includes a 'Confirm deduplication' subsection checking for matching event IDs and no double counting.
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 and 5 specify Purchase should come from a Shopify order webhook/server process with the same event_id as the thank-you-page browser event, guarded against duplicate firing.
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 assume that server-side tracking restores all otherwise-unavailable attribution' and repeatedly ties data sending to consent and regional legal requirements.
dedup_correct
Deduplication is technically correct: the same event_id and event_name sent on both the Pixel and CAPI event so Meta drops the duplicate; not a vague mention.
✓Section 3 correctly states Meta deduplicates events sharing the same event_name and event_id across Pixel and CAPI, with concrete matching 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 derives event_id as `purchase_<shopify_order_id>` and explicitly instructs 'Retry transient failures without changing the event ID.'
event_time_stable
The server Purchase event uses the purchase/order occurrence timestamp in Unix seconds and preserves it across retries; using the current send or retry time fails.
✓The code computes event_time from `order.processed_at` in Unix seconds rather than the current send time, preserving the original order timestamp across retries.
pii_hashing
Customer data handling is correct: personally identifiable fields (e.g. email) are normalized (trimmed, lowercased) and SHA-256 hashed before sending in user_data.
✓Email is trimmed, lowercased, and SHA-256 hashed via the normalizeEmail/sha256 functions before inclusion 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).
✓The guide decisively recommends the native Meta sales channel app for a small DTC store with a numbered concrete setup path (steps 1-8).

GPT-5.6 Terra medium 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.089 · 78.7s · 7.3k tok
# Cedar & Coil Meta Conversion Tracking Implementation Guide This guide is for tracking Shopify conversions for the Arc Clip Lamp into Meta in a way that is more resilient to browser privacy restrictions while respecting customer consent. Use this as an implementation plan before launching Meta ads. Do not treat it as a promise of a particular attribution or match-rate outcome. --- ## 1. Recommended architecture: Meta Pixel + Conversions API ### Recommended setup Implement both: 1. **Browser-side Meta Pixel** - Runs in the shopper’s browser. - Sends standard website events to Meta as customers view the Arc Clip Lamp, add it to cart, begin checkout, and purchase. 2. **Server-side Meta Conversions API (CAPI)** - Sends the same important events from a trusted server-side environment, such as Shopify’s native Meta integration or a Cedar & Coil tracking service receiving Shopify webhooks. - Is less dependent on browser cookies, ad blockers, JavaScript execution, and browser privacy controls. 3. **Event deduplication** - Required whenever both Pixel and CAPI send the same conversion event. - Prevents Meta from counting one customer action twice. ### Why both are needed | Component | Strengths | Limitations | |---|---|---| | Browser Pixel | Captures browser context, page URL, Meta click/browser identifiers, and immediate shopper interactions. | Can be blocked by privacy settings, ad blockers, cookie restrictions, network failures, or JavaScript failures. | | Conversions API | Sends events from Shopify/server systems and can continue to report some events when browser delivery is impaired. | Does not automatically have all browser context unless it is intentionally passed to the server. Must be implemented securely and with consent controls. | | Combined setup | Gives Meta browser and server signals for the same conversion, with deduplication. | Requires consistent event names, IDs, product identifiers, and consent handling. | CAPI is not a workaround for consent requirements. It is a different transport method for data that Cedar & Coil is permitted to process and disclose. --- ## 2. Standard events and required parameters Track these four Meta standard events: 1. `ViewContent` 2. `AddToCart` 3. `InitiateCheckout` 4. `Purchase` Use the same product identifier convention across: - Shopify product/variant data - Meta catalog, if used for dynamic ads - Browser Pixel events - CAPI events For a single-product store, it is still best to use the **Shopify variant ID** consistently, rather than mixing product IDs, handles, SKUs, and variant IDs. Example internal content ID convention: ```text shopify_variant_1234567890 ``` If Meta catalog items use raw Shopify variant IDs instead, use those raw IDs everywhere. The exact format matters less than consistency. ### Event parameter requirements | Event | Trigger | Important parameters | |---|---|---| | `ViewContent` | A shopper views the Arc Clip Lamp product page. | `content_ids`, `content_type`, `contents`, `value`, `currency` | | `AddToCart` | The shopper adds the lamp to cart. | `content_ids`, `content_type`, `contents`, `value`, `currency` | | `InitiateCheckout` | The shopper begins checkout. | `content_ids`, `content_type`, `contents`, `value`, `currency`, `num_items` | | `Purchase` | The order is completed according to the selected business rule, usually checkout completion or paid-order confirmation. | `content_ids`, `content_type`, `contents`, `value`, `currency`, `order_id` or `event_id` | ### 2.1 `ViewContent` Send when the Arc Clip Lamp product-detail page loads. Example payload parameters: ```json { "event_name": "ViewContent", "content_ids": ["shopify_variant_1234567890"], "content_type": "product", "contents": [ { "id": "shopify_variant_1234567890", "quantity": 1, "item_price": 68.00 } ], "value": 68.00, "currency": "USD" } ``` Notes: - `value` should represent the currently displayed purchasable variant price. - `currency` must use ISO 4217 format, such as `USD`. - The Arc Clip Lamp price is currently `$68`, but event values should come from Shopify data rather than hard-coded campaign code. ### 2.2 `AddToCart` Send once per successful add-to-cart action. ```json { "event_name": "AddToCart", "content_ids": ["shopify_variant_1234567890"], "content_type": "product", "contents": [ { "id": "shopify_variant_1234567890", "quantity": 1, "item_price": 68.00 } ], "value": 68.00, "currency": "USD" } ``` If a shopper adds multiple quantities, use the cart line quantity and appropriate line value. ### 2.3 `InitiateCheckout` Send when the shopper takes the meaningful action that starts checkout, not merely when they view the cart. ```json { "event_name": "InitiateCheckout", "content_ids": ["shopify_variant_1234567890"], "content_type": "product", "contents": [ { "id": "shopify_variant_1234567890", "quantity": 1, "item_price": 68.00 } ], "num_items": 1, "value": 68.00, "currency": "USD" } ``` For carts with multiple line items: - Include all item IDs in `content_ids`. - Include one entry per line in `contents`. - Set `num_items` to the total item quantity. - Set `value` to the checkout/cart subtotal or total according to Cedar & Coil’s documented tracking convention. ### 2.4 `Purchase` Send once per completed order. ```json { "event_name": "Purchase", "content_ids": ["shopify_variant_1234567890"], "content_type": "product", "contents": [ { "id": "shopify_variant_1234567890", "quantity": 1, "item_price": 68.00 } ], "value": 68.00, "currency": "USD", "order_id": "CC-1001" } ``` For `Purchase`, make sure the following are always present: - `value` - `currency` - `content_ids` - `contents` - A stable order reference, such as `order_id` - A unique event ID for deduplication when Pixel and CAPI both send the purchase ### Value convention Document one convention and use it consistently. A practical default is: ```text Purchase value = final order total charged to the customer ``` Determine whether that includes shipping, tax, discounts, and gift cards based on Cedar & Coil’s reporting preference, then keep the implementation consistent across Pixel, CAPI, and internal reporting. Do not send a product price from the page if the actual order contains discounts, multiple items, shipping, or tax. Use final Shopify order data for server-side `Purchase` events. --- ## 3. Exactly how Pixel/CAPI deduplication works When both the browser Pixel and server-side CAPI report the same shopper action, Meta needs to recognize them as one event. ### Deduplication rule For the same Meta dataset/Pixel, send: - The same `event_name` - The same `event_id` to both the browser Pixel and the CAPI request. For example: | Delivery method | Event name | Event ID | |---|---|---| | Browser Pixel | `Purchase` | `purchase_987654321` | | CAPI | `Purchase` | `purchase_987654321` | Meta uses the matching event name and event ID to identify the browser and server records as the same conversion and count one conversion rather than two. ### Browser Pixel example ```javascript fbq( 'track', 'Purchase', { value: 68.00, currency: 'USD', content_type: 'product', content_ids: ['shopify_variant_1234567890'] }, { eventID: 'purchase_987654321' } ); ``` Important: Browser Pixel uses `eventID` with capital `ID`. ### CAPI example ```json { "event_name": "Purchase", "event_id": "purchase_987654321" } ``` Important: CAPI uses `event_id` with an underscore. ### Requirements for reliable deduplication For every event sent from both systems: 1. Use the same Meta Pixel/data source ID. 2. Use the identical standard event name: - `Purchase` must match `Purchase` - Do not send `Purchase` in the browser and `OrderCompleted` from CAPI. 3. Use the exact same event ID. - Match case, punctuation, and prefix. - `purchase_123` and `Purchase_123` are different values. 4. Generate a unique ID for each event occurrence. - Do not reuse one event ID for multiple orders. 5. Do not use a generic ID such as `purchase` or `checkout`. 6. Send both versions close to the actual conversion time. ### Event ID strategy A practical approach: | Event | Recommended event ID pattern | |---|---| | `ViewContent` | `vc_<UUID>` | | `AddToCart` | `atc_<UUID>` | | `InitiateCheckout` | `ic_<checkout-token-or-UUID>` | | `Purchase` | `purchase_<Shopify-order-ID>` | For Purchase, a Shopify order ID is a strong deduplication key because it is unique and stable: ```text purchase_5793148821 ``` ### Important limitation A CAPI Purchase event sent from a Shopify order webhook can only deduplicate against a browser Purchase event if the browser event uses the same purchase event ID. That means the implementation needs a shared, deterministic key, typically based on the Shopify order ID or checkout ID. This is one reason the native Shopify Meta integration is usually preferable for a small store: it handles Shopify checkout and Meta event coordination without requiring custom checkout instrumentation. --- ## 4. Preparing customer information for server-side events CAPI can include customer and browser identifiers in `user_data` to help Meta associate an event with an ad interaction where permitted. Only send fields that: 1. Cedar & Coil collected lawfully; 2. Are covered by the applicable consent state and privacy notice; 3. Are appropriate for the event and platform policy; and 4. Have been normalized and hashed where Meta requires hashing. ### Send these identifiers when available and consented Potential CAPI `user_data` fields include: | Field | Typical source | Preparation | |---|---|---| | `em` | Checkout email | Lowercase, trim whitespace, SHA-256 hash | | `ph` | Checkout phone | Normalize to E.164-style digits including country code, SHA-256 hash | | `fn` | First name | Lowercase, trim, SHA-256 hash | | `ln` | Last name | Lowercase, trim, SHA-256 hash | | `ct` | City | Lowercase, trim, SHA-256 hash | | `st` | State/region | Normalize, lowercase, SHA-256 hash | | `zp` | Postal code | Normalize, SHA-256 hash | | `country` | Country code | Use normalized two-letter code, lowercase, SHA-256 hash | | `external_id` | Shopify customer ID or approved first-party ID | Normalize, SHA-256 hash | | `fbp` | `_fbp` browser cookie | Send as received; do **not** hash | | `fbc` | Meta click identifier / `_fbc` cookie | Send as received; do **not** hash | | `client_ip_address` | Request or server-side capture | Send raw; do **not** hash | | `client_user_agent` | Browser request header | Send raw; do **not** hash | ### Normalization examples Before hashing: ```text Email: " Shopper@Example.com " → "shopper@example.com" First name: " Maya " → "maya" Phone: "(415) 555-0199" → country-aware normalized digits, e.g. "14155550199" Country: "US" → "us" ``` Then hash the normalized value with SHA-256: ```text SHA-256("shopper@example.com") ``` ### Do not hash these fields Do not hash: - `fbp` - `fbc` - `client_ip_address` - `client_user_agent` These fields have their own expected formats. ### Capturing browser identifiers for CAPI The server will not automatically know the shopper’s `_fbp` and `_fbc` values. If using a custom CAPI implementation: 1. Read `_fbp` and `_fbc` in the browser after consent. 2. Pass them to Cedar & Coil’s tracking endpoint or save them in an approved first-party session/cart/checkout attribute. 3. Retrieve them when creating the CAPI event. 4. Send them un-hashed in `user_data`. Do not invent an `fbc` value. Only send it if Cedar & Coil actually captured a Meta click identifier, such as a `fbclid` that resulted in a valid `_fbc` value. ### Data minimization Do not send fields simply because they are technically available. For example: - Do not send payment details. - Do not send free-text order notes. - Do not send sensitive customer data. - Do not send unapproved custom data fields. - Do not place email addresses, phone numbers, or other personal data in URLs, `custom_data`, content IDs, or event names. --- ## 5. Shopify setup path: native Meta app vs. custom implementation ## Option A: Shopify’s native Meta sales channel app Use Shopify’s **Facebook & Instagram by Meta** sales channel app. Typical setup path: 1. In Shopify admin, go to: ```text Sales channels → Facebook & Instagram ``` or install the Facebook & Instagram by Meta app if it is not present. 2. Connect: - Cedar & Coil’s Meta Business Portfolio - Facebook Page, if applicable - Meta ad account - Meta Pixel/data source - Commerce catalog, if using one 3. In the app’s data-sharing or customer-data-sharing settings: - Select the highest setting Cedar & Coil is comfortable and legally permitted to use. - Confirm that both browser Pixel and server-side sharing/Conversions API are enabled where Shopify and Meta make this available. 4. Confirm the selected data source in Meta Events Manager. 5. Configure cookie consent so Meta tracking does not run before the appropriate consent signal is available. ### Advantages - Fastest implementation. - Lowest maintenance burden. - Better compatibility with Shopify checkout architecture. - Usually handles standard ecommerce events and server-side sharing without a custom webhook service. - Avoids placing a Meta access token in storefront code. - Reduces the risk of custom event-ID and checkout integration mistakes. ### Limitations - Less control over exact CAPI payload fields, retry behavior, and event mapping. - Shopify and Meta control much of the implementation detail. - Advanced custom data requirements may require an additional server-side system. - Validate actual behavior in Events Manager rather than assuming every event is server-side or deduplicated correctly. --- ## Option B: Custom Pixel + custom CAPI implementation A custom implementation generally includes: 1. A Shopify Custom Pixel or storefront event listener for browser events. 2. A Cedar & Coil server-side tracking endpoint. 3. Shopify webhooks, such as an order-paid or order-created workflow, for final Purchase events. 4. A queue/retry system for Meta API delivery failures. 5. A data store to keep: - event IDs, - Shopify order/checkout IDs, - consent state, - captured `_fbp` and `_fbc`, - event-delivery status. 6. Secure secret management for the Meta CAPI access token. 7. Webhook signature verification and idempotent processing. ### Advantages - Full control over events and data payloads. - Can add custom reporting logic. - Can explicitly retain consent state and event records. - Can integrate with internal systems beyond Shopify. ### Risks and maintenance costs - Requires secure server infrastructure. - Requires Shopify webhook verification. - Requires retries and idempotency controls. - Requires careful handling of Shopify checkout limitations. - Requires a reliable shared event-ID strategy for Pixel/CAPI deduplication. - Can accidentally duplicate Purchase events if both native and custom implementations are active. - Creates additional privacy, security, and operational responsibilities. --- ## Recommendation for Cedar & Coil For a small DTC Shopify store selling the Arc Clip Lamp, use the **native Facebook & Instagram by Meta sales channel app first**. It is the recommended baseline because it is simpler, more compatible with Shopify’s checkout, and less likely to create duplicate or malformed Purchase tracking. Use a custom CAPI implementation only if Cedar & Coil has a specific need the native setup cannot meet, such as: - a warehouse, subscription, CRM, or call-center conversion flow outside Shopify; - custom event governance and audit logs; - advanced internal attribution workflows; - a need to send approved offline conversions; - a technical team able to operate secure webhook and API infrastructure. ### Do not run overlapping Purchase implementations without a plan Avoid simultaneously using: - Shopify’s native Meta sales channel Purchase tracking, and - a separately built custom Purchase CAPI integration, unless the technical team has verified exactly how the events are deduplicated. Otherwise, Meta may receive duplicate purchases with different event IDs. --- ### Custom CAPI Purchase request: Node.js sketch This example is illustrative for a custom server. It assumes: - The order has passed Shopify webhook verification. - The event is consented and eligible to send. - `purchase_<order.id>` is also used by the browser Purchase event. - The Meta access token is stored only in secure server-side environment variables. - Customer fields have been normalized before hashing. ```javascript import crypto from "node:crypto"; const sha256 = (value) => crypto .createHash("sha256") .update(String(value).trim().toLowerCase()) .digest("hex"); // Example Shopify order values; populate from a verified Shopify webhook. const order = { id: "5793148821", order_number: "1001", total_price: "68.00", currency: "USD", email: "shopper@example.com", phone: "+14155550199", customer_id: "8123456789", processed_at: "2025-03-08T16:12:35Z", landing_site: "https://cedarandcoil.example/products/arc-clip-lamp", line_items: [ { variant_id: "1234567890", quantity: 1, price: "68.00" } ], // Capture only if available, valid, and consented. fbp: "fb.1.1234567890123.1234567890", fbc: "fb.1.1234567890123.ABCDEF123456", client_ip_address: "203.0.113.25", client_user_agent: "Mozilla/5.0 ..." }; const pixelId = process.env.META_PIXEL_ID; const accessToken = process.env.META_CAPI_ACCESS_TOKEN; const eventId = `purchase_${order.id}`; const payload = { data: [ { event_name: "Purchase", event_time: Math.floor(new Date(order.processed_at).getTime() / 1000), event_id: eventId, action_source: "website", event_source_url: order.landing_site, user_data: { em: order.email ? [sha256(order.email)] : undefined, ph: order.phone ? [sha256(order.phone)] : undefined, external_id: order.customer_id ? [sha256(order.customer_id)] : undefined, // Do not hash these: fbp: order.fbp || undefined, fbc: order.fbc || undefined, client_ip_address: order.client_ip_address || undefined, client_user_agent: order.client_user_agent || undefined }, custom_data: { currency: order.currency, value: Number(order.total_price), content_type: "product", content_ids: order.line_items.map( (item) => `shopify_variant_${item.variant_id}` ), contents: order.line_items.map((item) => ({ id: `shopify_variant_${item.variant_id}`, quantity: item.quantity, item_price: Number(item.price) })), order_id: order.order_number } } ] }; // Remove undefined values before sending. function removeUndefined(value) { if (Array.isArray(value)) { return value.map(removeUndefined); } if (value && typeof value === "object") { return Object.fromEntries( Object.entries(value) .filter(([, v]) => v !== undefined) .map(([key, v]) => [key, removeUndefined(v)]) ); } return value; } const cleanPayload = removeUndefined(payload); const response = await fetch( `https://graph.facebook.com/v22.0/${pixelId}/events?access_token=${accessToken}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(cleanPayload) } ); const result = await response.json(); if (!response.ok) { throw new Error(`Meta CAPI error: ${JSON.stringify(result)}`); } console.log(result); ``` Implementation notes: - Use the currently supported Meta Graph API version in production; do not leave a version hard-coded indefinitely without a maintenance process. - Store the CAPI access token in a secret manager or server-side environment variable. - Never expose the access token in Shopify theme code, browser JavaScript, or a public repository. - Add retry handling for temporary Meta API failures. - Store each order/event ID after successful delivery so webhook retries do not produce separate events. - Verify Shopify webhook signatures before accepting any order payload. - Use actual order completion time for `event_time`, not the time a delayed webhook happens to be processed. - Do not send the event when consent does not permit it. --- ## 6. Validate the setup end to end before scaling spend Do not scale media spend until the tracking path has been tested with real Shopify test orders or controlled low-risk transactions. ## Step 1: Confirm the correct Meta data source In Meta Events Manager: 1. Open the Cedar & Coil Pixel/data source. 2. Confirm that the Pixel ID connected in Shopify matches the intended ad account and business. 3. Confirm the domain is correct. 4. Complete domain verification if required for the advertising setup. 5. Review event configuration and prioritization requirements relevant to Cedar & Coil’s market and account setup. ## Step 2: Test browser Pixel events Using an approved test browser and a consented session: 1. Visit the Arc Clip Lamp product page. 2. Confirm `ViewContent` appears. 3. Add the lamp to cart. 4. Confirm `AddToCart` appears. 5. Start checkout. 6. Confirm `InitiateCheckout` appears. 7. Complete a test order. 8. Confirm `Purchase` appears. Use: - Meta Events Manager’s Test Events view; - Meta Pixel Helper browser extension, where applicable; - Browser developer tools Network tab, if needed; - Shopify customer events/pixel diagnostics, if available. Check that each event includes: - Correct event name; - `value`; - `currency: USD`; - Expected `content_ids`; - No personal information exposed in the browser URL or event parameters. ## Step 3: Test server-side CAPI events For native Shopify setup: - Check Events Manager for events marked as server-side, server, or Conversions API events where Meta exposes this classification. - Review diagnostic warnings in both Shopify and Meta. For custom CAPI setup: 1. Send a test event using Meta’s Test Events workflow and test event code, if applicable. 2. Confirm Meta receives the CAPI event. 3. Confirm the event has no schema warnings. 4. Confirm `event_time`, `action_source`, `value`, currency, and product data are correct. 5. Check that permitted `user_data` fields are correctly formatted and hashed. A CAPI test event may include a Meta-provided `test_event_code` during testing. Do not leave a test code in production requests. ## Step 4: Verify Purchase deduplication This is the most important validation step. For one completed test order: 1. Capture the browser Pixel Purchase event ID. 2. Capture the CAPI Purchase event ID. 3. Confirm both are exactly the same, for example: ```text purchase_5793148821 ``` 4. Confirm the event name is `Purchase` in both places. 5. Review Meta Events Manager diagnostics for deduplication status. 6. Confirm that one order is not reported as two Purchase events. Repeat with more than one test order if possible. ## Step 5: Verify product and value consistency For a completed Arc Clip Lamp order, confirm: ```text content_ids: Shopify/Meta catalog-consistent variant ID content_type: product quantity: correct item_price: actual line-item price value: documented final order-value convention currency: USD ``` For the current product setup, an undiscounted single-item order would ordinarily show: ```text Quantity: 1 Item price: 68.00 Value: 68.00, if no shipping/tax/discount difference under the chosen convention Currency: USD ``` Use Shopify order data as the source of truth. ## Step 6: Test consent states Test at least these scenarios: | Scenario | Expected behavior | |---|---| | Visitor has not made a consent choice | Non-essential Meta advertising tracking should not fire unless legally permitted under the applicable rules. | | Visitor declines marketing/advertising cookies | Pixel and CAPI behavior should follow the configured consent policy; do not send data beyond what is permitted. | | Visitor grants consent | Approved browser Pixel and server-side events may run. | | Shopper completes checkout in a consented session | Purchase should be delivered once after deduplication. | | Shopper blocks browser scripts | Server-side event behavior should follow Cedar & Coil’s consent policy and implementation design. | ## Step 7: Monitor after launch For the first days of spend, monitor: - Meta Events Manager diagnostics; - Missing `Purchase` value or currency warnings; - Product ID mismatches; - Event deduplication warnings; - Sudden changes in browser versus server event volume; - Shopify order count versus Meta Purchase event trends; - Consent-platform changes or Shopify theme/app changes that affect tracking. Do not expect Shopify order totals and Meta attributed conversions to match exactly. They represent different systems and attribution rules. --- ## 7. Consent and compliance note Cedar & Coil should implement Meta tracking within its privacy, cookie, and advertising-law obligations. ### Minimum requirements 1. **Use a consent management platform or Shopify-compatible consent mechanism** - Obtain and record consent where required before activating advertising cookies or sending related server-side data. - Configure Shopify, the Meta sales channel, and any custom CAPI service to honor the same consent state. 2. **Update the privacy policy and cookie disclosures** - Explain the use of Meta advertising and measurement technologies. - Explain relevant categories of data shared, such as purchase activity, device/browser identifiers, and hashed customer contact information where applicable. - Explain how customers can manage choices. 3. **Do not use CAPI to bypass a customer’s choice** - If a person has opted out or declined the relevant category of tracking, do not use server-side tracking to silently continue transmitting data that would otherwise be blocked. 4. **Use data minimization** - Send only fields needed for approved measurement purposes. - Avoid free-text fields, sensitive data, and irrelevant customer records. - Do not include personal data in URLs, content IDs, custom parameters, or event names. 5. **Secure implementation credentials** - Keep Meta access tokens server-side. - Restrict access to Shopify webhook secrets, Meta assets, and event logs. - Set retention limits for tracking logs and customer identifiers. 6. **Review regional requirements** - Requirements vary by jurisdiction, including rules related to cookies, targeted advertising, data sharing, opt-out rights, and cross-border transfers. - Cedar & Coil should obtain legal/privacy review appropriate to the markets in which it sells and advertises. --- ## Final recommended implementation checklist ```text [ ] Install and connect Shopify’s Facebook & Instagram by Meta sales channel. [ ] Connect the intended Meta Pixel/data source and ad account. [ ] Enable the highest permitted customer-data-sharing setting. [ ] Configure consent management before Meta tracking runs. [ ] Confirm ViewContent, AddToCart, InitiateCheckout, and Purchase events. [ ] Confirm value, currency, and consistent Shopify variant content IDs. [ ] Confirm Purchase includes content_ids and order-level value. [ ] Validate browser and server event delivery in Meta Events Manager. [ ] Validate Pixel/CAPI Purchase deduplication with matching event_name + event_id. [ ] Ensure no second custom Purchase implementation is duplicating native tracking. [ ] Document the event-value convention and product-ID convention. [ ] Monitor diagnostics and Shopify-to-Meta tracking health before increasing spend. ```
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 + deduplication and explains via a table why each is needed given browser privacy limits.
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓Section 2 covers ViewContent, AddToCart, InitiateCheckout, and Purchase with value, currency, and content_ids listed for each, including order_id on Purchase.
code_sketch
A concrete server-side Purchase event code sketch or request example is included showing event_name, event_time, event_id, action_source, and a user_data block.
✓The Node.js sketch includes event_name: 'Purchase', event_time, event_id, action_source: 'website', and a user_data block with em/ph/external_id/fbp/fbc.
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.
✓Step 3 uses Meta's Test Events workflow and Step 4 explicitly verifies that Pixel and CAPI Purchase event IDs match and reviews Events Manager deduplication diagnostics.
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 must use Shopify order data/webhook as source of truth ('Use Shopify order data as the source of truth' and 'not the time a delayed webhook happens to be processed'), while other events are tied to browser actions (page view, add-to-cart click, checkout start).
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 intro states 'Do not treat it as a promise of a particular attribution or match-rate outcome' and Section 7 lays out consent/regional constraints on what data 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 requires identical event_name and event_id sent from both Pixel (eventID) and CAPI (event_id) so Meta treats them as one conversion.
event_id_retry_stability
The event_id is generated or derived once per commerce event, shared by browser and server, and reused unchanged on webhook retries or order updates; a new random suffix per send or retry fails.
✓The event_id is derived as purchase_<order.id> and the notes say to 'Store each order/event ID after successful delivery so webhook retries do not produce separate events.'
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 and the notes instruct to 'Use actual order completion time for event_time, not the time a delayed webhook happens to be processed.'
pii_hashing
Customer data handling is correct: personally identifiable fields (e.g. email) are normalized (trimmed, lowercased) and SHA-256 hashed before sending in user_data.
✓The sha256 helper trims and lowercases the value before hashing, and the table specifies 'Lowercase, trim whitespace, SHA-256 hash' for em/fn/ln fields.
actionable_path
The recommended Shopify path is decisive and executable for a small DTC store (a clear recommendation with concrete setup steps, not an undifferentiated list of options).
✓The guide gives a decisive recommendation ('use the native Facebook & Instagram by Meta sales channel app first') with concrete numbered setup steps in Shopify admin.

GPT-5.6 Sol medium 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.14 · 74.0s · 4.7k tok
# Cedar & Coil: Shopify-to-Meta Conversion Tracking Guide ## 1. Recommended architecture: Meta Pixel + Conversions API Use both of Meta’s website event paths: 1. **Browser-side Meta Pixel** - Runs in the shopper’s browser. - Captures page and commerce interactions quickly. - Can collect browser identifiers such as `_fbp` and `_fbc`. - Is affected by ad blockers, cookie restrictions, browser privacy controls, page-navigation failures, and consent choices. 2. **Server-side Meta Conversions API (CAPI)** - Sends events from Shopify or Cedar & Coil’s server directly to Meta. - Is less dependent on browser execution and third-party scripts. - Is appropriate for authoritative events such as a paid Shopify order. - Is still subject to consent, data-quality, and platform-policy requirements; it does not bypass them. ### Why both are needed The browser event provides useful browser and click context, while the server event provides a more reliable path for completed transactions. Sending both also gives Meta more opportunities to match permitted events to users. For events sent through both paths, implement **deduplication** so Meta counts one conversion rather than two. Do not run the Shopify Meta integration and an additional custom Pixel/CAPI implementation for the same events unless duplicate behavior has been deliberately removed. --- ## 2. Standard events and parameters Use Meta’s standard event names exactly as shown. Keep product identifiers identical across the Shopify catalog, Pixel events, and CAPI events. For the Arc Clip Lamp, choose one stable identifier scheme: - Shopify variant ID, such as `gid://shopify/ProductVariant/...`; or - Shopify numeric variant ID; or - SKU, if every sellable variant has a unique and permanent SKU. For catalog-based advertising, `content_ids` must match the IDs Meta receives in the connected product catalog. ### `ViewContent` Fire when the Arc Clip Lamp product detail page is meaningfully viewed. Recommended parameters: ```json { "content_ids": ["<catalog-matching-variant-or-product-id>"], "content_type": "product", "content_name": "Arc Clip Lamp", "value": 68.00, "currency": "USD" } ``` Notes: - If a variant has not yet been selected, use the product or default variant ID according to the catalog’s ID scheme. - `value` should reflect the displayed product price. - Do not fire repeatedly for minor UI changes on the same page. ### `AddToCart` Fire after Shopify confirms that the item was added to the cart, not merely when the button was clicked. ```json { "content_ids": ["<catalog-matching-variant-id>"], "content_type": "product", "contents": [ { "id": "<catalog-matching-variant-id>", "quantity": 1, "item_price": 68.00 } ], "value": 68.00, "currency": "USD" } ``` For multiple units, `value` should be unit price multiplied by quantity. If the cart operation fails, do not send the event. ### `InitiateCheckout` Fire when the shopper successfully enters Shopify checkout. ```json { "content_ids": ["<variant-id-1>", "<variant-id-2>"], "content_type": "product", "contents": [ { "id": "<variant-id-1>", "quantity": 1, "item_price": 68.00 } ], "num_items": 1, "value": 68.00, "currency": "USD" } ``` Use the checkout’s current merchandise/order value according to one documented accounting rule. Avoid firing solely from a checkout-button click if checkout was not actually created. ### `Purchase` Fire only after Shopify confirms the qualifying order state—normally payment completed or an equivalent paid state. Avoid treating an unconfirmed checkout or failed payment as a purchase. ```json { "content_ids": ["<variant-id-1>"], "content_type": "product", "contents": [ { "id": "<variant-id-1>", "quantity": 1, "item_price": 68.00 } ], "num_items": 1, "value": 68.00, "currency": "USD", "order_id": "<shopify-order-id>" } ``` Purchase requirements and conventions: - `value` must be numeric, not `"$68.00"`. - `currency` must be an ISO currency code such as `USD`. - `content_ids` must be included and match the catalog identifier format. - Include every purchased line item in `contents`. - Decide whether purchase value includes discounts, shipping, and tax, then apply that rule consistently. Shopify’s final paid order total is usually the simplest authoritative value. - Refunds and cancellations need a separate documented handling process; do not silently rewrite historical purchase events. --- ## 3. Exactly how Pixel/CAPI deduplication works Deduplication depends primarily on these two fields matching: 1. **The same event name**, such as `Purchase` 2. **The same event ID**, generated for that single business event The browser Pixel sends the ID as `eventID`: ```html <script> fbq( 'track', 'Purchase', { value: 68.00, currency: 'USD', content_ids: ['<variant-id>'], content_type: 'product' }, { eventID: 'shopify_purchase_1234567890' } ); </script> ``` The server event sends the identical value as `event_id`: ```json { "event_name": "Purchase", "event_id": "shopify_purchase_1234567890" } ``` Meta receives two copies but recognizes them as the same logical conversion: | Field | Browser Pixel | Server CAPI | |---|---|---| | Event name | `Purchase` | `Purchase` | | Deduplication ID | `eventID` | `event_id` | | Required value | Same in both | Same in both | ### Event-ID rules - Generate the ID once and make it available to both paths. - Use a stable, unique ID for each logical event. - For `Purchase`, a deterministic value based on the Shopify order ID is suitable, for example: - `shopify_purchase_1234567890` - Do not generate separate random UUIDs in the browser and server. - Do not reuse one ID for two different orders or event types. - A retry of the same server event should keep the same `event_id`. - `event_id` does not replace `order_id`; send both where useful. - Keep event names identical. `Purchase` and `purchase` should not be treated as interchangeable. For non-purchase events, the same principle applies. For example, create an add-to-cart event ID in the browser, persist it with the cart operation, and use it if the corresponding event is also sent server-side. If only one path sends an event, deduplication is unnecessary. The native Shopify Meta integration should manage its own event IDs and deduplication. Do not add a second hand-built Purchase event on top of it without first confirming that the native event is disabled. --- ## 4. Preparing customer information for server-side events CAPI customer information belongs under `user_data`. Only send data that Cedar & Coil is permitted to process and disclose. ### Normalize and hash contact identifiers Meta requires supported customer identifiers such as email and phone to be normalized and SHA-256 hashed before transmission unless an approved integration performs that preparation automatically. #### Email 1. Trim leading and trailing whitespace. 2. Convert to lowercase. 3. SHA-256 hash the normalized value. Example: ```text " Customer@Example.com " → "customer@example.com" → SHA-256 hash ``` #### Phone 1. Remove punctuation, spaces, and formatting. 2. Include country code. 3. Normalize to digits in the expected international form. 4. SHA-256 hash the normalized value. #### Names, city, state, ZIP, country, and external ID Apply Meta’s normalization rules for each field and SHA-256 hash them where required. For example, names are generally lowercased and stripped of unnecessary punctuation before hashing. Do not guess missing values. ### Do not hash browser/network fields The following are sent in their expected raw form, not SHA-256 hashed: - `client_ip_address` - `client_user_agent` - `fbp` - `fbc` `fbp` is generally derived from the browser’s `_fbp` cookie. `fbc` represents Meta click information and should only be created when a valid Meta click identifier is available. Do not fabricate either value. Capture permitted browser identifiers during the session and associate them with the Shopify cart or checkout so they can be attached to the later server event. If they are unavailable, omit them rather than inventing values. ### Additional rules - Never put plaintext email or phone data in URLs, query strings, event IDs, or application logs. - Store access tokens only in server-side secret storage. - Minimize retention of raw customer data. - Restrict log access and redact webhook payloads. - Use the IP address and user agent associated with the customer request when legitimately available—not the server’s own IP or user agent. - Set `action_source` to `website` and provide the relevant `event_source_url`. --- ## 5. Shopify setup path ## Option A: Native “Facebook & Instagram by Meta” sales channel This is the recommended starting point for Cedar & Coil as a small DTC Shopify store. Typical setup path: 1. In Shopify Admin, install or open **Facebook & Instagram by Meta**. 2. Connect the correct: - Meta business portfolio/business account - Facebook Page - Ad account - Meta Pixel or dataset - Commerce account/catalog, if requested 3. Connect Shopify’s product catalog and confirm the Arc Clip Lamp is present. 4. Select the highest data-sharing setting appropriate for Cedar & Coil’s consent configuration and operating regions—commonly labeled **Maximum**. - This generally enables browser and server-side sharing. - Exact labels can change, so verify the setting’s current description. 5. Confirm the connected Pixel/dataset ID is the one selected in Ads Manager. 6. Complete domain verification and any required web-event configuration in Meta. 7. Review Shopify’s customer privacy settings and consent regions. 8. Remove any legacy theme-installed Pixel, old tag-manager Pixel, or duplicate Meta app. ### Why recommend the native integration - Lower implementation and maintenance burden - Shopify-managed checkout compatibility - Built-in catalog synchronization - Browser and server event support - Managed event-ID deduplication - Less exposure of access tokens and customer data - Better resilience to Shopify checkout and API changes Its tradeoff is reduced control over event timing, identifiers, payload composition, retries, and observability. ## Option B: Custom Pixel and CAPI implementation Use a custom implementation only when Cedar & Coil has requirements the native channel cannot meet, such as: - Specialized event definitions - A controlled first-party event pipeline - Custom consent routing - Detailed retry and audit requirements - Multiple destinations or advanced data governance A custom implementation generally needs: 1. A Shopify Web Pixel/custom pixel for browser events 2. A backend endpoint or event service 3. Shopify webhooks such as the appropriate paid-order webhook 4. Webhook HMAC verification 5. Idempotency and retry handling 6. Stable event-ID generation 7. Secure Meta access-token management 8. Consent-state propagation 9. A method to carry permitted `_fbp`, `_fbc`, IP, and user-agent data from browser/cart/checkout to the order event Avoid directly editing obsolete checkout templates. Use Shopify’s supported Web Pixels and checkout extensibility mechanisms. ### Server-side Purchase request sketch The following Node.js-style sketch demonstrates the shape of a CAPI Purchase request. Production code must also verify Shopify’s webhook HMAC, enforce idempotency, handle retries, and use the correct Shopify money fields. ```js import crypto from "node:crypto"; const sha256 = value => crypto.createHash("sha256").update(value).digest("hex"); const normalizeEmail = value => value.trim().toLowerCase(); const normalizePhone = value => value.replace(/\D/g, ""); // Ensure country code is present upstream. async function sendMetaPurchase({ order, pixelId, accessToken, sourceUrl, clientIp, clientUserAgent, fbp, fbc }) { // Stable across browser event, server event, and server retries. const eventId = `shopify_purchase_${order.id}`; const userData = {}; if (order.email) { userData.em = [sha256(normalizeEmail(order.email))]; } if (order.phone) { userData.ph = [sha256(normalizePhone(order.phone))]; } if (order.customer?.id) { userData.external_id = [ sha256(String(order.customer.id).trim().toLowerCase()) ]; } // These fields are not hashed. if (clientIp) userData.client_ip_address = clientIp; if (clientUserAgent) userData.client_user_agent = clientUserAgent; if (fbp) userData.fbp = fbp; if (fbc) userData.fbc = fbc; const contents = order.line_items.map(item => ({ // This must match the identifier format in Meta's product catalog. id: String(item.variant_id), quantity: item.quantity, item_price: Number(item.price) })); const payload = { data: [ { event_name: "Purchase", event_time: Math.floor( new Date(order.processed_at || order.created_at).getTime() / 1000 ), event_id: eventId, action_source: "website", event_source_url: sourceUrl, user_data: userData, custom_data: { currency: order.currency, value: Number(order.total_price), content_type: "product", content_ids: contents.map(item => item.id), contents, num_items: contents.reduce( (sum, item) => sum + item.quantity, 0 ), order_id: String(order.id) } } ] }; const response = await fetch( `https://graph.facebook.com/<CURRENT_GRAPH_VERSION>/${pixelId}/events` + `?access_token=${encodeURIComponent(accessToken)}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) } ); const result = await response.json(); if (!response.ok) { throw new Error(`Meta CAPI request failed: ${JSON.stringify(result)}`); } return result; } ``` Production considerations: - Keep the Graph API version in configuration and update it deliberately. - Prefer an authorization header if supported by the selected API pattern; never expose the token client-side. - Trigger only from the chosen authoritative order state. - Record an idempotency key such as `Purchase:<order.id>`. - Retry transient failures with backoff using the same `event_id`. - Do not resend an event with a new ID merely because the first request timed out. - If sending a matching browser Purchase, it must use the same `shopify_purchase_<order.id>` ID. - If the checkout environment cannot safely provide the same order-based ID, do not deploy two uncontrolled Purchase paths; use the native integration or redesign the handoff. --- ## 6. End-to-end validation before scaling spend ### A. Audit the store first Check for all existing Meta installations: - Facebook & Instagram by Meta - Theme code containing `fbq(` - Google Tag Manager tags - Shopify custom pixels - Legacy checkout scripts - Third-party tracking apps - A separate server-side gateway There should be one intentional owner for each event path. ### B. Validate browser events Use Meta Events Manager’s **Test Events** tool and, where applicable, Meta Pixel Helper. Run this sequence: 1. Open the Arc Clip Lamp product page. 2. Confirm one `ViewContent`. 3. Add one lamp to cart. 4. Confirm one `AddToCart` with: - Correct ID - Quantity `1` - Value `68.00`, absent discounts - Currency `USD` 5. Start checkout. 6. Confirm one `InitiateCheckout`. 7. Complete a Shopify test order. 8. Confirm a browser `Purchase` if the chosen integration sends one. Check that navigation, cart refreshes, and page reloads do not create unexplained duplicates. ### C. Validate the server event In Test Events or CAPI diagnostics, verify: - `event_name` is `Purchase` - `action_source` is `website` - `event_time` is valid and close to the order time - `event_id` is present - `value` and `currency` match Shopify - `content_ids` match the catalog - `contents` includes the correct quantities and prices - Permitted customer fields are normalized and hashed correctly - `_fbp`/`_fbc` are passed raw when available - No plaintext personal information appears in logs For a custom implementation, Meta supports a test-event code for validation. Use it only in testing and remove it from production payloads. ### D. Validate deduplication For the test purchase: 1. Inspect both browser and server event details. 2. Confirm both use `Purchase`. 3. Confirm the browser `eventID` exactly equals the server `event_id`. 4. Confirm Events Manager reports browser and server receipt without counting two purchases. 5. Retry the server delivery with the same ID and confirm it remains one logical event. 6. Reload the order-status page and confirm it does not create a new Purchase ID. Allow for processing delay before concluding that deduplication failed. ### E. Reconcile against Shopify For several controlled test orders, compare: - Number of paid Shopify orders - Number of Meta Purchase events received - Order currency and value - Product/variant IDs - Event timestamps - Duplicate or missing order IDs Meta Ads Manager attribution will not necessarily equal Shopify order totals because attribution rules and identity matching differ. Operational validation should use event receipts and order-level reconciliation, not only campaign-report totals. ### F. Monitor after launch Regularly review: - Events Manager diagnostics - Deduplication warnings - Event match-quality diagnostics - Catalog item-match errors - CAPI request failures and latency - Webhook retries - Consent-related changes - Shopify theme or checkout updates - Graph API deprecations Do not scale spend until the complete test journey produces correct values, IDs, and one logical Purchase per paid test order. --- ## 7. Consent and compliance Pixel and CAPI use must follow applicable privacy laws, Shopify requirements, and Meta’s Business Tools Terms. Server-side delivery is not a way to override a shopper’s consent choice or browser privacy preference. Cedar & Coil should: - Use a consent-management mechanism appropriate to the regions served. - Prevent nonessential marketing events from firing before required consent. - Propagate the shopper’s consent state to the server-side pipeline. - Suppress CAPI marketing events when consent or another valid legal basis is absent. - Clearly disclose Meta Pixel, CAPI, cookies, identifiers, and advertising uses in the privacy notice. - Provide required opt-out or withdrawal mechanisms. - Collect and send only necessary fields. - Define retention and deletion procedures. - Protect Meta tokens and Shopify webhook secrets. - Honor applicable data-subject and restricted-data-processing requirements. - Have legal or privacy counsel review the final configuration for Cedar & Coil’s actual markets. Start with the native Meta sales channel, the appropriate consent-aware data-sharing setting, and no duplicate legacy tags. Move to a custom implementation only when there is a documented technical or governance need.
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 and explains 'Why both are needed' under browser privacy limits.
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓Section 2 covers ViewContent, AddToCart, InitiateCheckout, and Purchase, each with value, currency, and content_ids parameters.
code_sketch
A concrete server-side Purchase event code sketch or request example is included showing event_name, event_time, event_id, action_source, and a user_data block.
✓The Node.js sendMetaPurchase function includes event_name, event_time, event_id, action_source, and a user_data block.
validation
End-to-end validation is described using Meta's Events Manager test events tool and an explicit check that duplicate browser/server events are being deduplicated.
✓Section 6B/6D explicitly instructs using Meta Events Manager Test Events and checking that browser eventID equals server event_id with no double counting.
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 'Fire only after Shopify confirms the qualifying order state' and describes triggering via the paid-order webhook rather than solely a 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 lists consent/regional constraints on what data 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 details that matching event_name and event_id across Pixel (eventID) and CAPI (event_id) lets 'Meta receives two copies but recognizes them as the same logical conversion.'
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 'A retry of the same server event should keep the same event_id' and derives eventId deterministically from order.id.
event_time_stable
The server Purchase event uses the purchase/order occurrence timestamp in Unix seconds and preserves it across retries; using the current send or retry time fails.
✓event_time is computed from order.processed_at/created_at in Unix seconds, which remains constant across retries since it's tied to the order, not 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.
✓Email normalization (trim, lowercase) followed by SHA-256 hashing is shown both in prose and code (normalizeEmail then sha256).
actionable_path
The recommended Shopify path is decisive and executable for a small DTC store (a clear recommendation with concrete setup steps, not an undifferentiated list of options).
✓Section 5 explicitly recommends 'Option A: Native Facebook & Instagram by Meta sales channel' as the starting point for a small DTC store with an 8-step setup path.

Claude Sonnet 5 default

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.046 · 50.0s · 4.5k tok
# Meta Conversion Tracking Implementation Guide ## Cedar & Coil — Arc Clip Lamp (Shopify) This guide sets up conversion tracking that remains functional as browsers restrict third-party cookies and users decline tracking consent. It assumes a standard Shopify store (not Shopify Plus checkout customization) and a single primary product, the Arc Clip Lamp ($68). --- ### 1. Recommended Architecture: Pixel + Conversions API (CAPI), Deduplicated **Architecture:** - **Browser-side Meta Pixel** fires on page load/interaction events (ViewContent, AddToCart, InitiateCheckout) and on the order status page (Purchase). - **Server-side Conversions API** sends the same events from Shopify's backend (via webhook or the Meta sales channel app) directly to Meta's servers. - Both paths send a shared `event_id` so Meta can **deduplicate** and count each real event once. **Why both are needed:** - The Pixel alone is unreliable under Safari ITP, Firefox ETP, ad blockers, and iOS in-app browser restrictions — it simply doesn't fire for a meaningful share of sessions. - CAPI alone loses browser-side signals (click IDs like `fbclid`, `fbp`/`fbc` cookies, device/browser context) that materially help Meta's matching and optimization. - Together, they give Meta two independent signal paths for the same event. If the pixel fails silently, the server event still lands. If the server event is delayed, the pixel event already registered. This is Meta's own recommended pattern ("Pixel + CAPI, deduplicated") — not a workaround, the standard architecture. --- ### 2. Standard Events and Required Parameters Send these four events consistently from both Pixel and CAPI. **ViewContent** (product page view) - `content_ids`: [Shopify variant ID or product ID] - `content_type`: `product` - `value`: 68.00 (or variant price if multiple variants exist) - `currency`: `USD` - `content_name`: "Arc Clip Lamp" **AddToCart** - `content_ids`: [variant ID] - `content_type`: `product` - `value`: unit price × quantity - `currency`: `USD` - `contents`: [{id, quantity, item_price}] (recommended for multi-line accuracy) **InitiateCheckout** - `content_ids`: [variant IDs in cart] - `content_type`: `product` - `value`: cart subtotal - `currency`: `USD` - `num_items`: item count **Purchase** (fires once, on order confirmation — highest-value event, gets the most scrutiny) - `content_ids`: [variant/product IDs — **required**, drives catalog/dynamic ad matching] - `content_type`: `product` - `value`: order total **excluding or including shipping/tax consistently** — pick one convention (recommend order subtotal or total-paid, matched exactly between Pixel and CAPI) and never mix - `currency`: `USD` - `contents`: [{id, quantity, item_price}] - `order_id` / `transaction_id`: Shopify order ID (also used for dedup safety and to prevent double-counting on page refresh) Keep `value` and `currency` present on **every** event, not just Purchase — Meta's optimization and reporting degrade without them even on funnel events. --- ### 3. How Pixel/CAPI Deduplication Works Deduplication is based on **two fields matching exactly** across the browser event and the server event for the same real-world action: 1. **`event_name`** — must be identical (e.g., both must say `Purchase`, not one `Purchase` and one `purchase`). 2. **`event_id`** — a unique string you generate per event occurrence, sent in *both* the Pixel call and the CAPI call for that same action. **Implementation mechanics:** - Generate the `event_id` once per event (e.g., `order_id + "_purchase"`, or a UUID stored server-side and passed to the client). - Pass it to the Pixel via the `eventID` parameter in `fbq('track', 'Purchase', {...}, {eventID: 'abc123'})`. - Pass the identical string as `event_id` in the CAPI payload for that event. - Meta matches events with the same `event_name` + `event_id` inside a rolling dedup window and **counts only one** in reporting and optimization, regardless of which arrived first or whether both arrived. - `event_time` does **not** need to match exactly, but both events should carry an accurate Unix timestamp of when the action actually happened. - If `event_id` is missing or mismatched between the two paths, Meta will count both — inflating conversions. Test this explicitly (see Section 6). --- ### 4. Preparing Customer Information for Server-Side Sending CAPI events include a `user_data` object that improves match quality. Because this data leaves your server, it must be prepared correctly: - **Hash all PII with SHA-256** before sending: email, phone number, first name, last name, city, state, zip, country. - Email: lowercase, trim whitespace, then hash. - Phone: strip to digits only including country code (E.164-style, no `+` or symbols per Meta's spec), then hash. - Never send raw/plaintext PII fields. - **Do not hash** the following — send as plain values: - `client_ip_address` - `client_user_agent` - `fbc` (click ID cookie, if present) - `fbp` (browser ID cookie, if present) - **Capture `fbp`/`fbc` server-side accurately:** read them from the request cookies at the time the Shopify webhook/order event fires, not from a stale value. If a customer purchased without those cookies present (e.g., different device), simply omit — do not fabricate. - Send as many matched identifiers as are legitimately available (email + phone + `fbp`/`fbc` + IP/UA) — match quality improves with more corroborating fields, but only send fields you actually have. --- ### 5. Shopify Setup Path **Option A — Native Meta & Instagram sales channel app (Shopify App Store)** - Meta's own app auto-installs the Pixel and configures server-side event forwarding for standard Shopify checkout events (View, AddToCart, InitiateCheckout, Purchase) via Shopify's Pixel and order webhooks, with deduplication handled automatically. - No custom code required; updates are maintained by Meta/Shopify as platform APIs change. **Option B — Custom implementation** - Manually add Pixel base code + event calls via Shopify theme customization or a custom app/Pixel extension, and build a server-side listener (order webhook → your server or a middleware like a Cloudflare Worker/AWS Lambda → Meta CAPI endpoint) with your own `event_id` generation and hashing logic. - Gives full control over `value` conventions, additional custom parameters, and multi-destination routing (e.g., also sending to GA4/other platforms), but requires ongoing maintenance as Shopify checkout or Meta's API evolves. **Recommendation for a small DTC store like Cedar & Coil:** Use the **native Meta sales channel app** as the foundation. It covers Pixel + CAPI + dedup out of the box with minimal engineering overhead, which is appropriate for a single-product store without a dedicated dev team. Only move to a custom implementation if you need non-standard value logic, additional CAPI events Shopify doesn't natively support, or multi-platform server-side routing later. **Code sketch — server-side Purchase event (custom implementation path)**, e.g. from a webhook handler triggered by Shopify's `orders/paid` webhook: ```javascript // Node.js sketch — order webhook handler const crypto = require('crypto'); const fetch = require('node-fetch'); function sha256(value) { return crypto.createHash('sha256').update(value.trim().toLowerCase()).digest('hex'); } async function sendPurchaseEvent(order, cookies, requestMeta) { const eventId = `${order.id}_purchase`; // must match client-side eventID const payload = { data: [{ event_name: "Purchase", event_time: Math.floor(new Date(order.processed_at).getTime() / 1000), event_id: eventId, action_source: "website", event_source_url: order.order_status_url, user_data: { em: [sha256(order.email)], ph: order.phone ? [sha256(order.phone.replace(/\D/g, ''))] : undefined, client_ip_address: requestMeta.ip, client_user_agent: requestMeta.userAgent, fbc: cookies.fbc || undefined, fbp: cookies.fbp || undefined, }, custom_data: { currency: "USD", value: order.total_price, // pick one convention, stay consistent w/ Pixel content_type: "product", content_ids: order.line_items.map(li => li.variant_id.toString()), contents: order.line_items.map(li => ({ id: li.variant_id.toString(), quantity: li.quantity, item_price: parseFloat(li.price) })), order_id: order.id.toString() } }], access_token: process.env.META_CAPI_ACCESS_TOKEN }; await fetch(`https://graph.facebook.com/v19.0/${process.env.PIXEL_ID}/events`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }); } ``` The corresponding client-side Pixel call on the order status page must use the **same `eventId`**: ```javascript fbq('track', 'Purchase', { value: order.total_price, currency: 'USD', content_ids: [/* variant ids */], content_type: 'product' }, { eventID: eventId }); ``` --- ### 6. End-to-End Validation Before Scaling Spend Do not increase budget until all of the following pass: 1. **Meta Events Manager → Test Events tool:** Trigger a real test purchase (Shopify test order or discount-code $0/low-value order) and confirm both a "Browser" and "Server" event appear for each of the four standard events, with matching `event_id`. 2. **Deduplication check:** In Events Manager's event detail view, confirm events show as deduplicated (Meta explicitly flags matched pairs) — not counted twice in the Overview totals. 3. **Parameter audit:** Inspect each event's payload in Test Events for presence and correctness of `value`, `currency`, `content_ids`, and `user_data` fields (hashed correctly, no plaintext PII visible). 4. **Diagnostics tab:** Check Events Manager's Diagnostics for warnings (missing parameters, low match quality, deprecated fields) and resolve before launch. 5. **Match quality score:** Confirm the Pixel/CAPI combined match quality reads in the "Good"–"Great" range in Events Manager, not "Poor" — this reflects breadth of matched identifiers, not projected performance. 6. **Real-order spot check:** Place one real end-to-end order (or use Shopify's order testing mode) through the full funnel — product page → cart → checkout → confirmation — and confirm all four events log correctly in sequence with correct values. 7. **Only then** turn on or scale ad spend. Re-check Diagnostics weekly for the first few weeks, since Shopify theme edits or checkout changes can silently break the client-side pixel. --- ### 7. Consent and Compliance Note - Server-side sending does **not** exempt this setup from consent requirements — CAPI events containing personal data are still subject to the same regional privacy laws (e.g., GDPR, CPRA) as the Pixel. - If serving EU/UK/California traffic, integrate a consent management platform (CMP) with Shopify and gate both Pixel firing and CAPI transmission on actual user consent state — do not send hashed PII server-side for users who have declined tracking consent, even though it's technically feasible to do so. - Use Meta's **Limited Data Use** flag or region-specific consent signals if operating under CCPA opt-outs. - Maintain a clear, accurate privacy policy disclosure describing that both browser and server-side tracking are used, and do not represent this setup as fully anonymized — hashed data is still considered personal data under most privacy frameworks when it can be matched to an individual. - This guide does not include, and should not be paired with, any claim about how much conversion volume or attribution this recovers — no such figures should be presented to stakeholders as expected 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 + server-side CAPI with shared event_id for deduplication and explains why both are needed under ITP/ETP/ad-blocker limits.
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓Section 2 lists ViewContent, AddToCart, InitiateCheckout, and Purchase each with value, currency, content_ids (and content_ids explicitly called required 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 JavaScript sketch includes event_name: 'Purchase', event_time, event_id, action_source: 'website', and a user_data block with hashed em/ph and fbc/fbp.
validation
End-to-end validation is described using Meta's Events Manager test events tool and an explicit check that duplicate browser/server events are being deduplicated.
✓Section 6 instructs using Meta Events Manager's Test Events tool and explicitly checking that events 'show as deduplicated ... not counted twice'.
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 1 states Pixel fires on the order status page while CAPI is triggered via Shopify's orders/paid webhook, establishing the webhook as the server-side source of truth for Purchase.
limits_stated
Limitations are stated honestly: no promised attribution-recovery percentages, and consent/regional rules are noted as constraints on what may be sent.
✓Section 7 explicitly says 'no such figures should be presented' regarding attribution recovery and requires gating both Pixel and CAPI on consent state per GDPR/CPRA.
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 deduplication requires identical event_name and event_id sent on both Pixel and CAPI so Meta 'counts only one' event.
event_id_retry_stability
The event_id is generated or derived once per commerce event, shared by browser and server, and reused unchanged on webhook retries or order updates; a new random suffix per send or retry fails.
✓The event_id is deterministically derived as `${order.id}_purchase`, ensuring it stays identical across retries rather than being randomly generated per send.
event_time_stable
The server Purchase event uses the purchase/order occurrence timestamp in Unix seconds and preserves it across retries; using the current send or retry time fails.
✓event_time is computed from order.processed_at converted to Unix seconds, preserving the original order timestamp rather than the send/retry time.
pii_hashing
Customer data handling is correct: personally identifiable fields (e.g. email) are normalized (trimmed, lowercased) and SHA-256 hashed before sending in user_data.
✓The sha256 helper trims and lowercases the value before hashing, and email/phone are passed through this function before inclusion in user_data.
actionable_path
The recommended Shopify path is decisive and executable for a small DTC store (a clear recommendation with concrete setup steps, not an undifferentiated list of options).
✓Section 5 gives a clear decisive recommendation ('Use the native Meta sales channel app as the foundation') with concrete reasoning and fallback conditions for custom implementation.

Claude Opus 5 default

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.35 · 183.3s · 13.7k tok
# Conversion Tracking Implementation Guide ## Cedar & Coil — Arc Clip Lamp | Shopify → Meta **Status: pre-launch draft.** No campaign has run and no performance data exists, so every number in this guide is a configuration target or a validation threshold, not a measured result. This guide describes how to build the measurement layer; it does not predict how much attribution any configuration will recover. **Inputs to collect before you start** - Meta Pixel / Dataset ID (Events Manager) - Business Manager ID, verified domain (`cedarandcoil.com` or equivalent) - Shopify store admin access + ability to create a private/custom app (for the custom path) - CAPI system-user access token with `ads_management` on the dataset - A consent management platform (CMP) decision, or the Shopify Customer Privacy API defaults - Catalog feed status (needed to decide `content_ids` format) --- ## 1. Recommended Architecture **Ship both signal paths for every conversion event, joined by a shared `event_id`.** ``` ┌─────────────────────────────┐ Shopper's browser │ Meta Pixel (fbq) │──► Meta (theme + Shopify │ event_id = <deterministic> │ Customer Events) └─────────────────────────────┘ ┌── dedup on │ (event_name, event_id) Shopify backend ┌─────────────────────────────┐ │ (webhooks / │ Conversions API (HTTPS POST)│──►┘ Admin API) │ event_id = <same value> │ │ + hashed customer data │ └─────────────────────────────┘ ``` **Why the browser Pixel alone is not sufficient** - Safari ITP caps script-written first-party cookies (including `_fbp`) at 7 days; the `_fbc` click-ID cookie is written by a script and is subject to the same cap. - Firefox ETP and Brave block the Meta domain outright for a share of sessions. - Ad blockers and enterprise DNS filtering drop `fbevents.js` before it loads. - Shopify's Checkout Extensibility sandbox restricts what runs on checkout and thank-you pages — the highest-value event (`Purchase`) sits in the most constrained environment. - Network drop-off: page unloads during redirect to the order status page can kill an in-flight beacon. **Why CAPI alone is not sufficient** - Server events have no `_fbp` / `_fbc` unless the browser captured and forwarded them first — the browser layer is the source of the strongest identifiers. - Browser events supply `client_user_agent` and referrer context and populate signals used for optimization and diagnostics. - Removing the Pixel entirely degrades Event Match Quality rather than improving it. **What the pairing actually buys you:** two independent paths to the same event, so a failure or block on one path does not silently zero out the event, plus a richer identifier set (server-side hashed customer PII + browser cookies) for matching. Treat it as redundancy and match-signal enrichment. Do not commit to a recovery figure to stakeholders — you have no baseline, and the outcome depends on your traffic's browser mix, consent rate, and match quality. --- ## 2. Event Plan and Parameters Cedar & Coil is a single-SKU store ($68 Arc Clip Lamp), which makes the payloads simple and makes value/currency errors very visible in QA. ### 2.0 Global parameters (every event, both paths) | Parameter | Value | Notes | |---|---|---| | `event_name` | Exact Meta standard name, case-sensitive | `ViewContent`, `AddToCart`, `InitiateCheckout`, `Purchase` | | `event_id` | Deterministic string, identical across Pixel + CAPI | See §3 | | `event_time` | Unix seconds (server side) | Must be within 7 days of receipt; aim for <60s latency | | `action_source` | `website` | All four events originate on the storefront | | `event_source_url` | Full URL of the page | Server side, pass through from the browser or reconstruct | | `currency` | `USD` | ISO-4217, uppercase, on all four events | | `content_type` | `product` | Use `product_group` only if you feed groups to the catalog | **`content_ids` format decision (make it once):** if you run a Meta catalog for dynamic ads or Advantage+ catalog, `content_ids` must exactly match the `id` field in the catalog feed. Shopify's Meta sales channel feed uses the **variant ID** (e.g. `shopify_US_8123456789_44987654321`) by default. If you have no catalog, use a stable SKU such as `ARC-CLIP-LAMP`. Mixing formats across events breaks catalog matching and produces confusing content-level reporting. ### 2.1 ViewContent Fires on the Arc Clip Lamp product page. Debounce so it fires once per pageview, not per scroll or variant toggle. ``` content_ids: ["ARC-CLIP-LAMP"] // or catalog variant ID content_name: "Arc Clip Lamp" content_type: "product" content_category: "Lighting" // optional, keep stable value: 68.00 currency: "USD" ``` `value` on `ViewContent` should be the displayed unit price. It is not revenue; it is a relevance signal. ### 2.2 AddToCart Fires on successful cart mutation (AJAX response 200 / cart drawer confirmation), **not** on button click. Clicking before a stock or validation failure inflates the numerator of your funnel. ``` content_ids: ["ARC-CLIP-LAMP"] content_type: "product" contents: [{ "id": "ARC-CLIP-LAMP", "quantity": 1, "item_price": 68.00 }] value: 68.00 // quantity × item_price currency: "USD" ``` ### 2.3 InitiateCheckout Fires when the shopper reaches checkout (Shopify `checkout_started` Customer Event), not when they click "Checkout." ``` content_ids: ["ARC-CLIP-LAMP"] content_type: "product" contents: [{ "id": "ARC-CLIP-LAMP", "quantity": 1, "item_price": 68.00 }] num_items: 1 value: 68.00 currency: "USD" ``` ### 2.4 Purchase The event your bidding depends on. Send from both paths, always, with all required parameters. ``` content_ids: ["ARC-CLIP-LAMP"] // REQUIRED, array of strings content_type: "product" contents: [{ "id": "ARC-CLIP-LAMP", "quantity": 1, "item_price": 68.00 }] num_items: 1 value: 68.00 // REQUIRED, number not string currency: "USD" // REQUIRED, uppercase ISO-4217 order_id: "5544332211" // Shopify order ID — dedup + reconciliation ``` **Value definition — decide and document.** Pick one and apply it identically on both paths: - **Recommended:** net product subtotal after discounts, excluding shipping and tax. Cleanest ROAS read against COGS. - Alternative: order grand total. Acceptable, but shipping and tax inflate ROAS and make cross-market comparison noisy. Send `value` as a numeric type with two decimals. Never send `"$68.00"`, `"68"` as a string, or `0`. A `Purchase` with `value: 0` or a missing `currency` will register but is unusable for value-based bidding. **Refunds:** Meta does not net out refunds from `Purchase`. If refund rate becomes material, track it in Shopify and adjust ROAS targets manually rather than sending negative-value events. --- ## 3. Deduplication — Exactly How It Works Meta deduplicates when it receives two events that share **both**: 1. the same `event_name` (case-sensitive), **and** 2. the same `event_id`. The Pixel calls it `eventID` (camelCase, in the third argument); the CAPI payload calls it `event_id` (snake_case, top-level in the event object). They are the same value. ```js // Browser fbq('track', 'Purchase', { value: 68.00, currency: 'USD', content_ids: ['ARC-CLIP-LAMP'], content_type: 'product' }, { eventID: 'purchase_5544332211' } ); ``` ```json // Server { "event_name": "Purchase", "event_id": "purchase_5544332211", "...": "..." } ``` **Behavior:** Meta keeps whichever copy arrives first and discards the later duplicate. It does **not** merge the two payloads. Therefore **both copies must carry the full parameter set** — value, currency, content_ids, and all available customer data. If the browser copy wins and it is missing `content_ids`, the richer server copy is dropped and you lose that data. Populate both fully; assume either may win. **Window:** Meta's documented deduplication window allows the two copies to arrive up to roughly 48 hours apart, but do not rely on the tail. Fire the CAPI event within seconds of the browser event. Long server-side delays (batch jobs, nightly syncs) risk falling outside the window and also degrade optimization freshness. **Generating the `event_id` — it must be deterministic, not random.** Both paths must independently compute the same string without talking to each other. | Event | `event_id` recipe | |---|---| | `Purchase` | `purchase_{shopify_order_id}` — the order ID is available in the checkout-completed browser event and in the `orders/paid` webhook | | `InitiateCheckout` | `ic_{checkout_token}` | | `AddToCart` | `atc_{cart_token}_{variant_id}_{unix_minute}` | | `ViewContent` | `vc_{session_or_client_id}_{variant_id}_{unix_minute}` | For `ViewContent` and `AddToCart` — where there is no server-issued ID — the more practical pattern is: generate a UUID in the browser, attach it as `eventID`, and pass the same UUID to your server endpoint in the same request that triggers the CAPI call. This guarantees a match without timestamp-bucketing fragility. **Secondary safety net:** Meta additionally applies redundancy checks using `fbp` / `fbc` and, for `Purchase`, `order_id`. This is a backstop, not a substitute. `event_id` is the mechanism you control and the one to test. **The double-count failure mode to avoid:** if the Shopify Meta sales channel is already sending a Purchase and you add your own webhook-based Purchase with a different `event_id`, you will report roughly 2× purchases and 2× revenue, and your bidding will optimize against inflated conversions. Before adding any second source, confirm you control the `event_id` on both. --- ## 4. Preparing Customer Information for Server-Side Sends All personally identifying parameters must be **normalized, then hashed with SHA-256, then hex-encoded in lowercase** before leaving your server. Send them inside `user_data` as arrays of strings. ### 4.1 Normalize first, hash second | Field | Key | Normalization | Example → hashed input | |---|---|---|---| | Email | `em` | Trim, lowercase, strip nothing else (keep dots and `+` in Gmail addresses) | ` Ada@Example.COM ` → `ada@example.com` | | Phone | `ph` | Digits only, include country code, **no** `+`, no spaces/dashes/parens | `+1 (503) 555-0134` → `15035550134` | | First name | `fn` | Trim, lowercase, strip punctuation; UTF-8; keep accents | `Ada` → `ada` | | Last name | `ln` | Same as first name | `Ó Brien` → `óbrien` | | City | `ct` | Lowercase, remove spaces and punctuation | `São Paulo` → `sãopaulo` | | State/Province | `st` | 2-letter code, lowercase (US/CA) | `OR` → `or` | | Zip / Postal | `zp` | US: first 5 digits only. Others: lowercase, no spaces | `97214-1234` → `97214` | | Country | `country` | 2-letter ISO-3166-1 alpha-2, lowercase | `US` → `us` | | Date of birth | `db` | `YYYYMMDD` | Do not collect for this store | | External ID | `external_id` | Your stable customer/anonymous ID; hash it | Shopify customer ID | ### 4.2 Send these **unhashed** (hashing them breaks matching) | Key | Source | |---|---| | `client_ip_address` | Shopify order `client_details.browser_ip`, or your edge headers | | `client_user_agent` | Shopify order `client_details.user_agent` — required for good match quality | | `fbp` | `_fbp` cookie value, verbatim (e.g. `fb.1.1712345678901.1234567890`) | | `fbc` | `_fbc` cookie value, or constructed from `fbclid`: `fb.1.{click_timestamp_ms}.{fbclid}` | ### 4.3 Rules that trip people up - **Do not double-hash.** If a field arrives already hashed (some CDPs pre-hash), pass it through unchanged. A hash of a hash matches nothing. - **Omit, never fake.** If you don't have a last name, leave `ln` out. Do not send a hash of an empty string, `"null"`, `"undefined"`, or `"n/a"` — these produce a valid hash of garbage and quietly poison match quality. - **Hash server-side only.** Never hash in the browser and pass hashes around client-side; you gain nothing and add exposure. - **Arrays.** `user_data` fields accept arrays: `"em": ["<hash>"]`. Use arrays for multi-value cases (customer email + a second contact email on the order). - **Capture `_fbc` early.** The click ID is only in the landing URL. Read `fbclid` on first page load, store it (first-party cookie or your session store), and attach it to the order record so the server-side `Purchase` can include it. If you only read cookies at checkout, ITP expiry will have eaten it for some users. - **`external_id` is high-leverage.** A stable pseudonymous ID set on first visit and persisted through purchase gives Meta a join key that survives cookie expiry. ### 4.4 Purchase `user_data` payload shape ```json "user_data": { "em": ["8f9b...c2a1"], "ph": ["3e7d...9b04"], "fn": ["1c4a...77ef"], "ln": ["b210...3d8c"], "ct": ["9a55...e1b7"], "st": ["44fe...0c92"], "zp": ["7dd1...ab36"], "country": ["79ad...5f10"], "external_id": ["c018...6e44"], "client_ip_address": "203.0.113.42", "client_user_agent": "Mozilla/5.0 (Macintosh; ...) Safari/605.1.15", "fbp": "fb.1.1712345678901.1234567890", "fbc": "fb.1.1712345670000.IwAR0abc123..." } ``` Target **Event Match Quality of 6.0+** on `Purchase`. Below ~5.0, audit for the failure modes above before touching anything else. --- ## 5. Concrete Shopify Setup Path ### 5.1 Option A — Native Meta sales channel (Facebook & Instagram app) **How it works:** install the Facebook & Instagram sales channel from the Shopify App Store, connect Business Manager, select the Pixel/Dataset, and set **data sharing to "Maximum"** — this is the setting that enables the Conversions API. Shopify then sends browser events via the Customer Events pipeline and server events from its own infrastructure, with `event_id` deduplication handled for you. | | | |---|---| | **Pros** | Zero code. Survives Checkout Extensibility (Shopify has privileged checkout access you do not). Purchase fires reliably from the order record, not a fragile thank-you page. Dedup handled. Catalog sync included for dynamic ads. Maintained by Shopify as Meta's API versions change. | | **Cons** | Fixed parameter set — you cannot add custom parameters or a custom `value` definition. No control over `event_id` scheme. Limited visibility when something breaks. Consent behavior is governed by Shopify's Customer Privacy settings, not your CMP directly. | ### 5.2 Option B — Custom implementation **How it works:** a Shopify **Custom Pixel** (Settings → Customer events) subscribes to `product_viewed`, `product_added_to_cart`, `checkout_started`, and `checkout_completed` and fires `fbq` with your `eventID`. In parallel, a Shopify webhook on `orders/paid` hits your own endpoint, which hashes customer data and POSTs to CAPI. | | | |---|---| | **Pros** | Full control of parameters, value definition, `event_id`, and consent gating. Can enrich with CRM/LTV data. Can route through a server-side GTM container or a warehouse. | | **Cons** | You own the code, the token rotation, the API version upgrades, the retry logic, and the double-count risk. Custom Pixels run in a sandboxed iframe with constrained DOM/cookie access — reading `_fbp`/`_fbc` requires deliberate work via the browser API surface Shopify exposes. Meaningful ongoing maintenance. | ### 5.3 Recommendation for Cedar & Coil **Start with Option A — the native Meta sales channel with data sharing set to Maximum.** Rationale: a single-SKU, pre-launch DTC store with one $68 product does not have a measurement problem that custom code solves. The native app's deduplication and checkout access are the two hardest parts of a custom build, and Shopify's Checkout Extensibility sandbox makes the custom path meaningfully harder than it was in the Checkout.liquid era. Ship the native app, verify it (§6), and start spending. **Add a custom server-side layer only when a specific need appears**, such as: - You need a value definition the native app doesn't produce (e.g. margin-based or subtotal-excluding-shipping value for value-based bidding). - You need offline or CRM events (e.g. a wholesale channel, or post-purchase LTV signals). - Events Manager diagnostics show a match-quality or coverage problem you've traced to the native integration. **If you do add a custom layer, choose one owner per event.** Either disable the native app's Purchase and own it fully, or keep the native app and only add events it does not send. Never send two Purchase events with different `event_id` values. ### 5.4 Code sketch — server-side Purchase (custom path) Node/Express handler for the Shopify `orders/paid` webhook. **Sketch, not production code:** add retries with exponential backoff, a dead-letter queue, structured logging, secret management, and idempotency on `order_id`. ```js // server/routes/shopify-orders-paid.js import crypto from 'node:crypto'; import express from 'express'; const router = express.Router(); const PIXEL_ID = process.env.META_PIXEL_ID; const ACCESS_TOKEN = process.env.META_CAPI_TOKEN; // system user token const API_VERSION = 'v21.0'; const SHOPIFY_SECRET = process.env.SHOPIFY_WEBHOOK_SECRET; // --- normalize + SHA-256 hex (lowercase) --- const sha256 = (v) => crypto.createHash('sha256').update(v, 'utf8').digest('hex'); const hash = (value, normalizer = (s) => s.trim().toLowerCase()) => { if (value === null || value === undefined) return undefined; const norm = normalizer(String(value)); if (!norm) return undefined; // omit, never hash "" return [sha256(norm)]; }; const normPhone = (s) => s.replace(/\D/g, ''); // digits only, no '+' const normName = (s) => s.trim().toLowerCase().replace(/[^\p{L}\p{N}]/gu, ''); const normZip = (s) => s.trim().toLowerCase().replace(/\s/g, '').split('-')[0]; const normCountry = (s) => s.trim().toLowerCase().slice(0, 2); // --- verify Shopify HMAC before trusting the body --- function verifyShopify(rawBody, headerHmac) { const digest = crypto.createHmac('sha256', SHOPIFY_SECRET).update(rawBody).digest('base64'); return crypto.timingSafeEqual(Buffer.from(digest), Buffer.from(headerHmac || '')); } router.post('/webhooks/orders-paid', express.raw({ type: 'application/json' }), async (req, res) => { if (!verifyShopify(req.body, req.get('X-Shopify-Hmac-Sha256'))) { return res.status(401).send('bad hmac'); } res.status(200).send('ok'); // ack fast, then process const order = JSON.parse(req.body.toString('utf8')); const addr = order.shipping_address || order.billing_address || {}; const cd = order.client_details || {}; // fbp / fbc captured on the storefront and stashed in cart/order attributes const attrs = Object.fromEntries( (order.note_attributes || []).map(a => [a.name, a.value]) ); // net product subtotal after discounts, excluding shipping + tax const value = Number(order.current_subtotal_price ?? order.subtotal_price); const contents = order.line_items.map(li => ({ id: li.sku || String(li.variant_id), // MUST match catalog feed ids quantity: li.quantity, item_price: Number(li.price), })); const payload = { data: [{ event_name: 'Purchase', event_time: Math.floor(new Date(order.processed_at || Date.now()).getTime() / 1000), event_id: `purchase_${order.id}`, // MUST match browser eventID event_source_url: 'https://cedarandcoil.com/checkout/thank-you', action_source: 'website', user_data: { em: hash(order.email), ph: hash(order.phone || addr.phone, normPhone), fn: hash(addr.first_name, normName), ln: hash(addr.last_name, normName), ct: hash(addr.city, normName), st: hash(addr.province_code, (s) => s.trim().toLowerCase()), zp: hash(addr.zip, normZip), country: hash(addr.country_code, normCountry), external_id: hash(order.customer?.id), client_ip_address: cd.browser_ip, // NOT hashed client_user_agent: cd.user_agent, // NOT hashed fbp: attrs._fbp, // NOT hashed fbc: attrs._fbc, // NOT hashed }, custom_data: { currency: (order.currency || 'USD').toUpperCase(), value, 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), }, // Consent-driven; see §7. Omit entirely when not applicable. // data_processing_options: [], data_processing_options_country: 0, data_processing_options_state: 0, }], // test_event_code: 'TEST12345', // REMOVE before production traffic }; // strip undefined user_data keys — omit, never send empty hashes payload.data[0].user_data = Object.fromEntries( Object.entries(payload.data[0].user_data).filter(([, v]) => v !== undefined && v !== '') ); const r = await fetch( `https://graph.facebook.com/${API_VERSION}/${PIXEL_ID}/events?access_token=${ACCESS_TOKEN}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) } ); const body = await r.json(); if (!r.ok || body.error) { // enqueue for retry with backoff; alert on repeated failure console.error('CAPI Purchase failed', order.id, body); } } ); export default router; ``` **The matching browser side** (Shopify Custom Pixel, `checkout_completed`) must use the identical ID: ```js analytics.subscribe('checkout_completed', (event) => { const order = event.data.checkout.order; fbq('track', 'Purchase', { value: Number(event.data.checkout.subtotalPrice.amount), currency: event.data.checkout.currencyCode, content_ids: ['ARC-CLIP-LAMP'], content_type: 'product', order_id: String(order.id), }, { eventID: `purchase_${order.id}` }); // ← same string as the server }); ``` Confirm the order ID exposed to the Custom Pixel is the same numeric ID the `orders/paid` webhook delivers (Shopify surfaces both legacy numeric IDs and GIDs in different contexts). If they differ, normalize both to one form before templating the `event_id` — a mismatch here silently disables deduplication. --- ## 6. End-to-End Validation Before Scaling Spend Work through this in order. Do not raise budget past a small learning spend until every item passes. **Stage 1 — Prerequisites** 1. Domain verified in Business Manager (Brand Safety → Domains), DNS TXT or meta-tag method. 2. Aggregated Event Measurement configured: `Purchase` set as the highest-priority event in the 8-slot list for the verified domain. Without this, iOS conversions are throttled regardless of how good your CAPI is. 3. Access token stored as a secret, not in the repo. Confirm it's a system-user token (long-lived), not a user token. **Stage 2 — Browser layer** 4. Install Meta Pixel Helper. Walk product page → add to cart → checkout. Confirm each event fires **exactly once**, with the expected `value`, `currency`, `content_ids`, and a visible `eventID`. 5. Confirm `_fbp` is set on first visit and `_fbc` is set when you arrive with a `?fbclid=` parameter appended manually. **Stage 3 — Server layer** 6. In Events Manager → **Test Events**, copy the `test_event_code` into your payload and place a real test order (use a 100%-off discount code or Shopify's Bogus Gateway). 7. Confirm the server `Purchase` appears in Test Events within seconds, with `action_source: website`, correct `value`/`currency`/`content_ids`, and populated `user_data` keys. 8. Confirm the response body has `events_received: 1` and an empty `messages` array. Any warning in `messages` is a real defect — fix it now. 9. **Remove `test_event_code` from production code.** Events sent with it do not count toward attribution or optimization. **Stage 4 — Deduplication proof (the critical test)** 10. Place a test order with both paths live. In Events Manager → your dataset → **Purchase** → the deduplication/"Redundant events" panel, confirm the pair is being deduplicated and that Meta reports one counted Purchase, not two. 11. Cross-check totals: place 5 test orders. Events Manager should show **5** Purchases over that window, not 10. If you see 10, your `event_id` values do not match — inspect both payloads before proceeding. **Stage 5 — Data quality** 12. Check **Event Match Quality** on `Purchase` in Events Manager. Target 6.0+. If low, audit §4.3 (empty-string hashes, double-hashing, missing `client_user_agent`, missing `fbc`). 13. Check the **Diagnostics** tab for every event. Resolve all errors and warnings — especially "missing required parameter," "invalid content_ids format," and "server event missing user data." 14. If a catalog is connected, confirm `content_ids` match the feed by checking the catalog's diagnostics for unmatched IDs. **Stage 6 — Reconciliation over live traffic** 15. Run a small budget for 7 days. Then compare, over the same date range and time zone: - Shopify Analytics order count vs. Events Manager `Purchase` count → should be within a few percent. Large gaps up = double-counting or test orders; large gaps down = a broken path or consent blocking. - Shopify revenue vs. Events Manager `Purchase` value sum → should reconcile under your chosen value definition. 16. Confirm the `Purchase` count is not lower than the `InitiateCheckout` count in a way that contradicts Shopify's checkout funnel — that pattern usually means the browser Purchase is failing and the server path is carrying the load alone (fine) or that both are dropping (not fine). 17. Set a monitoring alert on CAPI non-200 responses and on any day with zero server events. **Only after Stages 1–6 pass should budget scale.** Optimizing against a broken or double-counted Purchase signal trains the algorithm on noise, and the damage persists after the fix. --- ## 7. Consent and Compliance **This is not legal advice.** Have counsel review the final configuration and the privacy policy before launch. **Consent gating is upstream of everything in this guide.** The Conversions API is a resilience and match-quality mechanism, not a consent workaround. If a user has not consented (or has opted out) under an applicable regime, you must suppress **both** the Pixel event and the server-side event for that user. Sending server-side data that the browser was blocked from sending, in order to bypass a user's choice, is exactly the practice regulators are looking for. **Practical implementation** - **EEA / UK (GDPR, ePrivacy):** opt-in required before setting cookies or transmitting identifiers. Implement a CMP; block `fbevents.js` and suppress the CAPI call until consent is recorded. If you use Meta's Consent Mode–style signaling, configure it deliberately rather than defaulting to "granted." - **US state laws (CA, CO, CT, VA, TX, OR, and others):** honor opt-out of sale/sharing. Meta's mechanism is **Limited Data Use** — set `data_processing_options: ["LDU"]` with `data_processing_options_country: 1` and `data_processing_options_state: 1000` (California) or `0` to let Meta geolocate. Wire this to your CMP's opt-out signal, and honor **Global Privacy Control** headers as an opt-out in states that require it. - **Shopify:** the Customer Privacy API and the store's privacy/cookie banner settings govern whether Customer Events pixels fire. If you use the native Meta sales channel, verify that its behavior matches your CMP's state — test with consent denied and confirm no events reach Events Manager. - **Data minimization:** send only what improves matching. For Cedar & Coil, email + phone + name + address + `fbp`/`fbc` + `external_id` is sufficient. Do not collect or transmit date of birth, gender, or any special-category data for a lamp purchase. - **Never send unhashed PII to Meta.** Hash server-side, always. Also confirm no PII leaks into `event_source_url` query strings, `custom_data` fields, or your own logs. - **Contracts and disclosure:** Meta's Business Tools Terms and the Controller/Processor addendum apply. Your privacy policy must disclose the use of Meta pixels and server-side transmission, name the categories of data shared, and explain the opt-out path. Update your ROPA/data map to include the CAPI endpoint. - **Retention and access:** rotate the CAPI access token on a schedule, restrict it to the single dataset, and log who has it. Do not retain raw PII in your webhook processing layer longer than needed to send the event. - **Expect and accept lower volume from consent-restricted regions.** That is the correct outcome, not a bug to engineer around. --- ## Appendix — Launch Checklist - [ ] Meta sales channel installed, data sharing = Maximum - [ ] Domain verified; AEM configured with `Purchase` as top priority - [ ] `content_ids` format decided and consistent across all four events + catalog - [ ] `value` definition documented (subtotal after discounts, ex. shipping/tax) - [ ] All four events firing once each, verified in Pixel Helper - [ ] Dedup proven: 5 test orders → 5 counted Purchases - [ ] Event Match Quality on `Purchase` ≥ 6.0 - [ ] Diagnostics tab clear of errors and warnings - [ ] `test_event_code` removed from production - [ ] CMP tested with consent denied → zero events on both paths - [ ] LDU wired to US opt-out signal; GPC honored - [ ] Privacy policy updated and reviewed by counsel - [ ] Shopify vs. Events Manager reconciliation run over 7 days - [ ] Monitoring/alerting on CAPI failures live All campaign creative referencing the Arc Clip Lamp remains draft-only pending approval; the approved CTA is **Explore the Arc Clip Lamp**.
Score the judge's verdict, criterion by criterion11/11 criteria passed
RequirementVerdictEvidence
architecture
The guide recommends browser Pixel plus server-side Conversions API with deduplication and explains why both are needed under browser privacy limits.
✓Section 1 explicitly recommends browser Pixel + server-side CAPI joined by shared event_id and lists concrete browser-privacy reasons (ITP, ad blockers, checkout sandbox) neither alone can cover.
events_mapped
All four standard events (ViewContent, AddToCart, InitiateCheckout, Purchase) are covered with key parameters, including value, currency, and content_ids on Purchase.
✓Sections 2.1-2.4 cover ViewContent, AddToCart, InitiateCheckout, and Purchase each with value, currency, content_ids and other parameters.
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 payload in 5.4 includes event_name, event_time, event_id, action_source: 'website', and a full user_data block.
validation
End-to-end validation is described using Meta's Events Manager test events tool and an explicit check that duplicate browser/server events are being deduplicated.
✓Section 6 Stage 3 uses Events Manager Test Events tool and Stage 4 explicitly checks the deduplication/redundant-events panel for correct counts.
sources_defined
For each event it is clear where it fires (browser vs server) and what the source of truth is (e.g. Purchase from the Shopify order webhook/server, not only the thank-you page).
✓Each event states its firing trigger (e.g. AddToCart on 'successful cart mutation... not on button click') and Purchase is explicitly sourced from the orders/paid webhook 'not a fragile 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 guide states 'Do not commit to a recovery figure to stakeholders' and dedicates Section 7 to consent/regional constraints (GDPR, US state laws, LDU) governing what can be sent.
dedup_correct
Deduplication is technically correct: the same event_id and event_name sent on both the Pixel and CAPI event so Meta drops the duplicate; not a vague mention.
✓Section 3 states Meta deduplicates when 'the same event_name... and the same event_id' are shared and shows matching fbq eventID and CAPI event_id 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.
✓event_id is derived deterministically as `purchase_${order.id}` from the stable Shopify order ID, ensuring the same value is reused rather than randomly regenerated on resend.
event_time_stable
The server Purchase event uses the purchase/order occurrence timestamp in Unix seconds and preserves it across retries; using the current send or retry time fails.
✓The code computes event_time from `order.processed_at` (the order occurrence timestamp) converted to Unix seconds rather than Date.now() at 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.1 specifies normalization (trim, lowercase) then SHA-256 hex hashing for em/ph/fn/ln etc., matched by the `hash()` function in the code sketch.
actionable_path
The recommended Shopify path is decisive and executable for a small DTC store (a clear recommendation with concrete setup steps, not an undifferentiated list of options).
✓Section 5.3 gives a decisive recommendation ('Start with Option A — the native Meta sales channel with data sharing set to Maximum') with concrete rationale and next steps for a small DTC store.

Claude Haiku 4.5 default

Task failed
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.055 · 89.8s · 10.9k tok
# Meta Conversion Tracking Implementation Guide for Cedar & Coil ## 1. Recommended Architecture: Dual-Layer Tracking ### Overview Implement **browser-side Meta Pixel** + **server-side Conversions API (CAPI)** with deduplication. This architecture is essential for Cedar & Coil because: | Layer | Purpose | Resilience | Coverage | |-------|---------|-----------|----------| | **Browser Pixel** | Real-time frontend signals, audience building, limited by ITP/ETP | Fails when cookies blocked or JavaScript disabled | iOS 14.5+, browsers with strict privacy | | **Server-side CAPI** | First-party data transmission, hashed customer info, cookie-independent | Survives privacy restrictions, offline conversions, direct server calls | Works universally once implemented | ### Why Both Are Mandatory 1. **Privacy Fragmentation**: iOS Safari, Firefox, and Chrome with Enhanced Tracking Protection block third-party cookies. Server-side CAPI circumvents this by sending hashed customer data (email, phone) directly from your Shopify server to Meta servers—no browser cookies required. 2. **Data Richness**: Browser Pixel captures behavioral signals (time on page, clicks) useful for lookalike audiences. CAPI captures clean transactional data (order ID, value, items) resistant to loss. 3. **Attribution Resilience**: When the browser Pixel fails to fire (privacy blockers, adblocker, SPAs not tracking), CAPI continues to report the conversion. Meta's matching engine can still credit the campaign via first-party customer data. 4. **Measurement Under iOS 14.5+**: Apple's App Tracking Transparency prevents Pixel from reaching many iOS users. CAPI's server-to-server channel is not subject to ATT prompts. ### Architecture Diagram (Conceptual) ``` User visits Meta ad for Arc Clip Lamp ↓ [Browser Pixel fires] ← ViewContent, AddToCart, InitiateCheckout ↓ (real-time, audience building) User completes checkout on Shopify ↓ [Shopify webhook triggers] ↓ [Server-side CAPI call] ← Purchase with hashed email, order ID ↓ (deduped against Pixel) Meta receives conversion (single attribution credit) ``` --- ## 2. Standard Events & Parameters Cedar & Coil should send four standard events at key funnel steps. Meta uses these as templates for machine learning in auction and attribution. ### ViewContent **Fired**: When user lands on product page or views Arc Clip Lamp in a collection. **Parameters**: ```json { "event_name": "ViewContent", "event_id": "<unique_client_event_id>", "event_time": 1699564800, "user_data": { "em": "<hashed_email_if_logged_in>" }, "custom_data": { "value": 68.00, "currency": "USD", "content_name": "Arc Clip Lamp", "content_ids": ["arc-clip-lamp-001"], "content_type": "product", "contents": [ { "id": "arc-clip-lamp-001", "quantity": 1, "delivery_category": "home_delivery" } ] } } ``` **Why**: Baseline signal for audience segmentation. Tells Meta "this user showed intent." Valuable for building lookalike audiences from product viewers. --- ### AddToCart **Fired**: When user clicks the "Add to Cart" button on the product page (browser Pixel) or server confirmation webhook (optional, rare for CAPI). **Parameters**: ```json { "event_name": "AddToCart", "event_id": "<unique_client_event_id>", "event_time": 1699564920, "user_data": { "em": "<hashed_email_if_logged_in>" }, "custom_data": { "value": 68.00, "currency": "USD", "content_name": "Arc Clip Lamp", "content_ids": ["arc-clip-lamp-001"], "content_type": "product", "contents": [ { "id": "arc-clip-lamp-001", "quantity": 1 } ] } } ``` **Why**: Signals purchase intent one step before checkout. Useful for retargeting users who abandoned cart. Meta weights this as a strong predictor of conversion. --- ### InitiateCheckout **Fired**: When user clicks the checkout button or enters the checkout flow (not necessarily payment info entry). **Parameters**: ```json { "event_name": "InitiateCheckout", "event_id": "<unique_client_event_id>", "event_time": 1699565040, "user_data": { "em": "<hashed_email_if_logged_in>" }, "custom_data": { "value": 68.00, "currency": "USD", "content_name": "Arc Clip Lamp", "content_ids": ["arc-clip-lamp-001"], "content_type": "product", "contents": [ { "id": "arc-clip-lamp-001", "quantity": 1 } ], "num_items": 1 } } ``` **Why**: Distinguishes checkout abandoners from browsers. Helps Meta identify high-intent users for retargeting campaigns. --- ### Purchase (Primary Conversion Event) **Fired**: Server-side via Conversions API only (after Shopify order webhook fires). **Parameters** (CAPI payload): ```json { "event_name": "Purchase", "event_id": "<unique_order_id>_purchase", "event_time": 1699565400, "user_data": { "em": "<sha256_hashed_email>", "ph": "<sha256_hashed_phone>", "fn": "<sha256_hashed_first_name>", "ln": "<sha256_hashed_last_name>", "ct": "<sha256_hashed_city>", "st": "<sha256_hashed_state>", "zp": "<sha256_hashed_zip>", "country": "<sha256_hashed_country>", "external_id": "<sha256_hashed_customer_id>" }, "custom_data": { "value": 68.00, "currency": "USD", "content_name": "Arc Clip Lamp", "content_type": "product", "content_ids": ["arc-clip-lamp-001"], "num_items": 1, "contents": [ { "id": "arc-clip-lamp-001", "quantity": 1, "title": "Arc Clip Lamp", "description": "Rechargeable task light with clamp", "brand": "Cedar & Coil", "category": "Lighting", "price": 68.00 } ] }, "data_processing_options": ["LDU"], "data_processing_options_country": 1, "data_processing_options_state": 1000 } ``` **Key Parameters Explained**: - **value**: Order subtotal (before tax/shipping if tax-inclusive; Meta asks for revenue as customer sees it). - **currency**: Always "USD" for Cedar & Coil. - **content_ids**: Array of product IDs in order. For single Arc Clip Lamp, `["arc-clip-lamp-001"]`. Allows Meta to optimize by product. - **external_id**: Hashed Shopify customer ID or order ID; enables Meta to link offline purchases to ads. - **user_data**: Hashed customer PII (email required; phone/name optional but improve matching). See Section 4 for hashing requirements. **Why CAPI-only for Purchase**: Browser Pixel Purchase events can be blocked by privacy tools. Server-side ensures the conversion always reaches Meta's servers. The hashed customer data allows Meta to match the conversion to the original ad impression via their matching network, even if the browser cookie was deleted. --- ## 3. Deduplication: How Pixel and CAPI Work Together ### The Deduplication Flow Meta deduplicates conversions using the **event_id** parameter. Both Pixel and CAPI must send the same `event_id` for a single user action, or different `event_id` values to signal distinct actions. #### Scenario: User Completes Purchase **Browser Pixel fires** (on checkout success page): ```javascript fbq('track', 'Purchase', { value: 68.00, currency: 'USD', content_ids: ['arc-clip-lamp-001'] }, { eventID: 'order_12345_pixel' // Unique ID for this Purchase event }); ``` **Server-side CAPI fires** (webhook receives `order.created` and sends to Meta): ```json { "event_name": "Purchase", "event_id": "order_12345_pixel", // SAME event_id as Pixel "event_time": 1699565400, "user_data": { "em": "<sha256_hashed_email>" }, "custom_data": { "value": 68.00, "currency": "USD", "content_ids": ["arc-clip-lamp-001"] } } ``` **Meta's Deduplication Logic**: 1. Both events arrive with `event_id` = `order_12345_pixel`. 2. Meta matches them by `event_id` and `user_data` (email hash). 3. Meta counts **one conversion**, not two. 4. If Pixel event arrived first, CAPI event is treated as a server-side confirmation (preferred because it has richer `user_data`). 5. If Pixel never arrived (browser privacy blocker), CAPI event counts as the primary conversion. ### Implementation Rule for Cedar & Coil For **non-Purchase events** (ViewContent, AddToCart, InitiateCheckout): - Send from **browser Pixel only** using JavaScript. - Use a client-side event ID generator (e.g., `uuid()`). - Do not duplicate from server-side (no value, wastes data). For **Purchase events**: - Send **event_id from browser Pixel** (if Pixel fires) to the server. - Pass that same `event_id` in the CAPI request. - If you cannot capture Pixel event_id, generate one server-side and ensure it's deterministic (e.g., hash of order ID + customer email). ### Code Example: Deterministic Event ID (Server-Side) If the browser Pixel fails to send the event_id to your server, generate it deterministically: ```javascript // On Shopify order webhook receipt (server-side, Node.js pseudocode) const crypto = require('crypto'); function generateEventId(orderId, customerEmail) { const raw = `${orderId}:${customerEmail}:purchase`; return crypto.createHash('sha256').update(raw).digest('hex').slice(0, 16); } const eventId = generateEventId('order_12345', 'customer@example.com'); // Result: deterministic, repeatable if webhook retries ``` --- ## 4. Customer Information Preparation: Hashing & PII Handling ### Why Hashing Is Mandatory Meta's Conversions API requires that personally identifiable information (PII) be hashed before transmission. Hashing: - Protects customer privacy (you never send plain email to Meta). - Allows Meta to match server-side conversions to browser impressions via their own user database without storing PII. - Is legally safer under GDPR and CCPA (you are not sharing identifiable data). ### Required Hashing Algorithm: SHA-256 All user_data fields must be hashed using **SHA-256**, then converted to **lowercase hexadecimal**. ### User Data Fields for Cedar & Coil | Field | Key | Shopify Source | Required? | Example | |-------|-----|-----------------|-----------|---------| | Email | `em` | `order.email` or `customer.email` | **Yes** | `john@example.com` → `9f9d51bc61e57992f2d852a0a...` | | Phone | `ph` | `order.billing_address.phone` or `customer.phone` | No | `+14155552671` → `hash` | | First Name | `fn` | `order.billing_address.first_name` | No | `John` → `hash` | | Last Name | `ln` | `order.billing_address.last_name` | No | `Doe` → `hash` | | City | `ct` | `order.billing_address.city` | No | `San Francisco` → `hash` | | State | `st` | `order.billing_address.province_code` (US) | No | `CA` → `hash` | | Zip | `zp` | `order.billing_address.zip` | No | `94103` → `hash` | | Country | `country` | `order.billing_address.country_code` | No | `US` → `hash` | | External ID | `external_id` | Shopify Customer ID (hashed) | No | Customer ID → `hash` | ### Hashing Transformation Rules 1. **Normalize before hashing**: - Trim whitespace: `" john@example.com "` → `"john@example.com"`. - Lowercase: `"John@Example.COM"` → `"john@example.com"` (especially important for email). - Remove special characters for phone: `"+1 (415) 555-2671"` → `"+14155552671"`. - For names, lowercase only: `"John"` → `"john"`. 2. **Hash using SHA-256**: ```javascript const crypto = require('crypto'); function hashPII(value) { if (!value) return null; // Skip empty fields const normalized = value.toString().trim().toLowerCase(); return crypto .createHash('sha256') .update(normalized) .digest('hex'); } const hashedEmail = hashPII('John@Example.COM'); // Result: '9f9d51bc61e57992f2d852a0a3b02f25e5a1efb8...' (64 hex chars) ``` 3. **Double-hash if needed** (rare): Some integrations ask for SHA-256 of a SHA-256. Check Meta's current API docs. Typically single hash is correct. ### Implementation Checklist: Shopify Order Webhook When Shopify fires an `orders/fulfilled` or `orders/create` webhook: ```javascript // Pseudocode: Node.js + Express const crypto = require('crypto'); app.post('/webhooks/shopify/order', (req, res) => { const order = req.body; // Extract customer data const customerEmail = order.email; const customerPhone = order.billing_address?.phone; const firstName = order.billing_address?.first_name; const lastName = order.billing_address?.last_name; const city = order.billing_address?.city; const state = order.billing_address?.province_code; const zip = order.billing_address?.zip; const country = order.billing_address?.country_code; const customerId = order.customer?.id; // Hash all fields const userData = { em: hashPII(customerEmail), ph: hashPII(customerPhone), fn: hashPII(firstName), ln: hashPII(lastName), ct: hashPII(city), st: hashPII(state), zp: hashPII(zip), country: hashPII(country), external_id: hashPII(customerId?.toString()) }; // Remove null entries Object.keys(userData).forEach(k => !userData[k] && delete userData[k]); // Send to Meta CAPI (see Section 5 for full request) sendToCAPI(order, userData); res.status(200).json({ received: true }); }); function hashPII(value) { if (!value) return null; const normalized = value.toString().trim().toLowerCase(); return crypto.createHash('sha256').update(normalized).digest('hex'); } ``` ### Privacy & Consent Notes - **GDPR**: Hashing does not exempt you from consent requirements. You must have consent before sending any PII (hashed or not) to a third party (Meta). See Section 7. - **CCPA**: Similarly, hashing is a safeguard, not a free pass. Document consent properly. - **Data Residency**: Shopify stores order data in the US. Ensure your webhook processor also handles data residency per your compliance obligations. --- ## 5. Shopify Setup Path: Native App vs. Custom Implementation ### Option A: Native Meta Sales Channel App (Shopify App Store) **What it is**: Official Shopify + Meta integration. Shopify automatically sends Pixel code and CAPI webhooks on your behalf. **Pros**: - Zero code required; enable in Shopify admin. - Shopify maintains deduplication logic. - Automatic updates if Meta/Shopify API changes. - No PII handling on your servers (Shopify does the hashing). **Cons**: - Limited customization (e.g., cannot add custom events or override event values). - Debugging is opaque (Shopify logs, not your own). - Dependency on Shopify's roadmap (if you want a feature, request it; no guarantee of priority). - Shopify takes a % of ad spend in some cases (verify current terms). **For Cedar & Coil**: **Not recommended at this stage.** - You need full control to test event tracking before scaling spend. - A small DTC brand should own its stack to iterate quickly. - Once you confirm conversion tracking works and campaigns perform, you can migrate to the native app later. --- ### Option B: Custom Implementation (Recommended for Cedar & Coil) **What it is**: You add Meta Pixel code to your Shopify theme and build a server-side webhook handler to send CAPI events. **Pros**: - Full control over event parameters and timing. - Easy to debug (you log and inspect your own requests). - Ability to implement custom events (e.g., "View Arc Clip Lamp Specs"). - No third-party dependency for core conversion tracking. - Cost: zero additional fees. **Cons**: - Requires technical implementation (or a developer). - You own PII hashing (security responsibility). - You maintain deduplication logic. **For Cedar & Coil**: **Recommended.** You are early-stage; custom implementation lets you validate the setup end-to-end, adjust parameters, and iterate faster than waiting for Shopify app updates. --- ### Implementation Path: Custom Setup #### Step 1: Add Meta Pixel to Shopify Theme In Shopify Admin > Settings > Customer events: 1. Go to **Settings > Customer events** (or **Customer events** in newer Shopify versions). 2. Add Pixel ID: `<your_meta_pixel_id>`. 3. Shopify will inject the Meta Pixel base code into every page. Alternatively, manually add to theme (Admin > Themes > Edit code): In `theme.liquid` (or `base.liquid`), add in the `<head>` section: ```html <!-- Meta Pixel --> <script> !function(f,b,e,v,n,t,s) {if(f.fbq)return;n=f.fbq=function(){n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments)}; if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0'; n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t,s)}(window, document,'script', 'https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '<your_meta_pixel_id>'); fbq('track', 'PageView'); </script> <!-- End Meta Pixel --> ``` #### Step 2: Track Pixel Events (Browser-Side) **ViewContent** (on product page): Add to `product.liquid`: ```javascript <script> fbq('track', 'ViewContent', { value: {{ product.selected_variant.price | money_without_currency }}, currency: 'USD', content_name: '{{ product.title }}', content_ids: ['{{ product.id }}'], content_type: 'product', contents: [ { id: '{{ product.id }}', quantity: 1, title: '{{ product.title }}', price: {{ product.selected_variant.price | money_without_currency }} } ] }, { eventID: '{{ 'now' | date: "%s" }}_{{ product.id }}_view_{{ cart.token }}' }); </script> ``` **AddToCart** (on add to cart button): Add to `product.liquid` or cart drawer: ```javascript <script> document.addEventListener('DOMContentLoaded', function() { const addToCartBtn = document.querySelector('[name="add"]'); // Adjust selector if (addToCartBtn) { addToCartBtn.addEventListener('click', function() { fbq('track', 'AddToCart', { value: {{ product.selected_variant.price | money_without_currency }}, currency: 'USD', content_ids: ['{{ product.id }}'], content_type: 'product' }, { eventID: '{{ 'now' | date: "%s" }}_{{ product.id }}_addtocart' }); }); } }); </script> ``` **InitiateCheckout** (on checkout button): Shopify theme typically has a checkout form in `cart.liquid`: ```javascript <script> document.addEventListener('DOMContentLoaded', function() { const checkoutBtn = document.querySelector('[name="checkout"]'); if (checkoutBtn) { checkoutBtn.addEventListener('click', function() { fbq('track', 'InitiateCheckout', { value: {{ cart.total_price | money_without_currency }}, currency: 'USD', content_ids: {{ cart | map: 'product_id' | json }}, num_items: {{ cart | size }} }, { eventID: '{{ 'now' | date: "%s" }}_{{ cart.token }}_checkout' }); }); } }); </script> ``` #### Step 3: Set Up Shopify Webhook for Server-Side CAPI Create a **private Shopify app** (or use a Public app if deploying on app marketplace): 1. In Shopify Admin > Settings > Apps and integrations > App and sales channel settings. 2. Create a custom app. 3. Set scopes: `read_orders`, `write_orders` (minimal; you only need to receive webhook data). 4. Note the API key and API secret. Register webhook endpoint: Use Shopify CLI or GraphQL to subscribe to `orders/fulfilled` or `orders/create`: ```bash shopify app function create --template order_discount # Or use GraphQL mutation: ``` GraphQL (via Shopify Admin API): ```graphql mutation { webhookSubscriptionCreate( topic: ORDERS_FULFILLED webhookSubscription: { format: JSON callbackUrl: "https://your-server.com/webhooks/shopify/order" } ) { webhookSubscription { id topic callbackUrl } userErrors { field message } } } ``` Or use Shopify CLI: ```bash shopify webhook trigger orders/fulfilled --address https://your-server.com/webhooks/shopify/order ``` #### Step 4: Build Webhook Handler to Send CAPI **Technology Stack** (example: Node.js + Express): ```javascript // webhooks/shopify.js const express = require('express'); const crypto = require('crypto'); const axios = require('axios'); const router = express.Router(); const META_PIXEL_ID = process.env.META_PIXEL_ID; const META_ACCESS_TOKEN = process.env.META_ACCESS_TOKEN; const WEBHOOK_SECRET = process.env.SHOPIFY_WEBHOOK_SECRET; // Middleware to verify Shopify webhook signature function verifyShopifyWebhook(req, res, next) { const hmac = req.headers['x-shopify-hmac-sha256']; const body = req.rawBody; // Store raw body before JSON parsing const hash = crypto .createHmac('sha256', WEBHOOK_SECRET) .update(body, 'utf8') .digest('base64'); if (hash === hmac) { next(); } else { res.status(401).json({ error: 'Webhook verification failed' }); } } router.post('/order', verifyShopifyWebhook, async (req, res) => { try { const order = req.body; // Extract order details const orderId = order.id; const orderNumber = order.order_number; const email = order.email; const totalPrice = parseFloat(order.total_price); const currency = order.currency; const createdAt = order.created_at; // Extract customer details const billingAddress = order.billing_address || {}; const phone = billingAddress.phone || order.phone; const firstName = billingAddress.first_name || order.customer?.first_name; const lastName = billingAddress.last_name || order.customer?.last_name; const city = billingAddress.city; const state = billingAddress.province_code; const zip = billingAddress.zip; const country = billingAddress.country_code; const customerId = order.customer?.id; // Extract line items for content_ids const contentIds = order.line_items.map(item => item.product_id.toString()); const contents = order.line_items.map(item => ({ id: item.product_id.toString(), quantity: item.quantity, title: item.title, price: parseFloat(item.price) })); // Hash PII const userData = { em: hashPII(email), ph: hashPII(phone), fn: hashPII(firstName), ln: hashPII(lastName), ct: hashPII(city), st: hashPII(state), zp: hashPII(zip), country: hashPII(country), external_id: hashPII(customerId?.toString()) }; // Remove null entries Object.keys(userData).forEach(k => !userData[k] && delete userData[k]); // Build CAPI payload const capiPayload = { data: [ { event_name: 'Purchase', event_id: `${orderId}_purchase`, event_time: Math.floor(new Date(createdAt).getTime() / 1000), user_data: userData, custom_data: { value: totalPrice, currency: currency, content_name: 'Arc Clip Lamp', content_type: 'product', content_ids: contentIds, num_items: order.line_items.length, contents: contents }, data_processing_options: ['LDU'], data_processing_options_country: 1, data_processing_options_state: 1000 } ] }; // Send to Meta CAPI const response = await axios.post( `https://graph.facebook.com/v18.0/${META_PIXEL_ID}/events`, capiPayload, { params: { access_token: META_ACCESS_TOKEN } } ); console.log('CAPI event sent successfully:', response.data); // Respond to Shopify immediately (fire and forget) res.status(200).json({ success: true, meta_response: response.data }); } catch (error) { console.error('Error sending CAPI event:', error.message); // Still respond 200 to Shopify to prevent retries (log for later investigation) res.status(200).json({ success: false, error: error.message }); } }); function hashPII(value) { if (!value) return null; const normalized = value.toString().trim().toLowerCase(); return crypto.createHash('sha256').update(normalized).digest('hex'); } module.exports = router; ``` **Environment Variables** (`.env`): ``` META_PIXEL_ID=<your_pixel_id> META_ACCESS_TOKEN=<your_system_user_token> SHOPIFY_WEBHOOK_SECRET=<shared_secret_from_webhook_registration> ``` **Server Setup** (`app.js`): ```javascript const express = require('express'); const bodyParser = require('body-parser'); const webhookRoutes = require('./webhooks/shopify'); const app = express(); // Middleware: store raw body for webhook verification app.use((req, res, next) => { let data = ''; req.setEncoding('utf8'); req.on('data', chunk => { data += chunk; }); req.on('end', () => { req.rawBody = data; next(); }); }); app.use(express.json()); app.use('/webhooks/shopify', webhookRoutes); app.listen(process.env.PORT || 3000, () => { console.log('Webhook server running on port 3000'); }); ``` --- ### Summary: Custom vs. Native | Aspect | Native Meta App | Custom Implementation | |--------|-----------------|----------------------| | Setup Time | 5 min (enable in Shopify) | 2–4 hours (code + deploy) | | Control | Limited | Full | | PII Handling | Shopify (safe) | You (requires care) | | Debugging | Opaque logs | Your own logs | | Customization | None | Unlimited | | Cost | Possible fees | $0 | | **Recommendation for Cedar & Coil** | ❌ Not now | ✅ **Yes, recommended** | --- ## 6. End-to-End Validation Before Scaling Spend ### Validation Checklist #### Phase 1: Setup Verification (Day 1–2) - [ ] **Pixel fires on product page** - Open Arc Clip Lamp product page in Chrome DevTools (Network tab). - Look for request to `https://graph.facebook.com/...` with `event=Purchase` (or ViewContent). - Should see response code 200. - Alternative: Use Meta's Pixel Helper browser extension (search "Meta Pixel Helper" in Chrome Web Store). Should show pixel events in real time. - [ ] **CAPI endpoint receives webhook** - Create a test order in Shopify (use a test account or place a real order). - Check your server logs for incoming webhook POST request. - Verify Shopify's HMAC signature validates. - [ ] **CAPI event reaches Meta** - Check server logs for successful response from `graph.facebook.com`. - Response should include `"events_received": 1`. - If errors, note the error code (e.g., "Requires server-side event data for optimization"). #### Phase 2: Event Quality (Day 2–3) - [ ] **Parameters are correct** - CAPI payload includes `value` (order total), `currency` ("USD"), and `content_ids` (product IDs). - Hashed email field (`em`) is present and valid SHA-256 (64 hex characters). - Test with `hashPII("test@example.com")` locally; should be consistent. - [ ] **Deduplication works** - Place a test order. - Check Meta Events Manager (facebook.com/events) > **Conversions** tab. - Should see **1 conversion**, not 2 (one from Pixel, deduplicated by CAPI). - If you see 2, debug the `event_id` matching. - [ ] **User data is hashed** - Inspect CAPI payload in server logs. - Confirm no plain-text email or phone is sent to Meta (should be hashed hexadecimal only). - Never log or inspect hashed values; they are Meta's bridge to their user matching. #### Phase 3: Campaign Linkage (Day 3–4) - [ ] **Conversions attributed to Meta ads** - Run a small test campaign ($5–10 budget, targeted to your own location/interests). - Place an order as a test customer (or friend). - Wait 24 hours for Meta to process. - In Meta Ads Manager > **Campaigns** > Campaign name > **Results** should show 1 conversion. - If 0, check: - Is the Pixel tracking the same user who clicked the ad (same browser/device)? - Did the order complete within the attribution window (28 days default)? #### Phase 4: Scale Validation (Week 1–2) - [ ] **Monitor conversion quality** - Run a small budget campaign ($20–50/day). - Daily check Events Manager > Conversions. - Ensure CAPI events continue to arrive (watch for webhook errors). - Look for anomalies: sudden drop in events, or events with missing `value` or `content_ids`. - [ ] **Monitor for errors** - Set up alerts on your webhook handler for errors (e.g., hashing failure, Meta API timeout). - Review Shopify's webhook logs (Admin > Settings > Apps and integrations > Webhooks) for failures. - [ ] **Test user journeys** - Have a team member or friend click an ad, browse the product, add to cart, and complete checkout. - Verify all events (ViewContent → AddToCart → InitiateCheckout → Purchase) appear in Events Manager. - Confirm no duplicates. ### Validation Test Checklist Template ```markdown ## Cedar & Coil Meta CAPI Validation **Date**: [date] **Tester**: [name] ### Setup - [ ] Meta Pixel ID: `[pixel_id]` - [ ] Access Token: `[token_created_date]` - [ ] Shopify Webhook: `[URL]` - [ ] Server: `[host]` ### Phase 1: Setup Verification - [ ] Pixel fires on product page (Network tab or Pixel Helper) - [ ] Webhook receives POST (server log) - [ ] Webhook signature valid (HMAC verified) - [ ] CAPI request succeeds (200 response from graph.facebook.com) - [ ] Meta response includes "events_received": 1 ### Phase 2: Event Quality - [ ] CAPI payload includes value, currency, content_ids - [ ] Hashed email is SHA-256 (64 hex chars) - [ ] No plain-text PII in logs - [ ] Events Manager shows 1 conversion (deduplicated) ### Phase 3: Campaign Linkage - [ ] Test campaign created ($5 budget) - [ ] Test order placed / completed - [ ] Conversion appears in Ads Manager after 24h - [ ] Attribution: [Yes / No / Investigating] ### Phase 4: Scale Readiness - [ ] Webhook stable for 7 days (0 errors) - [ ] No duplicate conversions - [ ] User journey tested (all events fired in sequence) - [ ] Ready to increase budget: [Yes / No] ### Notes [Any issues found and resolutions] ``` --- ## 7. Consent & Compliance Notes ### GDPR (EU / UK) **Requirement**: You must obtain explicit, informed consent before sending customer data (hashed or not) to Meta. **Implementation for Cedar & Coil**: 1. **On checkout page**, display a consent banner: > "We use Meta to measure ad effectiveness. Your email (encrypted) helps us understand which ads work. You can opt out in account settings. [Learn more](#privacy-policy)" 2. **Offer an opt-out**: Provide a preference center where customers can disable Meta tracking. 3. **Document consent**: Store the consent choice (yes/no) with the order. On webhook, before sending CAPI: ```javascript if (!order.customer.meta_consent) { // Skip CAPI event; do not send user_data console.log('Order skipped: no Meta consent'); return; } ``` 4. **Privacy Policy**: Link to your privacy policy from the consent banner. State: - You send hashed email to Meta for conversion tracking. - Data is not sold or shared beyond Meta. - Retention: [your policy, e.g., 90 days]. ### CCPA (California) **Requirement**: Similar to GDPR. You must disclose data sharing and provide a "Do Not Sell My Personal Information" option. **Implementation for Cedar & Coil**: 1. **Disclosure**: In your privacy policy, list "Meta Conversions API" under "Categories of third parties" that receive personal information. 2. **Opt-out link**: Provide a "Do Not Sell" link. If a user opts out, respect it: ```javascript if (order.customer.do_not_sell === true) { // Skip CAPI return; } ``` 3. **Data Processing Options**: In your CAPI payload, include (if user is in California or you apply universally): ```json { "data_processing_options": ["LDU"], "data_processing_options_country": 1, "data_processing_options_state": 1000 } ``` This tells Meta to apply limited data use (LDU), honoring CCPA-like opt-outs. ### Canada (PIPEDA) **Requirement**: Similar to GDPR, but less granular. Consent and transparency required. **Implementation**: Use the same consent banner and privacy policy disclosure as GDPR. ### Data Retention **Best practice for Cedar & Coil**: - **Hashed PII**: Do not retain beyond 90 days. After 90 days, delete hashed email from your logs. - **Webhook logs**: Retain for 30 days for debugging, then delete. - **Order data**: Retain per legal obligation (typically 7 years for tax/refund), but do not re-send to Meta after 90 days. **Implementation**: ```javascript // Pseudocode: weekly cleanup job const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); await WebhookLog.deleteMany({ createdAt: { $lt: thirtyDaysAgo } }); ``` ### Data Security **Cedar & Coil must**: - Use **HTTPS** for all webhook endpoints (non-negotiable). - Store the Meta access token in a secure environment variable (never in version control). - Verify the Shopify webhook signature (HMAC) before processing. - Encrypt the access token at rest if stored in a database. - Use a secrets manager (e.g., AWS Secrets Manager, HashiCorp Vault) in production. ### Transparent Communication with Customers **Example footer text for Cedar & Coil emails or website**: > Cedar & Coil uses Meta Ads to reach customers interested in practical lighting. When you complete an order, we send your hashed email to Meta to measure whether ads work. This helps us improve our marketing. Your data is encrypted and not sold. [Learn more about your privacy.](#privacy-policy) --- ## Appendix: Quick Reference ### Event Parameters Cheat Sheet | Event | Pixel? | CAPI? | Required Fields | Example Value | |-------|--------|-------|-----------------|----------------| | **ViewContent** | ✅ | ❌ | content_ids, value, currency | `["arc-clip-lamp-001"]`, `68.00`, `"USD"` | | **AddToCart** | ✅ | ❌ | content_ids, value, currency | `["arc-clip-lamp-001"]`, `68.00`, `"USD"` | | **InitiateCheckout** | ✅ | ❌ | content_ids, value, currency, num_items | `["arc-clip-lamp-001"]`, `68.00`, `"USD"`, `1` | | **Purchase** | ❌ | ✅ | content_ids, value, currency, user_data (em) | `["arc-clip-lamp-001"]`, `68.00`, `"USD"`, `{em: "sha256hash..."}` | ### Troubleshooting Reference | Problem | Cause | Fix | |---------|-------|-----| | Pixel not firing | JS error or ad blocker | Check DevTools Console; disable blockers | | CAPI not firing | Webhook not registered or failing signature verification | Verify webhook URL is accessible; check HMAC | | Events are duplicated (2 instead of 1) | event_id mismatch between Pixel and CAPI | Ensure both use same event_id | | Conversions not attributed to ads | Conversion happened outside 28-day attribution window | Check order date vs. ad click date | | "Requires server-side event data" error | user_data not included in CAPI | Add hashed email (`em`) to CAPI payload | | Hashed email doesn't match | Different normalization before hashing | Always trim, lowercase, normalize before hashing | ### Deployment Checklist - [ ] Environment variables configured (META_PIXEL_ID, META_ACCESS_TOKEN, WEBHOOK_SECRET) - [ ] HTTPS enabled on webhook endpoint - [ ] Shopify webhook registered and tested - [ ] Webhook signature verification implemented - [ ] Hashing function tested (consistent results) - [ ] CAPI payload schema validated - [ ] Error logging configured - [ ] Server rate limits set (avoid throttling by Meta) - [ ] Consent logic implemented (GDPR/CCPA) - [ ] Privacy policy updated - [ ] Data retention cleanup job scheduled - [ ] Test order placed and verified in Events Manager --- ## Conclusion Cedar & Coil is now equipped to build resilient conversion tracking across browser privacy restrictions. By layering browser Pixel with server-side CAPI and deduplicating intelligently, you maximize the chances that Meta can credit your Arc Clip Lamp sales to your campaigns, regardless of which privacy tools your customers use. **Start with the custom implementation** (Section 5, Option B) to validate your setup end-to-end before scaling spend. Once you confirm conversions are tracking reliably, you can optimize campaign parameters, refine targeting, and grow with confidence. Remember: **no implementation can recover 100% of conversions lost to privacy tools.** Your job is to recover *most* through thoughtful architecture and first-party data. Good luck.
Score the judge's verdict, criterion by criterion9/11 criteria passed · failed: code_sketch, validation
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 privacy fragmentation, iOS 14.5+ ATT limits, and attribution resilience as reasons 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 covers ViewContent, AddToCart, InitiateCheckout, and Purchase, each with value, currency, and content_ids (Purchase explicitly includes content_ids array).
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 Purchase CAPI payload (Section 2 and the full webhook handler in Section 5) includes event_name, event_id, event_time, and user_data but never includes an 'action_source' field anywhere in the response.
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.
✗Validation steps reference 'Meta Events Manager (facebook.com/events) > Conversions tab' and Pixel Helper, but never name or describe Meta's specific Events Manager 'Test Events' tool, even though a duplicate-check step ('Should see 1 conversion, not 2') is present.
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 2 states Purchase is 'Fired: Server-side via Conversions API only (after Shopify order webhook fires)', explicitly establishing the webhook as the source of truth rather than a thank-you page, while ViewContent/AddToCart/InitiateCheckout are marked browser-only.
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 conclusion states 'no implementation can recover 100% of conversions lost to privacy tools' without citing a percentage, and Section 7 details GDPR/CCPA consent requirements as constraints on what data 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 shows the same event_id ('order_12345_pixel') sent from both fbq('track','Purchase',...) and the CAPI JSON payload, explaining Meta matches by event_id to count one conversion.
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 webhook handler generates event_id as `${orderId}_purchase`, a deterministic value tied to the order ID that would remain stable across retries, and Section 3 explicitly notes the deterministic hash approach is 'repeatable if 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 server code computes event_time as `Math.floor(new Date(createdAt).getTime() / 1000)` using the order's created_at timestamp rather than the current send time.
pii_hashing
Customer data handling is correct: personally identifiable fields (e.g. email) are normalized (trimmed, lowercased) and SHA-256 hashed before sending in user_data.
✓The hashPII function trims, lowercases, and applies SHA-256 to normalize PII before inclusion in user_data, as shown in Sections 4 and 5.
actionable_path
The recommended Shopify path is decisive and executable for a small DTC store (a clear recommendation with concrete setup steps, not an undifferentiated list of options).
✓Section 5 explicitly recommends 'Option B: Custom Implementation (Recommended for Cedar & Coil)' over the native app and lays out four concrete numbered setup steps with code.