Skip to content

Analytics Integrations (Matomo, Databox, Criteo, Contactpigeon)

Flow ID: IN-12 | Module(s): src/Analytics/, ecommercen/libraries/, ecommercen/feeds/, ecommercen/helpers/ | Complexity: High

Business Overview

Ecommercen integrates with multiple analytics and marketing platforms to provide merchants with comprehensive visitor tracking, business intelligence dashboards, and retargeting product feeds. These integrations fall into three categories:

  1. Server-side tracking (Matomo) -- Real-time visitor profiling, ecommerce event tracking, site search analytics, and user identity stitching via the Matomo PHP SDK with bulk tracking and circuit breaker protection.
  2. Business intelligence push (Databox) -- Hourly push of 15+ aggregated metrics (revenue, orders, customers, shipping, referrers, geographic breakdowns) to the Databox dashboard API.
  3. Product catalog feeds (Criteo, Contactpigeon) -- XML feed exports that power retargeting ad campaigns and personalized push notifications.

A shared tracking_helper.php provides client-side analytics data transforms (GA4 purchase events, platform-specific product ID prefixes, category hierarchy mapping).

API Reference

Matomo Tracking API (Server-Side)

MethodParametersDescription
trackPageView($pageTitle)stringTracks a page view event
trackLoginEvent($userId, $email)int, stringTracks Auth/Login event (value: 1)
trackRegisterEvent($userId, $email)int, stringTracks Auth/Registration event (value: 5)
trackSiteSearch($keyword, $category, $count)string, ?string, ?intTracks internal search query
trackEcommerceOrder(...)orderId, grandTotal, subTotal, tax, shipping, discountTracks completed order
trackEcommerceCartUpdate($grandTotal)floatTracks cart state change
setEcommerceView($sku, $name, $category, $price)mixedSets product/category page context
addEcommerceItem($sku, $name, $category, $price, $qty)mixedAdds item to current transaction
flush()--Sends all queued actions in bulk HTTP request

Databox Push API

Metric KeySQL SourceAttributes
RevenueSUM(total_vat), SUM(total)vat: With Vat / No Vat
OrdersCOUNT(id)--
QuantitySUM(qty)--
Average Order ValueAVG(total_vat)--
RegistrationsCOUNT(customer.id)--
CustomersCOUNT(customer.id)registration: Registered / No registered
Order MethodCOUNT(id)method: By phone / On line
Payment MethodCOUNT(id)method: payway value
Shipping CostCOUNT(id)cost: Paid / Free
Shipping typeCOUNT(id)transporter: transporter name
Picking pointCOUNT(id)store: store address
MarketplacesCOUNT(id)chanel: marketplace domain
ReferrerCOUNT(id)channel: referrer domain
CountryCOUNT(id)country: country name
CountyCOUNT(id)county: county name

Feed Endpoints

PlatformEndpointController
CriteoGET /xml/criteoAdvCriteoCatalog
ContactpigeonGET /xml/contactpigeonAdvContactpigeonXml

Tracking Helper Functions

FunctionDescription
productIdToGoogleId($id)Prefixes product ID for Google Analytics
productIdToFaceBookId($id)Prefixes product ID for Facebook Pixel
productIdToManagoId($id)Prefixes product ID for Manago
applyCategoriesToItemGA4($item, $cats)Maps up to 5 category levels to GA4 item_category* fields
trackPurchase($orderData)Builds GA4 purchase event payload

Code Flow

Matomo Server-Side Tracking

Page Request (storefront)
  -> Adv_front_controller (base controller)
     -> MatomoTracking is initialized via DI with:
        - Config: enabled, baseUrl, siteId, token, productIdPrefix, timeout
        - CircuitBreaker (optional, configured via APP_CB_MATOMO_* env vars)
     -> During page lifecycle:
        -> setEcommerceView() on product pages
        -> addEcommerceItem() for cart items
        -> trackPageView() / trackSiteSearch() / trackEcommerceOrder()
     -> On shutdown/deferred:
        -> flush() sends all queued actions via bulk HTTP POST
           -> CircuitBreaker check: if open, silently skip
           -> On failure: recordFailure(), log error
           -> On success: recordSuccess()

Databox Hourly Push

Cron: AdvReportingToDatabox job
  -> Check registry: DATABOX.ENABLED, DATABOX.TOKEN
  -> Initialize AdvDatabox (legacy) or Databox (client) with token
  -> allData() calls 15 metric methods sequentially:
     -> Each method:
        1. Build SQL query (3-month window, or 3-year for initialization)
        2. Execute query, get hourly-aggregated results
        3. Transform to Databox push format [{key, value, date, unit?, attributes?}]
        4. Chunk into batches of 500
        5. POST each batch to https://push.databox.com/data
           -> Rate limiting: sleep(1) every 10 API calls
           -> Auth: Basic auth with token

Criteo Catalog Feed

HTTP GET /xml/criteo?token=xxx
  -> AdvCriteoCatalog::index() (extends AdvGoogleCatalog)
     -> secureXml(): check XML_FEEDS.IS_ENABLED_CRITEO, optional token auth
     -> getDbData(): product_model->getCriteoRecords()
     -> parseItem(): maps to Google Shopping format with optional custom price modifier
     -> OutputGoogleCatalog XML output

Contactpigeon Feed

HTTP GET /xml/contactpigeon?token=xxx&brand=1&category=2&top=100&stock=50
  -> AdvContactpigeonXml::index() (extends AdvXml)
     -> secureXml(): check XML_FEEDS.IS_ENABLED_CONTACTPIGEON, optional token auth
     -> getDbData(): product_model->getFeedProductsForContactPigeon(brand, category, topSellers, topStock)
     -> parseItems(): for each product:
        -> If colorAsDifferentProduct enabled and multiple colors:
           -> splitProductWithColors(): creates separate XML entries per color variant
           -> Each variant gets: unique uid, color-appended name, color query param in URL, color-specific image
        -> Otherwise: parseSkroutzItem() (standard format)
     -> push_image field: resized to w360,h180 with white fill background

Architecture

src/Analytics/
  MatomoTracking.php           # Server-side Matomo tracking with bulk mode and circuit breaker

ecommercen/libraries/
  AdvDatabox.php               # Databox push client with 15 metric types and SQL queries

ecommercen/job/libraries/
  AdvReportingToDatabox.php    # Cron job wrapper for Databox push

ecommercen/feeds/controllers/
  AdvCriteoCatalog.php         # Criteo product feed (extends AdvGoogleCatalog)
  AdvContactpigeonXml.php      # Contactpigeon product feed (extends AdvXml)

ecommercen/helpers/
  tracking_helper.php          # Client-side analytics transforms (GA4, Facebook, Manago ID prefixes)

application/libraries/
  Databox.php                  # Client-overridable Databox class (extends AdvDatabox)

application/modules/job/libraries/
  ReportingToDatabox.php       # Client-overridable job class (extends AdvReportingToDatabox)

tests/Unit/Analytics/
  MatomoTrackingTest.php       # Unit tests for Matomo tracking

Class Relationships

  • MatomoTracking wraps MatomoTracker (matomo/matomo-php-tracker SDK). Uses CircuitBreaker for fault tolerance and LoggerInterface (PSR-3) for logging.
  • AdvDatabox is a standalone library with direct SQL queries and Guzzle HTTP client. Uses basic auth with push.databox.com.
  • AdvCriteoCatalog extends AdvGoogleCatalog (Google Shopping format) -- only overrides parseItem() and secureXml().
  • AdvContactpigeonXml extends AdvXml (generic feed base) -- adds color-splitting logic and push image resizing.

Data Model

Matomo

No database tables. Uses Matomo PHP SDK to send tracking events to an external Matomo instance. User identity is stitched via setUserId() with the customer ID.

Databox

Queries these tables for aggregated metrics:

TableMetrics Derived
shop_orderRevenue, orders, avg order value, payment method, order method, shipping cost, transporters, stores, marketplaces, referrers, country, county
shop_order_basketQuantity (items sold)
shop_customerRegistrations, customer type (guest vs registered)
transporters_muiTransporter name lookup
store_muiStore address lookup
country / countyGeographic name lookups

Criteo / Contactpigeon

Standard product model queries via product_model methods. Contactpigeon supports query parameters for brand, category, top sellers, and top stock filtering.

Configuration

Matomo (Environment)

VariableDescription
MATOMO_LOG_THRESHOLDLog level threshold (default: ERROR)
MATOMO_LOG_MAX_FILESMaximum log file rotation
APP_CB_MATOMO_THRESHOLDCircuit breaker failure threshold (default: 3)
APP_CB_MATOMO_COOLDOWN_SECONDSInitial cooldown on open (default: 30)
APP_CB_MATOMO_MAX_COOLDOWN_SECONDSMaximum cooldown (default: 300)
APP_CB_MATOMO_COOLDOWN_MULTIPLIERExponential backoff multiplier (default: 2.0)
APP_CB_MATOMO_STATE_TTL_BUFFERState TTL buffer (default: 300)

Matomo site config (baseUrl, siteId, token, productIdPrefix) is loaded from DI container configuration.

Databox (Registry)

GroupKeyDescription
DATABOXENABLEDEnable/disable Databox push
DATABOXTOKENDatabox push API token

Criteo (Registry)

GroupKeyDescription
XML_FEEDSIS_ENABLED_CRITEOEnable feed
XML_FEEDSIS_PROTECTED_CRITEORequire token auth
XML_FEEDSCRITEO_TOKENFeed access token
XML_FEEDSCUSTOM_PRICE_CRITEOApply custom price modifier

Contactpigeon (Registry)

GroupKeyDescription
XML_FEEDSIS_ENABLED_CONTACTPIGEONEnable feed
XML_FEEDSIS_PROTECTED_CONTACTPIGEONRequire token auth
XML_FEEDSCONTACTPIGEON_TOKENFeed access token
XML_FEEDSCUSTOM_PRICE_CONTACTPIGEONApply custom price modifier

Tracking (Registry)

GroupKeyDescription
TRACKINGPRODUCT_ID_PREFIX_GOOGLEPrefix for Google Analytics product IDs
TRACKINGPRODUCT_ID_PREFIX_FACEBOOKPrefix for Facebook Pixel product IDs
MATOMOENABLEDEnable/disable Matomo dashboard widget

Client Extension Points

Matomo

The MatomoTracking class is registered in the DI container. Clients can override the container definition to inject custom configuration or disable tracking entirely.

Databox

  • Override application/libraries/Databox.php (extends AdvDatabox) to add custom metrics.
  • Override application/modules/job/libraries/ReportingToDatabox.php to modify the job execution logic.
  • The allData() method calls all metric pushers -- individual metrics can be overridden by overriding their sent*SQL() and prepare*Rows() method pairs.

Criteo / Contactpigeon

  • Override parseItem() to modify feed field mapping.
  • Override secureXml() to change authentication logic.
  • Override getDbData() to change the product query.

Tracking Helper

Client repos can provide a custom tracking_helper.php in application/helpers/ to override ID prefix functions.

Business Rules

  1. Matomo bulk tracking: All tracking calls are queued in memory and sent in a single bulk HTTP request at the end of the page lifecycle.
  2. Circuit breaker: Matomo tracking is protected by a circuit breaker. When Matomo is unavailable, tracking silently degrades (no impact on page rendering).
  3. Databox rate limiting: API calls are throttled to prevent rate limiting (1-second sleep every 10 calls). Data is chunked in batches of 500 data points.
  4. Databox time windows: Regular pushes cover 3 months; initialization (allData(true)) covers 3 years.
  5. Order status filtering: Databox excludes orders with status CANCELED, RETURN, or PENDING from all metrics.
  6. Criteo format: Extends Google Shopping catalog format. Only overrides pricing and authentication.
  7. Contactpigeon color splitting: When colorAsDifferentProduct is enabled, products with multiple color variants generate separate feed entries, each with a unique ID suffix, color-specific image, and color query parameter in the URL.
  8. Contactpigeon push images: Images are resized to 360x180 with white background fill for push notification compatibility.
  9. Product ID prefixes: Each analytics platform uses a configurable prefix (e.g., ADV_ for Google, FB_ for Facebook) to avoid ID collisions across platforms.