=== CapiFlow – Conversions API (CAPI) Tracking for WooCommerce ===
Contributors: capiflow
Tags: meta pixel, conversions api, facebook pixel, woocommerce, server-side tracking
Requires at least: 6.0
Tested up to: 7.0
Requires PHP: 7.4
Stable tag: 1.1.1
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Send WooCommerce events to Meta Conversions API with server-side tracking, deduplication, and confirmed Purchase control.

== Description ==

**CapiFlow** sends supported WooCommerce events from your server to Meta's Conversions API (CAPI) — helping reduce the impact of browser-side tracking limitations like ad blockers, Safari ITP, and Firefox ETP.

= Why Server-Side Tracking Matters =

When the Meta pixel is blocked, event data may not reach Meta — affecting ad optimization. CapiFlow complements the browser pixel by sending events server-side with a matching `event_id` for deduplication.

= How It Works =

1. **Install & Activate** — Setup wizard launches automatically
2. **Enter Pixel ID + Access Token** — From Meta Events Manager
3. **Click Test Connection** — Events start flowing

No theme edits. No GTM server container required. No separate server-container subscription needed for the built-in Meta CAPI workflow.

= Core Features =

**Server-Side Event Tracking**

* 🎯 **7 Standard Events** — Purchase, InitiateCheckout, AddPaymentInfo, AddToCart, ViewContent, Search, PageView
* 🔄 **Deduplication** — Browser pixel and server events share the same `event_id` to support Meta's deduplication
* 🛡️ **First-Party Event Endpoint** — Browser events can be delivered through your own domain where configured
* 🔐 **SHA-256 PII Hashing** — Email, phone, name hashed before leaving your server

**Event Match Quality Support** — `fbc`, `fbp`, `external_id`, client IP, user agent, and hashed customer data (email, phone, name) for logged-in users.

**Analytics & Monitoring**

* 📈 Dashboard — event breakdown and source attribution
* 🔍 Debug console — payloads and Meta API responses
* 🏥 System health — token, queue, connection test
* 🛒 Cart monitor — abandoned cart summary

**Data Quality & Control**

* 📞 Phone validation at checkout
* 🔒 COD Purchase gate — hold events until admin confirms
* 📋 Order metabox and columns — per-order CAPI status

**Developer Tools**

* 🔧 Code injection — GTM, analytics, chat widgets (admin-only)
* 🪝 Filter hooks — `capiflow_proxy_url`, `capiflow_has_tracking_consent`
* 📦 HPOS compatible — WooCommerce High-Performance Order Storage support
* ⏱️ Action Scheduler queue — async event delivery with retry logic

= CapiFlow Pro =

CapiFlow Pro is a separate addon that extends the free plugin with:

* Phone reputation scoring and fraud detection
* Negative Purchase events for cancelled/refunded orders
* Multi-pixel and category-based pixel routing
* COD auto-confirm with courier integration
* Real-time EMQ score display from Meta API
* Blacklist management for known fraud patterns
* Advanced order quality tools

Learn more on the [CapiFlow website](https://capiflowpro.com).

= Compatibility =

* **Gateways:** bKash, Nagad, SSLCommerz, Stripe, PayPal, COD, and all standard WooCommerce gateways
* **Themes:** Any theme — Classic, Block (FSE), page builders
* **WooCommerce:** HPOS and legacy post-based orders
* **Consent:** CookieYes, Complianz, CookieBot, GDPR Cookie Consent, custom filter hook

= Requirements =

* WordPress 6.0+
* WooCommerce 7.0+
* PHP 7.4+
* OpenSSL PHP extension
* Meta Pixel ID and System User Access Token

= External Services =

This plugin connects to the following third-party services:

**Meta (Facebook) Conversions API**

CapiFlow sends WooCommerce event data to the Meta Conversions API via: `https://graph.facebook.com/`

This connection is made from your server to Meta's servers when a configured tracking event occurs. No data is sent until a valid Pixel ID and Access Token are configured.

Data transmitted includes:

* Hashed email, phone, first and last name (SHA-256)
* Client IP address and Browser User Agent
* Meta Click ID (_fbc) and Browser ID (_fbp) cookies
* Order total, currency, and event metadata

All personal data is SHA-256 hashed before transmission.

* [Meta Terms of Service](https://www.facebook.com/terms.php)
* [Meta Privacy Policy](https://www.facebook.com/privacy/policy/)
* [Meta Platform Terms](https://developers.facebook.com/terms/)

**Meta Pixel JavaScript SDK**

This plugin loads the Meta Pixel SDK from: `https://connect.facebook.net/en_US/fbevents.js`

Loaded on frontend pages when a Pixel ID is configured. The SDK is hosted by Meta.

* [Meta Terms of Service](https://www.facebook.com/terms.php)
* [Meta Privacy Policy](https://www.facebook.com/privacy/policy/)

= Privacy =

For server-side events, all personal data is SHA-256 hashed before transmission. For browser events, the Meta Pixel SDK handles hashing via Advanced Matching. This plugin does not store raw PII in its own tables. See [Meta's privacy policy](https://www.facebook.com/privacy/policy/).

= Cookies =

* `cs_uid` — Random visitor identifier for `external_id` deduplication. 180 days. No PII.
* `_fbc` — Meta Click ID. Set by Meta SDK on ad click. CapiFlow reads/extends server-side. 180 days.
* `_fbp` — Meta Browser ID. Set by Meta SDK. CapiFlow reads/extends server-side. 180 days.

All cookies are first-party and contain no personally identifiable information.

= Data Storage =

* `{prefix}_capiflow_events` — Queued/sent event payloads. Auto-purged after delivery.
* `{prefix}_capiflow_analytics` — Daily aggregated analytics. Auto-purged by retention settings.
* Order metadata with `_capiflow_` prefix. Removed on uninstall if "Keep Data" is disabled.
* Logs in `wp-content/uploads/capiflow-logs/` with `.htaccess` protection. Auto-cleaned daily.

= Consent =

By default, events fire once configured. Enable "Consent Enforcement" in Settings to respect CMP signals for both browser and server events.

Supported CMPs: CookieYes, Complianz, CookieBot, GDPR Cookie Consent. Custom integration via `capiflow_has_tracking_consent` filter.

When Consent Enforcement is enabled, browser and server-side events are blocked until valid tracking consent is detected.

Store owners are responsible for lawful consent configuration where required by privacy regulations.

== Installation ==

1. Install from WordPress plugins screen or upload `capiflow` to `/wp-content/plugins/`.
2. Activate through the **Plugins** menu.
3. Setup wizard launches — enter **Pixel ID** and **Access Token**.
4. Click **Test Connection** — check **CapiFlow → Dashboard** to monitor.

= Getting an Access Token =

1. [Meta Events Manager](https://www.facebook.com/events_manager2/) → Select Pixel → Settings → Conversions API
2. Click **Generate Access Token** or create a System User
3. Paste into CapiFlow → Settings → Pixel Settings

== Frequently Asked Questions ==

= Does this replace the Meta browser pixel? =

No. CapiFlow works alongside the browser pixel using Meta's recommended redundant setup — both share a matching `event_id` for deduplication.

= Will this cause duplicate events? =

No. Matching `event_id` values ensure Meta deduplicates browser and server events automatically.

= Do I need a GTM server container or a service like Stape.io? =

No. CapiFlow sends events directly from your WooCommerce server to Meta — no separate GTM server container, third-party service, or monthly subscription needed.

= How does this support Event Match Quality? =

CapiFlow sends `fbc`, `fbp`, `external_id`, client IP, user agent, and hashed customer data — additional signals that can improve event matching vs browser-only tracking.

= How is privacy handled? =

All PII is SHA-256 hashed before transmission. Consent Enforcement toggle blocks events until CMP consent is granted. Privacy policy content auto-added to your WordPress Privacy Policy page.

= Which order storage is supported? =

Both traditional posts-based and HPOS (High-Performance Order Storage). Auto-detected, no configuration needed.

= Does this work with my payment gateway? =

Yes. CapiFlow uses WooCommerce's standard order status hooks. Compatible with bKash, Nagad, SSLCommerz, Stripe, PayPal, COD, and all standard gateways.

= What happens with COD orders? =

Purchase event is held until admin confirms the order, preventing unverified COD orders from reaching Meta.

= Do I need Google Tag Manager? =

No. CapiFlow works standalone. If you need GTM or other scripts, a built-in code injection feature is included.

= What is CapiFlow Pro? =

A separate addon that adds fraud protection, negative Purchase events for cancellations, multi-pixel routing, courier integration, and real-time EMQ scores. [Learn more](https://capiflowpro.com).

== Screenshots ==

1. **Setup Wizard** — Guided first-time configuration
2. **Settings Page** — Pixel ID, Access Token, and connection test
3. **Analytics Dashboard** — Event tracking overview
4. **Event Configuration** — Per-event browser and server toggles
5. **System Health** — Token validity and queue status
6. **Debug Console** — Event log with API responses
7. **Order Columns** — CAPI sync status in order list
8. **Pixel Helper** — Browser and server event verification
9. **Event Test Tool** — All events delivery status
10. **Purchase Event** — Server-side Purchase with API response

== Changelog ==

= 1.1.1 — 2026-08-21 =

* Fix: `predicted_ltv` is now only sent in Purchase events when COGS (Cost of Goods Sold) data is actually populated. Previously, missing `_woo_capi_cogs` meta caused `predicted_ltv` to always equal the order total, which Meta flagged as an invalid value and could distort Value-Based Bidding optimization.

= 1.1.0 — 2026-08-20 =

* New: Marketplace Catalog Verified — Content ID Strategy setting (SKU / Parent SKU / WooCommerce Product ID) for pixel-to-catalog alignment.
* New: `Event_Builder::resolve_content_id()` static resolver — single source of truth for all event methods (Purchase, InitiateCheckout, AddToCart, ViewContent, AddPaymentInfo, Negative Events).
* New: `Event_Builder::resolve_content_type()` — automatically switches between `product` and `product_group` based on ID strategy and product type.
* New: `Event_Builder::resolve_item_price()` — tax-parity normalizer ensures item_price matches catalog feed pricing (incl./excl. tax).
* New: Search event now includes `content_ids` and `contents` arrays from search results (up to 10 products).
* New: Guard 5 — Order Source Filter blocks CAPI Purchase events for marketplace/external channel orders (configurable via Settings > Events).
* New: Guard 6 — `capiflow_should_track_purchase` filter provides a clean developer escape hatch to suppress individual Purchase events without setting a dedup lock.
* New: `capiflow_content_id` filter allows custom catalog integrations to override resolved content IDs.
* Fix: `content_category` now correctly uses the parent product ID for variable product variations (variations have no direct category assignment).
* Fix: `get_product_sku_map()` in Pixel Injector now uses `resolve_content_id()` so JS AddToCart content_ids always match server-side events.
* Fix: `store_deferred_addtocart()` now uses `resolve_content_type()` for the deferred AddToCart pixel event.
* Fix: Cart loop guards now check `instanceof WC_Product` before processing to prevent TypeError on malformed cart data.
* Fix: Order item loops now check `instanceof WC_Order_Item_Product` to skip shipping/fee/coupon line items silently.
* Deprecated: `Event_Builder::get_content_type()` and `get_content_id()` now proxy to new static resolvers for backward compatibility.

= 1.0.2 — 2026-07-29 =

* Fix: Prevent firing Purchase events for pre-existing orders created prior to CapiFlow installation or >7 days ago when order status is changed in WP Admin/background.
* Fix: Add self-healing installation timestamp and multi-layered pre-installation protection guard to prevent invalid server-side Purchase attribution.

= 1.0.1 — 2026-05-22 =

* Update WordPress compatibility header to Tested up to 7.0 for WordPress 7.0 "Armstrong" release.

= 1.0.0 — 2026-05-01 =

* Initial public release
* Server-side tracking for 7 Meta standard events via Conversions API
* Browser + server event deduplication with matching event_id
* First-party event endpoint, SHA-256 PII hashing, Advanced Matching
* COD Purchase gate, phone validation, analytics dashboard
* Debug console, system health, setup wizard
* HPOS compatible, Action Scheduler queue, CMP integration

== Upgrade Notice ==

= 1.1.1 =
Fixes Meta Events Manager "predicted_ltv invalid value" warning. The predicted_ltv field is now only included when COGS data exists.

= 1.1.0 =
Major catalog alignment release: configurable Content ID Strategy (SKU/Parent SKU/Product ID), Search content_ids, Order Source Filter for marketplace integrations, Guard 5 and Guard 6 for Purchase events, and tax-parity item pricing. Upgrade recommended for all Dynamic Ads users.

= 1.0.2 =
Fixes issue where pre-existing orders created before plugin installation triggered invalid Purchase events upon status changes.

= 1.0.1 =
WordPress 7.0 compatibility release.

= 1.0.0 =
Initial public release.
