get_meta('_vs_event_session_id', true)); if (wp_is_uuid($session_id, 4)) { return strtolower($session_id); } $session_id = wp_generate_uuid4(); $order->update_meta_data('_vs_event_session_id', $session_id); $order->save_meta_data(); return strtolower($session_id); } class VASP_WooCommerce_Integration { private $event_recorder; private $pending_cart_events = []; public function __construct() { $this->event_recorder = null; $this->init_hooks(); } /** * Initialize WooCommerce hooks */ private function init_hooks() { // Only initialize if WooCommerce is active if (!class_exists('WooCommerce')) { return; } // Cart item added add_action('woocommerce_add_to_cart', [$this, 'track_cart_item_added'], 10, 6); // Cart item removed add_action('woocommerce_cart_item_removed', [$this, 'track_cart_item_removed'], 10, 2); add_action('woocommerce_cart_item_removed', [$this, 'flush_pending_empty_cart_events'], 30, 2); // Cart item quantity updated add_action('woocommerce_after_cart_item_quantity_update', [$this, 'track_cart_item_quantity_updated'], 10, 4); add_action('woocommerce_after_calculate_totals', [$this, 'flush_pending_cart_events'], 100, 1); // Coupon applied add_action('woocommerce_applied_coupon', [$this, 'track_coupon_applied'], 10, 1); // Coupon removed add_action('woocommerce_removed_coupon', [$this, 'track_coupon_removed'], 10, 1); // Authoritative checkout and purchase lifecycle boundaries. add_action('woocommerce_checkout_order_processed', [$this, 'track_checkout_processed'], 10, 3); add_action('woocommerce_payment_complete', [$this, 'track_order_completed'], 10, 1); add_action('woocommerce_order_status_completed', [$this, 'track_order_completed'], 10, 2); } /** * Persist the event session on the order and close the active cart lifecycle. */ public function track_checkout_processed($order_id, $posted_data, $order) { if (!$order instanceof WC_Order) { $order = wc_get_order($order_id); } if (!$order) { return; } $recorder = $this->get_event_recorder(); $result = $recorder->record_event('checkout.started', [ 'order_id' => (int) $order_id, 'item_count' => (int) $order->get_item_count(), 'order_total' => (string) $order->get_total(), 'currency' => (string) $order->get_currency(), 'detected_via' => 'woocommerce_checkout_order_processed', ], null, [ 'event_uid' => hash('sha256', 'checkout.started|order|' . (int) $order_id), 'producer' => 'woocommerce_order_background', ]); if (!empty($result['success']) && !empty($result['session_id'])) { $order->update_meta_data('_vs_event_session_id', sanitize_text_field((string) $result['session_id'])); $order->save_meta_data(); } } /** * Get event recorder instance */ private function get_event_recorder() { if ($this->event_recorder === null) { if (!class_exists('VASP_Event_Recorder')) { require_once __DIR__ . '/recorder.php'; } $this->event_recorder = new VASP_Event_Recorder(); } return $this->event_recorder; } /** * Track when items are added to cart */ public function track_cart_item_added($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) { $cart = WC()->cart; if (!$cart) { return; } $cart_item = $cart->cart_contents[$cart_item_key] ?? []; $this->pending_cart_events = array_values(array_filter($this->pending_cart_events, function($event) use ($cart_item_key) { return ($event['cart_item_key'] ?? '') !== $cart_item_key; })); $this->pending_cart_events[] = [ 'event_type' => 'cart.added', 'cart_item_key' => $cart_item_key, 'data' => array_merge([ 'product_id' => $product_id, 'variation_id' => $variation_id, 'quantity' => $quantity, 'detected_via' => 'woocommerce_hook', ], $this->get_product_fields($product_id, $variation_id, $quantity, $cart_item)), ]; } /** * Track when items are removed from cart */ public function track_cart_item_removed($cart_item_key, $cart) { $cart_item = $cart->removed_cart_contents[$cart_item_key] ?? null; if ($cart_item) { $product_id = $cart_item['product_id'] ?? null; $quantity = $cart_item['quantity'] ?? 1; $variation_id = $cart_item['variation_id'] ?? null; $this->pending_cart_events[] = [ 'event_type' => 'cart.removed', 'cart_item_key' => $cart_item_key, 'data' => array_merge([ 'product_id' => $product_id, 'variation_id' => $variation_id, 'quantity' => $quantity, 'detected_via' => 'woocommerce_hook', ], $this->get_product_fields($product_id, $variation_id, $quantity, $cart_item)), ]; } } /** * Track when cart item quantities are updated */ public function track_cart_item_quantity_updated($cart_item_key, $quantity, $old_quantity, $cart) { // Simple duplicate prevention - skip if quantity didn't actually change if ($quantity == $old_quantity) { return; } $cart_item = $cart->cart_contents[$cart_item_key] ?? null; if ($cart_item) { $product_id = $cart_item['product_id'] ?? null; $variation_id = $cart_item['variation_id'] ?? null; $this->pending_cart_events[] = [ 'event_type' => 'cart.updated', 'cart_item_key' => $cart_item_key, 'data' => array_merge([ 'product_id' => $product_id, 'variation_id' => $variation_id, 'old_quantity' => $old_quantity, 'new_quantity' => $quantity, 'quantity_change' => $quantity - $old_quantity, 'detected_via' => 'woocommerce_hook', ], $this->get_product_fields($product_id, $variation_id, $quantity, $cart_item)), ]; } } /** Publish staged item mutations after WooCommerce has committed totals. */ public function flush_pending_cart_events($cart = null) { if (!$this->pending_cart_events || !is_object($cart) || !method_exists($cart, 'get_cart')) { return; } $pending = $this->pending_cart_events; $this->pending_cart_events = []; $snapshot = $this->get_cart_snapshot($cart); $recorder = $this->get_event_recorder(); foreach ($pending as $event) { $data = $event['data']; $data['cart_snapshot'] = $snapshot; $recorder->record_event($event['event_type'], $data, null, [ 'producer' => 'woocommerce_cart', ]); } } /** Publish the final removal after WooCommerce resets totals for an empty cart. */ public function flush_pending_empty_cart_events($cart_item_key, $cart) { unset($cart_item_key); if (is_object($cart) && method_exists($cart, 'is_empty') && $cart->is_empty()) { $this->flush_pending_cart_events($cart); } } /** * Track when coupons are applied */ public function track_coupon_applied($coupon_code) { unset($coupon_code); $this->pending_cart_events[] = [ 'event_type' => 'cart.coupon_applied', 'data' => [ 'coupon_present' => true, 'detected_via' => 'woocommerce_hook', ], ]; } /** * Get comprehensive cart snapshot */ private function get_cart_snapshot($cart) { $cart_items = []; $total_items = 0; foreach ($cart->get_cart() as $cart_item) { $product_id = $cart_item['product_id'] ?? 0; $variation_id = $cart_item['variation_id'] ?? 0; $quantity = $cart_item['quantity'] ?? 0; $line_total = $cart_item['line_total'] ?? 0; $product_fields = $this->get_product_fields($product_id, $variation_id, $quantity, $cart_item); $cart_items[] = array_merge([ 'product_id' => $product_id, 'variation_id' => $variation_id, 'quantity' => $quantity, 'price' => isset($cart_item['data']) && is_object($cart_item['data']) && method_exists($cart_item['data'], 'get_price') ? $cart_item['data']->get_price() : 0, 'line_total' => $line_total, ], $product_fields); $total_items += $quantity; } return [ 'items' => $cart_items, 'total_items' => $total_items, 'subtotal' => (float) $cart->get_subtotal(), 'total' => (float) $cart->get_total('edit'), 'currency' => get_woocommerce_currency(), ]; } /** Return stable identity fields for the mutated product and cart lines. */ private function get_product_fields($product_id, $variation_id, $quantity, $cart_item = []) { $product = isset($cart_item['data']) && is_object($cart_item['data']) ? $cart_item['data'] : null; $name = $product && method_exists($product, 'get_name') ? (string) $product->get_name() : (string) get_the_title((int) $product_id); $name = sanitize_text_field($name); $name = function_exists('mb_substr') ? mb_substr($name, 0, 200, 'UTF-8') : substr($name, 0, 200); $url = $product && method_exists($product, 'get_permalink') ? (string) $product->get_permalink() : (string) (get_permalink((int) $product_id) ?: ''); return [ 'product_id' => (int) $product_id, 'variation_id' => max(0, (int) $variation_id), 'product_title' => $name, 'product_url' => $url, 'quantity' => max(0, (float) $quantity), ]; } /** * Track when coupons are removed */ public function track_coupon_removed($coupon_code) { unset($coupon_code); $this->pending_cart_events[] = [ 'event_type' => 'cart.coupon_removed', 'data' => [ 'coupon_present' => false, 'detected_via' => 'woocommerce_hook', ], ]; } /** * Track when orders are completed */ public function track_order_completed($order_id, $order = null) { if (!$order instanceof WC_Order) { $order = wc_get_order($order_id); } if (!$order) { return; } $order_items = []; foreach ($order->get_items() as $item) { $product_id = (int) $item->get_product_id(); if (!$product_id) { continue; } $product_fields = function_exists('vasp_event_enrich_product_data') ? vasp_event_enrich_product_data(['product_id' => $product_id]) : []; $order_items[] = [ 'product_id' => $product_id, 'variation_id' => (int) $item->get_variation_id(), 'product_title' => $item->get_name(), 'product_url' => get_permalink($product_id) ?: '', 'default_product_id' => (int) ($product_fields['default_content_id'] ?? $product_id), 'default_product_title' => (string) ($product_fields['default_title'] ?? $item->get_name()), 'default_product_url' => (string) ($product_fields['default_url'] ?? (get_permalink($product_id) ?: '')), 'quantity' => (int) $item->get_quantity() ]; } $recorder = $this->get_event_recorder(); $session_id = vasp_event_resolve_order_session_id($order); $customer_id = (int) $order->get_customer_id(); $is_admin_user = $customer_id > 0 && user_can($customer_id, 'manage_options'); $recorder->record_event('order.completed', [ 'order_id' => $order_id, 'order_number' => $order->get_order_number(), 'order_total' => $order->get_total(), 'currency' => $order->get_currency(), 'payment_method' => $order->get_payment_method(), 'item_count' => $order->get_item_count(), 'order_items' => $order_items, 'customer_id' => $order->get_customer_id(), 'detected_via' => 'woocommerce_hook' ], null, [ 'producer' => 'woocommerce_order_background', 'session_id' => $session_id, 'wp_user_id' => $customer_id, 'is_admin_user' => $is_admin_user, 'is_internal' => $is_admin_user && !vasp_event_should_ignore_internal_traffic(), 'event_uid' => hash('sha256', 'order.completed|order|' . (int) $order_id), ]); } } // Initialize the WooCommerce integration function vasp_init_woocommerce_integration() { // Prevent multiple initializations per request static $initialized = false; if ($initialized) { return; } $initialized = true; // Hook registration is local and cheap. The recorder checks the canonical // setting only when WooCommerce produces an actual event. if (class_exists('WooCommerce')) { new VASP_WooCommerce_Integration(); } } // Hook into WordPress initialization