# Cedar & Coil: Meta Pixel + Conversions API Implementation Guide
**Store:** Shopify · **Product:** Arc Clip Lamp ($68) · **Status:** Pre-launch. No campaign has run and no performance data exists.
**Audience:** The technical marketer setting up tracking before any Meta spend.
> **Scope note.** This guide covers how to get conversion signals into Meta accurately and with deduplication. It does not predict how much attribution you will "recover." That depends on your traffic mix, consent rates, browsers, and Meta's own modeling, and none of those can be known before launch. Meta's interfaces and API versions change, so confirm field names and screen paths against current Meta and Shopify documentation as you go.
---
## 1. Recommended Architecture: Browser Pixel + Conversions API, Deduplicated
### The setup
```
Shopper's browser Your server / Shopify
───────────────── ─────────────────────
Meta Pixel (fbq) Conversions API (CAPI)
ViewContent ── eventID: abc ─┐ ┌── event_id: abc ── ViewContent
AddToCart ── eventID: def ─┤ ├── event_id: def ── AddToCart
InitiateCheckout ─ eventID: ghi┤ ├── event_id: ghi ── InitiateCheckout
Purchase ── eventID: purchase_123 purchase_123 ───── Purchase
▼ ▼
Meta Events Manager
(matches event_name + event_id → keeps one)
```
Every key event is sent twice, once from the browser and once from the server. Both copies carry the same `event_name` and the same event ID, and Meta keeps one.
### Why the browser Pixel alone is not enough
These are documented behaviors of the browser environment:
- **Ad blockers and privacy extensions** can block requests to Meta's domains, so the Pixel never fires.
- **Browser tracking protections** (Safari ITP, Firefox ETP) shorten or restrict cookie lifetimes. That can break the link between an ad click and a later purchase.
- **Network and page issues** such as a shopper closing the tab or a slow mobile connection can stop the Pixel request from completing.
- **Shopify checkout runs in a sandboxed environment.** Checkout and thank-you page tracking must go through Shopify's Customer Events (Web Pixels). Legacy theme code no longer works there.
### Why CAPI alone is not enough
- **Matching signals live in the browser.** The `_fbp` browser ID, the `_fbc` click ID (from `fbclid`), the user agent, and the event source URL all originate in the browser. A server-only setup has to capture and pass these deliberately, or match quality suffers.
- **Some browsing events never reach your server.** ViewContent and AddToCart happen in the browser. Sending them server-side means building a relay.
- **Meta designs and recommends the two to run together.** Redundancy lets you compare the two sources and spot breakage on either side.
**Bottom line:** the Pixel provides rich browser context. CAPI provides a delivery path that browser restrictions don't block. Deduplication keeps you from paying for both.
---
## 2. Standard Events and Parameters
### Tracking plan
| Event | Trigger | Required / key parameters | Notes |
|---|---|---|---|
| `ViewContent` | Arc Clip Lamp product page view | `content_ids`, `content_type`, `value`, `currency` | `value` = 68.00 for one unit. Optional: `content_name: "Arc Clip Lamp"`. |
| `AddToCart` | Successful add-to-cart (not just a button click) | `content_ids`, `content_type`, `contents` (`id`, `quantity`), `value`, `currency` | `value` = unit price × quantity added. |
| `InitiateCheckout` | Checkout starts (Shopify `checkout_started`) | `content_ids`, `contents`, `num_items`, `value`, `currency` | `value` = cart value at checkout start. |
| `Purchase` | Order completed (Shopify `checkout_completed` / order webhook) | **`value`** (required), **`currency`** (required), **`content_ids`**, `content_type`, `contents`, `num_items`, `order_id` | Most important event. Also gets the strictest dedup and validation. |
### Parameter rules
- **`value`** is a number, not a string with a `$`. Pick one revenue definition and use it in both browser and server events. A common choice is merchandise subtotal after discounts, excluding shipping and tax. Write the definition down here: `________`.
- **`currency`** is an ISO 4217 code. This guide assumes `USD` because the price is listed as $68. Confirm the store's currency settings, and if you sell in multiple currencies, send the currency the order was actually charged in.
- **`content_ids`** is an array of strings. They **must exactly match the `id` field in the Meta product catalog** connected to your ad account. The native Shopify app generates catalog IDs in its own format, so take the IDs from the catalog rather than assuming the raw Shopify product ID.
- **`content_type`** is `"product"` when the IDs are variant- or item-level catalog IDs. Use `"product_group"` only when you are sending item-group IDs.
- **`contents`** is an array of objects like `[{ "id": "<catalog id>", "quantity": 1 }]`.
### Example Purchase payload (browser)
```javascript
fbq('track', 'Purchase', {
value: 68.00,
currency: 'USD',
content_ids: ['<catalog_id_for_arc_clip_lamp>'],
content_type: 'product',
contents: [{ id: '<catalog_id_for_arc_clip_lamp>', quantity: 1 }],
num_items: 1
}, { eventID: 'purchase_<shopify_order_id>' });
```
**Track only what informs a decision.** These four events map directly to the funnel you'll optimize and diagnose: product interest, cart intent, checkout start, and sale. Avoid adding custom events until a specific question requires one.
---
## 3. How Deduplication Works
### The matching rule
Meta treats a browser event and a server event as duplicates when both of these match:
1. **`event_name`**, for example both are exactly `Purchase`. Event names are case-sensitive.
2. **The event ID.** It is `eventID` in the Pixel's fourth argument and `event_id` in the CAPI payload, and both must be the identical string.
Meta then keeps one event and discards the other. Its documentation describes a time window for this matching, which has been stated as 48 hours. Confirm the current window and still send both copies as close in time as possible.
A secondary method also exists, matching on `fbp` or `external_id` plus `event_name`. It is less reliable, so don't depend on it. **Always send an explicit event ID.**
### Generating event IDs
| Event | ID strategy | Why |
|---|---|---|
| `Purchase` | Deterministic: `purchase_<shopify_order_id>` | Browser and server can derive the same ID independently. A webhook retry or a thank-you page reload produces the same ID, so it dedups instead of double-counting. |
| `ViewContent`, `AddToCart`, `InitiateCheckout` | Random UUID generated in the browser, then passed to the server | The server has no natural shared key for these. The browser must hand its ID to whatever sends the server copy. |
### Common dedup failures
| Failure | Result |
|---|---|
| Browser sends `eventID`, server omits `event_id` | Both counted, so conversions are inflated |
| IDs differ in format, e.g. a GID string vs. a numeric order ID | Both counted |
| `Purchase` vs. `purchase` | Treated as different events |
| Pixel installed twice (native app plus a leftover theme snippet) | Duplicate browser events with different or no IDs |
| Server event sent days later (batch job) | May fall outside the dedup window |
On Shopify, the order ID can surface in different formats on the browser and server sides: a numeric ID in one place, a `gid://shopify/...` string in another. Normalize both to the numeric ID, and log both values during validation to confirm they match.
---
## 4. Preparing Customer Information for Server-Side Sending
CAPI matches events to Meta accounts using `user_data`. Most identifiers must be **normalized, then SHA-256 hashed** before sending. Some must **not** be hashed.
### Hash these (normalize first, then SHA-256, hex-encoded)
| Field | Key | Normalization before hashing |
|---|---|---|
| Email | `em` | Trim whitespace, lowercase |
| Phone | `ph` | Digits only, **include country code**, no `+`, spaces, dashes, or leading zeros (e.g. `15551234567`) |
| First name | `fn` | Lowercase, remove punctuation, UTF-8 for accented characters |
| Last name | `ln` | Same as first name |
| City | `ct` | Lowercase, remove spaces and punctuation (e.g. `sanfrancisco`) |
| State | `st` | Lowercase 2-letter code for US (e.g. `ca`) |
| Zip | `zp` | US: first 5 digits, lowercase, no spaces |
| Country | `country` | Lowercase ISO 3166-1 alpha-2 (e.g. `us`) |
| External ID | `external_id` | Your stable customer ID. Hashing is recommended. Use the same value in browser and server events. |
### Do NOT hash these
| Field | Key | Source on Shopify |
|---|---|---|
| Client IP address | `client_ip_address` | Order `client_details.browser_ip` / `browser_ip` |
| User agent | `client_user_agent` | Order `client_details.user_agent` (**required** for `action_source: "website"`) |
| Click ID | `fbc` | `_fbc` cookie, or build `fb.1.<ms_timestamp>.<fbclid>` from the landing URL |
| Browser ID | `fbp` | `_fbp` cookie |
### Rules
- **Never send plaintext PII.** Hash on your server before the request leaves it.
- **Omit empty fields.** Don't hash an empty string, because that produces a valid-looking but meaningless hash.
- **Don't guess a country code.** If a phone number lacks one and you can't determine it reliably from the order's country, omit `ph`.
- **Send only what you collect legitimately and need for matching.** Never put PII in `custom_data` or event names.
- **Use Event Match Quality as a guide.** Events Manager shows an Event Match Quality score per event. Low scores tell you which identifiers are missing. They do not tell you how many conversions you're losing.
---
## 5. Shopify Setup Path
### Option A: Native Meta sales channel (the "Facebook & Instagram" app)
**How it works:** You install the app, connect your Business portfolio, ad account, Pixel, and catalog, then choose a **customer data-sharing level**. The maximum level turns on server-side events via CAPI alongside the Pixel. Shopify generates event IDs and handles deduplication, and its consent handling integrates with Shopify's Customer Privacy settings.
| Pros | Cons |
|---|---|
| No code; can be done in an afternoon | Less control over the exact `value` definition and parameter mapping |
| Dedup, hashing, and checkout events handled by Shopify | Harder to inspect exactly what is sent; you rely on Events Manager diagnostics |
| Catalog sync keeps `content_ids` consistent with the catalog automatically | Custom events or enrichment (e.g. margin-based value) not supported |
| Maintained as Shopify and Meta APIs change | Behavior can change with app updates outside your control |
### Option B: Custom implementation
**How it works:**
- **Browser side:** a custom pixel in **Settings → Customer events** using Shopify's Web Pixels API. It subscribes to `product_viewed`, `product_added_to_cart`, `checkout_started`, and `checkout_completed`.
- **Server side:** a small service that receives Shopify **order webhooks** (`orders/paid` or `orders/create`) and sends CAPI events.
- **Funnel events server-side:** for ViewContent, AddToCart, and InitiateCheckout, you also need a relay endpoint that receives the browser's event ID and context.
| Pros | Cons |
|---|---|
| Full control over value, IDs, parameters, and consent logic | Requires a developer, hosting, secrets management, and monitoring |
| Easy to add enrichment later | You own dedup correctness, hashing, retries, and API version upgrades |
| Payloads are fully inspectable and loggable | Must capture `_fbp`, `_fbc`, and consent into the order yourself, e.g. via cart attributes |
| | A silent failure, like an expired token, can go unnoticed without alerting |
### Recommendation for Cedar & Coil: start with the native app
**The decision is driven by Cedar & Coil's situation:**
- **One product, no existing data.** Cedar & Coil is a small DTC brand selling one $68 product, with no campaign history.
- **The goal is reliable tracking before the first dollar of spend.** You need trustworthy Purchase data quickly, not a custom data pipeline.
- **The native app covers the requirement.** It delivers Pixel + CAPI with deduplication and catalog-consistent `content_ids`, with the fewest moving parts that can break.
**What you trade away:** control over the revenue definition, custom enrichment, and payload-level visibility.
**Revisit a custom build if any of these become true:**
- You need value-based optimization on something other than order revenue.
- Validation (Section 6) shows a defect in the app's events that you can't fix through its settings.
- Consent requirements in your selling regions need logic the app doesn't support.
### Native app setup steps
1. **Remove legacy Pixel code first.** Search `theme.liquid` and theme snippets for `fbq(` or `connect.facebook.net`. Also check for any old Pixel in checkout "Additional scripts" or existing Customer Events custom pixels, and remove or disable them. *This is the most common source of duplicate events.*
2. **Install** the Facebook & Instagram sales channel from the Shopify App Store.
3. **Connect assets:** Business portfolio, ad account, Pixel (create one or select the existing one), Facebook Page, and catalog.
4. **Set data sharing to the maximum level,** which enables Conversions API. Review the consent behavior the app describes before confirming.
5. **Verify your domain** in Meta Business settings (Brand safety → Domains).
6. **Confirm catalog sync.** The Arc Clip Lamp should appear in the Meta catalog, and its catalog ID is what `content_ids` should carry.
7. **Configure Shopify's customer privacy and consent banner** for the regions you sell to (see Section 7).
8. **Proceed to validation** (Section 6) before launching ads.
### Code sketch: server-side Purchase event (custom path, for reference)
This sketch shows the server half of Option B, or a future migration. It assumes:
- A Shopify `orders/paid` webhook.
- A theme or custom-pixel script that writes `_fbp`, `_fbc`, and the shopper's marketing-consent status into **cart attributes**. Shopify copies these onto the order as `note_attributes`.
- A browser custom pixel that fires `Purchase` with `eventID: 'purchase_<numeric order id>'`.
```javascript
// Node 18+ (global fetch). Sketch only — add logging, retries, alerting, secret rotation.
import crypto from 'node:crypto';
import express from 'express';
const {
META_PIXEL_ID,
META_CAPI_TOKEN, // System User access token; store in a secret manager
META_GRAPH_VERSION, // pin to a current version, e.g. 'vXX.0'
SHOPIFY_WEBHOOK_SECRET,
META_TEST_EVENT_CODE // set ONLY during validation; unset in production
} = process.env;
const app = express();
// ---------- normalization + hashing ----------
const sha256 = (v) => crypto.createHash('sha256').update(v, 'utf8').digest('hex');
const lower = (v) => (v ?? '').toString().trim().toLowerCase();
const hashed = (v) => (v ? [sha256(v)] : undefined); // never hash empty strings
const normEmail = (e) => lower(e);
const normName = (n) => lower(n).replace(/[^\p{L}]/gu, ''); // letters only
const normCity = (c) => lower(c).replace(/[^\p{L}]/gu, '');
const normState = (s) => lower(s); // 'CA' -> 'ca'
const normZip = (z, country) =>
lower(country) === 'us' ? lower(z).replace(/\s/g, '').slice(0, 5) : lower(z).replace(/\s/g, '');
const normCountry = (c) => lower(c); // 'US' -> 'us'
const normPhone = (p) => {
if (!p) return '';
const raw = p.toString().trim();
if (!raw.startsWith('+')) return ''; // don't guess a country code; omit instead
return raw.replace(/\D/g, '').replace(/^0+/, '');
};
const attr = (order, name) =>
(order.note_attributes || []).find((a) => a.name === name)?.value;
// ---------- webhook authenticity ----------
function verifyShopifyHmac(rawBody, hmacHeader) {
const digest = crypto.createHmac('sha256', SHOPIFY_WEBHOOK_SECRET).update(rawBody).digest('base64');
const a = Buffer.from(digest);
const b = Buffer.from(hmacHeader || '');
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
// ---------- catalog ID mapping ----------
// MUST return the exact `id` used in the Meta catalog for this item.
function catalogIdFor(lineItem) {
return String(lineItem.variant_id); // placeholder — replace with your catalog's ID format
}
app.post('/webhooks/orders-paid', express.raw({ type: 'application/json' }), async (req, res) => {
if (!verifyShopifyHmac(req.body, req.get('X-Shopify-Hmac-Sha256'))) return res.sendStatus(401);
res.sendStatus(200); // ack fast; process after (or enqueue)
const order = JSON.parse(req.body.toString('utf8'));
// Consent gate: only send if the shopper granted marketing consent (captured at browse/checkout).
if (attr(order, '_marketing_consent') !== 'granted') return;
const addr = order.billing_address || order.shipping_address || {};
const country = addr.country_code;
const lineItems = order.line_items || [];
const contents = lineItems.map((li) => ({ id: catalogIdFor(li), quantity: li.quantity }));
const event = {
event_name: 'Purchase',
event_time: Math.floor(new Date(order.processed_at || order.created_at).getTime() / 1000),
event_id: `purchase_${order.id}`, // identical string to the browser eventID
action_source: 'website',
event_source_url: order.order_status_url, // or the thank-you page URL you capture
user_data: {
em: hashed(normEmail(order.email)),
ph: hashed(normPhone(order.phone || addr.phone)),
fn: hashed(normName(addr.first_name)),
ln: hashed(normName(addr.last_name)),
ct: hashed(normCity(addr.city)),
st: hashed(normState(addr.province_code)),
zp: hashed(normZip(addr.zip, country)),
country: hashed(normCountry(country)),
external_id: order.customer?.id ? hashed(String(order.customer.id)) : undefined,
// NOT hashed:
client_ip_address: order.client_details?.browser_ip || order.browser_ip,
client_user_agent: order.client_details?.user_agent,
fbp: attr(order, '_fbp'),
fbc: attr(order, '_fbc')
},
custom_data: {
currency: order.currency, // e.g. 'USD'
value: Number(order.current_subtotal_price), // match your documented value definition
content_ids: contents.map((c) => c.id),
content_type: 'product',
contents,
num_items: lineItems.reduce((n, li) => n + li.quantity, 0),
order_id: String(order.id)
}
};
// Drop undefined keys so Meta doesn't receive empty fields.
event.user_data = Object.fromEntries(Object.entries(event.user_data).filter(([, v]) => v));
const body = { data: [event] };
if (META_TEST_EVENT_CODE) body.test_event_code = META_TEST_EVENT_CODE;
const url = `https://graph.facebook.com/${META_GRAPH_VERSION}/${META_PIXEL_ID}/events?access_token=${META_CAPI_TOKEN}`;
const resp = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
const result = await resp.json();
// Log result.events_received and result.fbtrace_id. On failure, retry with the SAME event_id
// (safe: duplicates dedup). Alert on repeated failures (e.g. expired token).
console.log(JSON.stringify({ order: order.id, status: resp.status, result }));
});
app.listen(3000);
```
**Things the sketch shows but you must confirm:**
- `catalogIdFor()` must match your catalog's actual ID format.
- The browser and server `value` definitions must match.
- The browser order ID must resolve to the same numeric `order.id`.
- `event_time` must be recent. Meta rejects events older than its limit (documented as 7 days), so don't batch Purchase sends.
---
## 6. End-to-End Validation Before Scaling Spend
Treat this as a pass/fail matrix. **An event is "clean" only when it passes every row.** Anything "fine, but…" goes on the findings list with its location and the standard it breaks.
### Step 1: Browser-side check
- [ ] Install **Meta Pixel Helper** (Chrome extension). Walk the funnel: product page → add to cart → checkout → (test) purchase.
- [ ] Each event fires **once** per action. No duplicate Pixel IDs and no second Pixel.
- [ ] Each event shows an event ID.
- [ ] Parameters populate: `value` is numeric, `currency` is correct, and `content_ids` matches the catalog ID.
- [ ] Checkout and purchase events fire inside Shopify's checkout. Use Events Manager's Test Events (Step 2) for this, because the Helper may not see the sandboxed checkout pixels.
### Step 2: Test Events in Events Manager
- [ ] Open **Events Manager → your Pixel → Test events**. Use the browser test option, and for a custom build set `test_event_code` on server requests.
- [ ] Place a **real test order.** Use Shopify's test/Bogus gateway, or a real order you refund. Note the order ID.
- [ ] For each of the four events, confirm **both** a Browser and a Server event appear.
- [ ] Confirm the two copies show as **deduplicated**, with matching event name and event ID.
- [ ] For Purchase: `value` equals the order's value under your documented definition, `currency` is correct, `content_ids` matches the catalog, and `order_id` is present.
### Step 3: Event-level diagnostics (after real traffic)
- [ ] **Overview:** Browser and Server sources reported for each event, with dedup reported.
- [ ] **Diagnostics tab:** no open errors (missing parameters, mismatched IDs, invalid currency, low dedup coverage).
- [ ] **Event Match Quality:** note the score per event as a baseline. If it's low, check which `user_data` fields are missing.
- [ ] **Catalog match rate:** shows that `content_ids` match catalog items.
### Step 4: Reconcile against Shopify over a closed window
Do this after several days of live traffic, still before scaling.
- **Use one closed window.** Choose a completed date range, e.g. last full Monday–Sunday, and pull Shopify orders and Meta Purchase events for that exact same range.
- **Align time zones.** Confirm the Shopify store and Meta ad account time zones, or convert one to the other.
- **Exclude non-comparable orders.** Leave out test and refunded test orders, plus any orders from channels without a Pixel journey (e.g. manual draft orders).
- **Compute from rows.** Export the order list and the event list and compare them with a spreadsheet or script rather than by eye. Check counts **and** summed value.
- **Spot-check by ID.** Pick 10 orders by `order_id` and confirm each appears in Meta exactly once.
### Step 5: Interpret gaps carefully
A gap between Shopify and Meta counts is a **symptom, not a diagnosis.** State what you observed, and treat the cause as a hypothesis until you can show the mechanism.
| Observation | Possible explanation (hypothesis) | How to confirm |
|---|---|---|
| Meta Purchases > Shopify orders | Would be explained by failed dedup or a second Pixel | Find duplicate rows for one `order_id`; check event IDs on both copies |
| Meta Purchases < Shopify orders | Consistent with consent-declined shoppers, server send failures, or orders outside the window | Check server logs for those order IDs; check consent status on missing orders |
| Purchase value differs from Shopify revenue | Would be explained by different value definitions (tax/shipping/discounts) | Compare the payload value for one order against its Shopify breakdown |
| Only Browser events, no Server | Consistent with CAPI disabled or token/connection issue | Check the app's data-sharing level; check server response logs |
### Exit criteria before scaling spend
- All four events show both sources and are deduplicated.
- Purchase parameters are correct on spot-checked orders.
- No open Diagnostics errors.
- The closed-window reconciliation has no **unexplained** gaps. Explained gaps, like consent declines, are documented.
### After launch
Re-check Diagnostics weekly, and alert on server send failures. Any theme change, app install, or checkout change requires re-running Steps 1–2.
---
## 7. Consent and Compliance Note
*This is implementation guidance, not legal advice. Confirm requirements with counsel for the regions you sell to.*
- **Consent applies to both paths.** If a shopper declines marketing or tracking consent, suppress or limit **both** the Pixel and the CAPI event. A server-side path is not a way around a declined banner.
- **Configure Shopify's consent tools.** Set up Shopify's Customer Privacy settings and consent banner, or a compatible consent platform, for every region you sell to. The native Meta app reads Shopify's consent signals. A custom build must read the Customer Privacy API in the browser and carry the consent state to the server, as the sketch does with `_marketing_consent`.
- **EU/UK and similar regimes** generally require opt-in before marketing tracking.
- **US state privacy laws.** Some, such as California's, give shoppers rights to opt out of the "sale/sharing" of data for targeted advertising. Meta supports a **Limited Data Use** flag (`data_processing_options`) for these cases. Check Meta's current documentation for the exact values and when to apply them.
- **Disclose and minimize.** Update the store privacy policy to state that you share data with Meta for advertising and measurement. Send only the identifiers listed in Section 4, always hashed where required, and never put PII in event names or `custom_data`.
- **Protect credentials.** Keep the CAPI access token in a secret manager, use a System User token rather than a personal one, and restrict who can access it.
- **Keep reporting honest.** Campaign work is draft-only and no performance data exists yet. Present tracking outputs as measurement infrastructure, not results. Don't cite conversion rates, ROAS, or recovery figures until real, reconciled data exists.
---
### One-page checklist
- [ ] Legacy Pixel code removed from theme and checkout
- [ ] Facebook & Instagram app installed; Pixel, ad account, and catalog connected
- [ ] Data sharing set to the level that enables Conversions API
- [ ] Domain verified
- [ ] Consent banner and Customer Privacy configured for selling regions
- [ ] Value definition documented: `________`
- [ ] Test order: all four events show Browser + Server, deduplicated
- [ ] Purchase `value`, `currency`, `content_ids`, and `order_id` verified against the order
- [ ] Diagnostics clean; Event Match Quality baseline recorded
- [ ] Closed-window Shopify vs. Meta reconciliation done from exported rows
- [ ] Gaps documented as observations with hypotheses and confirmation steps
- [ ] Only then: launch and scale spend