# Cedar & Coil — Shopify + Meta Conversions API Implementation Guide
> Draft-only evaluation deliverable. No tracking, ads, integrations, or store configuration was changed.
## 1. Recommended architecture
Use one Meta dataset (Pixel) and send the same commerce funnel through two paths:
1. **Browser path — Meta Pixel** fires `ViewContent`, `AddToCart`, `InitiateCheckout`, and `Purchase` in the shopper’s browser after consent.
2. **Server path — Meta Conversions API (CAPI)** sends the same events from a trusted server/webhook after consent, with an identical event name and `event_id` where the event is duplicated.
The Pixel captures browser context such as the Meta browser cookie (`_fbp`), click ID (`_fbc`), page URL, and immediate product interactions. Browser delivery can be reduced by ad blockers, cookie rules, browser privacy controls, and page failures. CAPI is not dependent on the browser completing the request and is especially useful for authoritative order completion from Shopify.
CAPI is a complement, not a replacement: CAPI without browser identifiers can match less well, while Pixel alone can miss browser-side delivery.
Do not send two independently named “Purchase” events for one order. Send a coordinated browser/server pair and deduplicate it.
---
## 2. Event contract
Use Meta standard event names, product/variant IDs that remain stable, ISO 4217 currency, and monetary values in the order/product currency. The Arc Clip Lamp’s current price is **$68**, but event value must use the actual item subtotal or order value at the time of the event—never a hard-coded `$68`.
| Event | Trigger | Required / recommended parameters |
|---|---|---|
| `ViewContent` | Product detail page is viewed | `content_ids: [variant_or_catalog_id]`, `content_type: "product"`, `content_name: "Arc Clip Lamp"`, `value` (current product/variant price), `currency: "USD"`; browser path also includes `eventID` / `event_id` if mirrored server-side. |
| `AddToCart` | Item is successfully added to cart | `content_ids`, `content_type: "product"`, `contents: [{id, quantity, item_price}]`, `value` (added-line subtotal), `currency: "USD"`, common `event_id` if both paths send it. |
| `InitiateCheckout` | Shopper begins checkout—not merely clicks a checkout button if the transition fails | `content_ids` and `contents` for cart lines, `num_items`, `value` (checkout/cart subtotal under the documented convention), `currency: "USD"`, common `event_id` if mirrored server-side. |
| `Purchase` | Shopify reports a paid/accepted completed order; use an idempotent server-side order-completion trigger | `content_ids: [variant IDs]`, `content_type: "product"`, `contents: [{id, quantity, item_price}]`, `num_items`, `value` (actual order amount under the chosen documented convention), `currency: "USD"`, `order_id`, and the same `event_id` in browser Pixel and CAPI when both are sent. |
### Parameter conventions
- Use the same ID namespace in Pixel, CAPI, and any Meta catalog. Prefer Shopify variant IDs if the catalog is also variant-based; do not mix Shopify product IDs in one path with SKUs in another.
- Define and document whether `Purchase.value` is subtotal, total excluding tax/shipping, or total charged. Apply it identically in both paths.
- `contents[].item_price` is per unit; `value` is the selected total. `quantity` is an integer.
- Never place email addresses, names, phone numbers, raw addresses, or other PII in `custom_data`, URLs, or client-side data-layer fields.
---
## 3. Pixel/CAPI deduplication: exact mechanism
For a shopper action intentionally sent on both browser and server paths:
1. Generate one opaque UUID at event creation.
2. Browser Pixel sends the standard event with that value as `eventID`:
```js
fbq('track', 'Purchase', pixelPayload, { eventID: eventId });
```
3. CAPI sends the **same** value as `event_id`, with the same event name (`Purchase`), to the same Meta dataset/pixel.
4. Meta recognizes the pair as one conversion rather than two.
Keep the event name and event ID byte-for-byte identical.
### Purchase example
- Shopify order completes.
- A durable `purchaseEventId` is created and stored once for that order.
- Browser sends Pixel `Purchase` with `eventID: purchaseEventId`.
- Server sends CAPI `Purchase` with `event_id: purchaseEventId`.
- If Shopify redelivers the webhook, reuse that same event ID rather than generating a new one.
Do not reuse one event ID across different events or orders. Do not rely only on `order_id` as the deduplication mechanism: include it as a business reference, but use the shared `event_id` to deduplicate Pixel and CAPI.
Maintain server-side idempotency keyed by Shopify order ID plus event type so webhook redelivery cannot create duplicate CAPI Purchases.
---
## 4. Preparing customer information for CAPI
Server-side matching uses `user_data`. Collect and process it only after the applicable consent decision and only for the stated advertising/measurement purpose.
### Normalize and hash customer fields
Before SHA-256 hashing, normalize consistently:
- **Email (`em`)**: trim whitespace and lowercase, then hash.
- **Phone (`ph`)**: normalize to E.164 digits with country code; remove punctuation/whitespace, then hash.
- **First/last name (`fn`, `ln`)**: lowercase and trim; hash separately if used.
- **City/state/country/ZIP (`ct`, `st`, `country`, `zp`)**: lowercase, trim, normalize country to the expected two-letter form, and hash each field if used.
- **External ID (`external_id`)**: use a stable, non-sensitive internal customer identifier where appropriate; normalize/hash according to Meta’s current specification.
Use SHA-256 on UTF-8 normalized strings. Do not hash unnormalized values, double-hash, salt values, or send raw PII in fields that require hashing.
Never expose the CAPI access token in storefront JavaScript.
### Include browser and click identifiers when permitted
When consent allows, send:
- `fbp`: Meta browser identifier from `_fbp`.
- `fbc`: Meta click identifier from the Meta click context.
- `client_ip_address` and `client_user_agent`: captured from the actual shopper request, where lawful and permitted.
A Shopify webhook often does not have the originating browser IP or user agent. Preserve consented `fbp`/`fbc` and other permitted identifiers in a secure first-party session/order record before checkout completion, then join them to the authoritative order event.
If that is not feasible, send the completed purchase with permitted customer fields Shopify provides and accept that matching may be less complete. Never manufacture identifiers.
Use least-privilege access, a defined retention period, and deletion/opt-out workflows.
---
## 5. Shopify setup path
### Option A: Native Meta sales channel app
Use Shopify’s official **Facebook & Instagram by Meta** sales channel/app to connect the Shopify store to the correct Meta business/dataset, select the appropriate data-sharing configuration, and implement supported Pixel plus CAPI commerce tracking.
**Advantages**
- Lowest implementation and maintenance burden.
- Native product and order mapping.
- Fewer opportunities to expose tokens or accidentally duplicate Purchases.
- Best starting point for a small DTC store selling the Arc Clip Lamp.
**Limits**
- Less control over custom server logic, consented identifier persistence, non-Shopify checkout flows, and unusual event contracts.
- Verify the actual emitted events and parameters in the current store configuration; do not assume a setting meets a bespoke tracking plan.
### Option B: Custom Pixel + custom CAPI service
Install Pixel through Shopify’s supported customer-events/pixel mechanism and operate CAPI through a small server service.
The service should:
1. Receive a trusted Shopify order/checkout webhook.
2. Verify webhook authenticity.
3. Check consent.
4. Load permitted first-party identifiers.
5. Normalize/hash customer data.
6. Send CAPI.
7. Persist idempotency state and redacted delivery logs.
**Advantages**
- Full control over event IDs, event payloads, consent gating, observability, and retry behavior.
**Costs and risks**
- Requires engineering ownership for webhook verification, secrets, token rotation, idempotency, monitoring, and privacy operations.
- Can double-count if the native Meta sales channel remains active without a clear event-ownership plan.
### Recommendation
For Cedar & Coil as a small DTC Shopify store, start with the official Meta sales channel/app and its supported Pixel+CAPI configuration.
Validate it fully before Meta ads go live. Move to a custom implementation only if a real requirement cannot be satisfied natively—for example:
- a custom or non-Shopify checkout flow;
- a permitted first-party identifier strategy the native app cannot support;
- explicit event-ID orchestration or bespoke server-side controls.
Do not run native and custom Purchase tracking together until there is a documented ownership map and a verified deduplication test.
### Custom CAPI Purchase request sketch
This illustrative Node.js server sketch uses placeholders and must sit behind verified Shopify webhook handling and consent enforcement. Do not put it in theme JavaScript.
```js
import crypto from 'node:crypto';
const sha256 = (s) =>
crypto.createHash('sha256').update(s, 'utf8').digest('hex');
const normEmail = (s) => s.trim().toLowerCase();
const normPhone = (s) => s.replace(/[^0-9+]/g, '');
// Replace with robust E.164 validation.
async function sendPurchaseToMeta({ order, tracking, consent }) {
if (!consent.marketingMeasurement) return;
// Persist once per order; never regenerate on webhook retry.
const eventId = tracking.purchaseEventId;
const contents = order.line_items.map((line) => ({
id: String(line.variant_id), // Same namespace as Pixel/catalog.
quantity: Number(line.quantity),
item_price: Number(line.price)
}));
const userData = {};
if (order.email) {
userData.em = [sha256(normEmail(order.email))];
}
if (order.phone) {
userData.ph = [sha256(normPhone(order.phone))];
}
if (tracking.fbp) userData.fbp = tracking.fbp;
if (tracking.fbc) userData.fbc = tracking.fbc;
if (tracking.ip) userData.client_ip_address = tracking.ip;
if (tracking.userAgent) userData.client_user_agent = tracking.userAgent;
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: tracking.orderStatusUrl,
user_data: userData,
custom_data: {
currency: order.currency || 'USD',
value: Number(order.total_price),
content_type: 'product',
content_ids: contents.map((x) => x.id),
contents,
num_items: contents.reduce(
(sum, item) => sum + item.quantity,
0
),
order_id: String(order.id)
}
}]
};
const endpoint =
'https://graph.facebook.com/<API_VERSION>/<META_DATASET_ID>/events';
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...payload,
access_token: process.env.META_CAPI_ACCESS_TOKEN
})
});
if (!response.ok) {
throw new Error(`Meta CAPI error: ${response.status}`);
}
}
```
Before production, add:
- Shopify webhook HMAC verification;
- durable idempotency storage;
- retries only for transient failures;
- redacted structured logs and alerts;
- secret storage and token rotation;
- consent audit records;
- deletion and opt-out handling;
- a guard against duplicate native purchase tracking.
---
## 6. End-to-end validation before scaling spend
Run this with a controlled test order before increasing spend.
1. **Inventory ownership**
List every Meta tag/app/pixel and every server endpoint/webhook. Confirm one intended Meta dataset owns the event stream. Disable or isolate duplicates.
2. **Test consent behavior**
Test an opt-out/no-consent browser and a consented browser separately. Pixel, CAPI, and identifier storage must behave exactly as the approved privacy design requires.
3. **Inspect browser events**
In a consented test browser, use Meta Pixel Helper and the browser network inspector. Verify one each of:
- `ViewContent`
- `AddToCart`
- `InitiateCheckout`
- `Purchase`
Confirm correct IDs, value, currency, `contents`, and browser `eventID`.
4. **Place one controlled test order**
Use Shopify’s supported test-payment method or another controlled order process. Confirm the order reaches the defined paid/completed condition once.
5. **Inspect server delivery**
In Meta Events Manager Test Events/diagnostics, confirm the CAPI event arrives with:
- expected event name and time;
- `event_id`;
- content IDs;
- value and currency;
- permitted matching fields.
Confirm no raw customer data appears in logs or captured payloads.
6. **Verify deduplication**
Confirm the browser and server `Purchase` events have the exact same event ID and are handled as a deduplicated pair—not two Purchases. If not, stop and fix the ID handoff, dataset selection, or duplicate-tag ownership before spending.
7. **Reconcile with Shopify**
Reconcile the test order ID and chosen value convention with Shopify. Shopify remains the source of truth for completed orders.
8. **Test failure paths**
Safely re-deliver the same webhook or simulate a retry in non-production. Verify it does not create a second CAPI Purchase. Also test:
- missing `fbp` / `fbc`;
- blocked browser requests;
- mobile browsers;
- multi-quantity carts.
9. **Set monitoring**
Alert on:
- CAPI delivery failures;
- sudden event-volume drops;
- schema/parameter errors;
- duplicate Purchase events;
- material divergence between Shopify completed orders and deduplicated Meta Purchases.
Re-test after any theme, checkout, app, consent-banner, or catalog change.
Ready to scale means the controlled journey has one correct authoritative order, expected funnel events, a validated deduplicated Purchase pair, consent behavior matching policy, and no unresolved diagnostics. It does **not** imply a specific attribution-recovery percentage.
---
## 7. Consent and compliance
This is an implementation guide, not legal advice. Cedar & Coil should have privacy/legal ownership confirm applicable obligations before activation, particularly for regions with consent and opt-out requirements.
At minimum:
- Clearly disclose Meta advertising/measurement processing, cookies, server-side disclosure, and applicable sharing in the privacy notice.
- Use a consent-management platform or equivalent mechanism that gates Pixel/CAPI and identifier storage according to the applicable legal basis and regional requirements.
- Remember: server-side tracking does **not** remove consent obligations.
- Honor opt-outs, withdrawals, deletion/access requests, and applicable global privacy signals where required. Apply the preference to both browser and server paths.
- Send only information needed for the measurement purpose. Do not send sensitive-category data or PII in URLs, product metadata, event properties, or advertising parameters.
- Protect the Meta token and customer data with server-side secrets, least-privilege access, access controls, audit logs, and documented retention/deletion rules.
- Recheck Shopify, Meta, and applicable legal requirements before launch; platform behavior and regional rules can change.
A durable copy of this draft is also saved at:
`resources/evals/20260826-053858-0af06e7c/shopify-meta-capi/cedar-coil-meta-capi-implementation-guide.md`
Files saved:
- [Open cedar-coil-meta-capi-implementation-guide.md](magister-file://resources/evals/20260826-053858-0af06e7c/shopify-meta-capi/cedar-coil-meta-capi-implementation-guide.md)