Commit 0936f91c5c6 for woocommerce

commit 0936f91c5c687f39700edbfe57baee6956955802
Author: Chi-Hsuan Huang <chihsuan.tw@gmail.com>
Date:   Wed Dec 2 14:16:14 2026 +0800

    Add a random order reference to analytics purchase events (#71633)

    * Link purchase events to their order with a random order reference

    * Add changelog entry for purchase event order references

    * Keep order references unique per order and erasable after tracking stops

    * Reword changelog entry for purchase event order references

    * Queue order reference hooks when loaded before WordPress, fix README

    * Sync erased order references to HPOS when posts are authoritative

    * Simplify order reference parsing and cover eraser and lookup edge cases

    * Clarify which events carry oi and shorten the changelog entry

    * Leave order reference lookup to the report that needs it

    * Leave Woo Ads' order reference key to Woo Ads

    * Keep checkout safe on 32-bit PHP and erase references from trashed orders

diff --git a/packages/php/woocommerce-analytics/README.md b/packages/php/woocommerce-analytics/README.md
index 9cbd290c8cc..be6d24df5a8 100644
--- a/packages/php/woocommerce-analytics/README.md
+++ b/packages/php/woocommerce-analytics/README.md
@@ -137,6 +137,10 @@ If an optimization plugin delays the WP Consent API script, for example until th

 When WP Consent API is not active, the package defaults to allowing all tracking to maintain backward compatibility.

+### Order References
+
+Purchase events carry `order_id`, a random reference stored only in the order's `_wc_analytics_order_ref` meta. They also still carry the order number as `oi`; the order confirmation view event carries the WooCommerce order ID as `oi` and no `order_id`. Tools > Erase Personal Data and order anonymization remove the reference while a plugin that loads this package is active, even when the store no longer tracks. To resolve a reference, match it against the `Order_Reference::META_KEY` order meta. Woo Ads replaces `order_id` with its own reference, stored under its own meta key.
+
 ## Tracked Events

 ### Session Events
@@ -199,7 +203,8 @@ Each event includes contextual data such as:
 -   **User Data**: Customer ID (when available and permitted)
 -   **Session Information**: Session ID, engagement metrics
 -   **Page Context**: URL, referrer, breadcrumbs
--   **Store Data**: Order ID, payment method, shipping info
+-   **Store Data**: Order number or ID (`oi`), payment method, shipping info
+-   **Order Reference**: `order_id` on purchase events, a random number saved in the order's `_wc_analytics_order_ref` meta, not the WooCommerce order ID

 ## Architecture

@@ -209,6 +214,7 @@ Each event includes contextual data such as:
 -   **`Universal`** - Core tracking logic and WooCommerce hooks
 -   **`My_Account`** - Account-specific event tracking
 -   **`WC_Analytics_Tracking`** - Event queuing and processing
+-   **`Order_Reference`** - Random per-order reference on purchase events, and its privacy eraser
 -   **`Features`** - Feature flag management

 ### Frontend
diff --git a/packages/php/woocommerce-analytics/changelog/uni-1118-purchase-order-ref b/packages/php/woocommerce-analytics/changelog/uni-1118-purchase-order-ref
new file mode 100644
index 00000000000..2d9ec49b133
--- /dev/null
+++ b/packages/php/woocommerce-analytics/changelog/uni-1118-purchase-order-ref
@@ -0,0 +1,4 @@
+Significance: minor
+Type: added
+
+Add a random order reference to purchase events, and remove it when a shopper's data is erased.
diff --git a/packages/php/woocommerce-analytics/composer.json b/packages/php/woocommerce-analytics/composer.json
index 4494dcb126d..1df6f28fbce 100644
--- a/packages/php/woocommerce-analytics/composer.json
+++ b/packages/php/woocommerce-analytics/composer.json
@@ -22,6 +22,9 @@
 	"autoload": {
 		"classmap": [
 			"src/"
+		],
+		"files": [
+			"src/actions.php"
 		]
 	},
 	"scripts": {
diff --git a/packages/php/woocommerce-analytics/src/actions.php b/packages/php/woocommerce-analytics/src/actions.php
new file mode 100644
index 00000000000..e68949d226f
--- /dev/null
+++ b/packages/php/woocommerce-analytics/src/actions.php
@@ -0,0 +1,19 @@
+<?php
+/**
+ * Hooks registered whenever the package is loaded.
+ *
+ * @package automattic/woocommerce-analytics
+ */
+
+// Not in Woocommerce_Analytics::init(): consumers skip init() once a store stops tracking, but its orders keep their references.
+if ( function_exists( 'add_action' ) ) {
+	Automattic\Woocommerce_Analytics\Order_Reference::init_hooks();
+} else {
+	// Loaded before WordPress's plugin API; WP_Hook::build_preinitialized_hooks() picks this up.
+	global $wp_filter;
+	// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
+	$wp_filter['plugins_loaded'][10][] = array(
+		'accepted_args' => 0,
+		'function'      => array( Automattic\Woocommerce_Analytics\Order_Reference::class, 'init_hooks' ),
+	);
+}
diff --git a/packages/php/woocommerce-analytics/src/class-order-reference.php b/packages/php/woocommerce-analytics/src/class-order-reference.php
new file mode 100644
index 00000000000..df58ed892b4
--- /dev/null
+++ b/packages/php/woocommerce-analytics/src/class-order-reference.php
@@ -0,0 +1,209 @@
+<?php
+/**
+ * The random number an order is known by in WooCommerce Analytics events.
+ *
+ * @package automattic/woocommerce-analytics
+ */
+
+namespace Automattic\Woocommerce_Analytics;
+
+use WC_Order;
+
+/**
+ * Names an order on purchase events with a random number instead of its id. Only the order's meta
+ * maps the number back to the order, and erasing the shopper's personal data removes it.
+ *
+ * @since 0.20.0
+ */
+class Order_Reference {
+
+	/**
+	 * Order meta key holding the reference.
+	 */
+	const META_KEY = '_wc_analytics_order_ref';
+
+	/**
+	 * Largest reference handed out: 2^53 - 1, so it stays exact through any JSON reader.
+	 */
+	const MAX = 9007199254740991;
+
+	/**
+	 * Orders the privacy eraser handles per page.
+	 */
+	const ERASER_BATCH_SIZE = 10;
+
+	/**
+	 * Register the hooks that keep the reference unique to its order and remove it on erasure.
+	 */
+	public static function init_hooks() {
+		add_filter( 'wp_privacy_personal_data_erasers', array( __CLASS__, 'register_eraser' ) );
+		add_action( 'woocommerce_privacy_before_remove_order_personal_data', array( __CLASS__, 'forget' ) );
+		add_filter( 'wc_subscriptions_object_data', array( __CLASS__, 'exclude_from_copy' ) );
+	}
+
+	/**
+	 * Keep WooCommerce Subscriptions from copying the reference onto subscriptions and renewal orders.
+	 *
+	 * @param array $data Meta to copy, keyed by meta key.
+	 * @return array
+	 */
+	public static function exclude_from_copy( $data ) {
+		if ( is_array( $data ) ) {
+			unset( $data[ self::META_KEY ] );
+		}
+
+		return $data;
+	}
+
+	/**
+	 * The order's reference, created and saved on first use. Null on 32-bit PHP, which cannot hold MAX as an int.
+	 *
+	 * @param WC_Order $order The order.
+	 * @return int|null
+	 */
+	public static function for_order( WC_Order $order ) {
+		if ( PHP_INT_SIZE < 8 ) {
+			return null;
+		}
+		$reference = self::get( $order );
+		if ( null !== $reference ) {
+			return $reference;
+		}
+
+		$reference = wp_rand( 1, self::MAX );
+		$order->update_meta_data( self::META_KEY, (string) $reference );
+		self::save_meta( $order );
+
+		return $reference;
+	}
+
+	/**
+	 * The reference stored on the order, if any.
+	 *
+	 * @param WC_Order $order The order.
+	 * @return int|null
+	 */
+	public static function get( WC_Order $order ) {
+		return self::parse( $order->get_meta( self::META_KEY, true, 'edit' ) );
+	}
+
+	/**
+	 * Drop the order's reference. The caller saves the order.
+	 *
+	 * @param WC_Order $order The order.
+	 * @return bool Whether it had one.
+	 */
+	public static function forget( $order ) {
+		if ( ! $order instanceof WC_Order || ! $order->meta_exists( self::META_KEY ) ) {
+			return false;
+		}
+		$order->delete_meta_data( self::META_KEY );
+
+		return true;
+	}
+
+	/**
+	 * Add the eraser that removes references from a shopper's orders.
+	 *
+	 * @param array $erasers Registered erasers.
+	 * @return array
+	 */
+	public static function register_eraser( $erasers ) {
+		if ( ! is_array( $erasers ) || ! function_exists( 'wc_get_orders' ) ) {
+			return $erasers;
+		}
+		$erasers['woocommerce-analytics-order-reference'] = array(
+			'eraser_friendly_name' => __( 'WooCommerce Analytics order references', 'woocommerce-analytics' ),
+			'callback'             => array( __CLASS__, 'erase' ),
+		);
+
+		return $erasers;
+	}
+
+	/**
+	 * Remove the references from one page of a shopper's orders.
+	 *
+	 * Runs whether or not the store removes personal data from orders, since the reference is
+	 * what ties the shopper's events in WooCommerce Analytics to the order.
+	 *
+	 * @param string $email_address The shopper's email address.
+	 * @param int    $page          Page, from 1.
+	 * @return array Eraser response.
+	 */
+	public static function erase( $email_address, $page = 1 ) {
+		$response = array(
+			'items_removed'  => false,
+			'items_retained' => false,
+			'messages'       => array(),
+			'done'           => true,
+		);
+		if ( ! function_exists( 'wc_get_orders' ) || ! is_string( $email_address ) || '' === $email_address ) {
+			return $response;
+		}
+
+		$customers = array( $email_address );
+		$user      = get_user_by( 'email', $email_address );
+		if ( $user instanceof \WP_User ) {
+			$customers[] = (int) $user->ID;
+		}
+
+		$orders = wc_get_orders(
+			array(
+				'limit'    => self::ERASER_BATCH_SIZE,
+				'page'     => max( 1, (int) $page ),
+				'customer' => $customers,
+				'status'   => array_merge( array_keys( wc_get_order_statuses() ), array( 'trash' ) ),
+			)
+		);
+		$orders = is_array( $orders ) ? $orders : array();
+
+		foreach ( $orders as $order ) {
+			if ( self::forget( $order ) ) {
+				// A full save bumps the modified date, so HPOS sync and storage switches see the removal.
+				$order->save();
+				$response['items_removed'] = true;
+			}
+		}
+		if ( $response['items_removed'] ) {
+			$response['messages'][] = __( 'Removed WooCommerce Analytics order references.', 'woocommerce-analytics' );
+		}
+		$response['done'] = count( $orders ) < self::ERASER_BATCH_SIZE;
+
+		return $response;
+	}
+
+	/**
+	 * Save the order's meta only, so its modified date and update hooks are left alone.
+	 *
+	 * @param WC_Order $order The order.
+	 */
+	private static function save_meta( WC_Order $order ) {
+		if ( $order->get_id() <= 0 ) {
+			return;
+		}
+		// Its own closure, so removing it cannot drop another plugin's identical `__return_false`.
+		$skip_full_save = static function () {
+			return false;
+		};
+		add_filter( 'woocommerce_orders_table_datastore_should_save_after_meta_change', $skip_full_save );
+		try {
+			$order->save_meta_data();
+		} finally {
+			remove_filter( 'woocommerce_orders_table_datastore_should_save_after_meta_change', $skip_full_save );
+		}
+	}
+
+	/**
+	 * A stored or passed-in reference as a positive integer, or null.
+	 *
+	 * @param mixed $value The value.
+	 * @return int|null
+	 */
+	private static function parse( $value ) {
+		if ( is_string( $value ) && ctype_digit( $value ) ) {
+			$value = (int) $value;
+		}
+
+		return is_int( $value ) && $value > 0 && $value <= self::MAX ? $value : null;
+	}
+}
diff --git a/packages/php/woocommerce-analytics/src/class-universal.php b/packages/php/woocommerce-analytics/src/class-universal.php
index 276bc4913e3..ad1e85674a6 100644
--- a/packages/php/woocommerce-analytics/src/class-universal.php
+++ b/packages/php/woocommerce-analytics/src/class-universal.php
@@ -361,6 +361,10 @@ class Universal {
 			$checkout_page_contains_checkout_shortcode = '1';
 		}

+		// Set before the event props filter runs, so a callback (Woo Ads) can still replace it.
+		$order_reference       = WC_Analytics_Tracking::can_record_events() ? Order_Reference::for_order( $order ) : null;
+		$order_reference_props = null === $order_reference ? array() : array( 'order_id' => (string) $order_reference );
+
 		// loop through products in the order and queue a purchase event.
 		foreach ( $order->get_items() as $order_item ) {
 			// @phan-suppress-next-line PhanUndeclaredMethod -- Checked before being called. See also https://github.com/phan/phan/issues/1204.
@@ -395,7 +399,7 @@ class Universal {
 						'from_checkout'            => $checkout_page_used,
 						'checkout_page_contains_checkout_block' => $checkout_page_contains_checkout_block,
 						'checkout_page_contains_checkout_shortcode' => $checkout_page_contains_checkout_shortcode,
-					)
+					) + $order_reference_props
 				)
 			);
 		}
diff --git a/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php b/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php
index 7c8f327fa87..d2b5aebc23b 100644
--- a/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php
+++ b/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php
@@ -61,6 +61,15 @@ class WC_Analytics_Tracking {
 	 */
 	const RESERVED_IDENTITY_PROPERTIES = array( '_ui', '_ut', '_en', '_ts', 'browser_type' );

+	/**
+	 * Event property names only the server sets, such as the order reference on purchase events.
+	 *
+	 * @since 0.20.0
+	 *
+	 * @var string[]
+	 */
+	const SERVER_EVENT_PROPERTIES = array( 'order_id' );
+
 	/**
 	 * Maximum number of events a single client request may record.
 	 *
@@ -178,6 +187,26 @@ class WC_Analytics_Tracking {
 	 */
 	private static $reserved_property_names = null;

+	/**
+	 * Whether record_event() sends events for this request: the shopper consented, is not a bot, and has a stable visitor id.
+	 *
+	 * @since 0.20.0
+	 *
+	 * @return bool
+	 */
+	public static function can_record_events() {
+		if ( ! Consent_Manager::has_analytics_consent() ) {
+			return false;
+		}
+
+		if ( User_Agent_Info::is_bot() ) {
+			return false;
+		}
+
+		// No stable visitor id (e.g. no tk_ai cookie); see get_visitor_id().
+		return ! empty( self::get_visitor_id() );
+	}
+
 	/**
 	 * Record an event in Tracks and ClickHouse (If enabled).
 	 *
@@ -195,21 +224,10 @@ class WC_Analytics_Tracking {
 	 *                       event name, or if the pixel could not be built or fired.
 	 */
 	public static function record_event( $event_name, $event_properties = array(), $is_client_supplied = false ) {
-		// Check consent before recording any event.
-		if ( ! Consent_Manager::has_analytics_consent() ) {
+		if ( ! self::can_record_events() ) {
 			return true; // Skip recording.
 		}

-		// Skip recording if the request is coming from a bot.
-		if ( User_Agent_Info::is_bot() ) {
-			return true;
-		}
-
-		// Skip events that arrive without a stable visitor id (e.g. no tk_ai cookie); see get_visitor_id().
-		if ( empty( self::get_visitor_id() ) ) {
-			return true;
-		}
-
 		if ( $is_client_supplied ) {
 			// Report invalid names because they cannot produce an event.
 			if ( ! self::is_valid_client_name( $event_name ) ) {
@@ -682,7 +700,7 @@ class WC_Analytics_Tracking {
 		);

 		self::$reserved_property_names = array_values(
-			array_unique( array_merge( $server_owned, self::RESERVED_IDENTITY_PROPERTIES ) )
+			array_unique( array_merge( $server_owned, self::RESERVED_IDENTITY_PROPERTIES, self::SERVER_EVENT_PROPERTIES ) )
 		);

 		return self::$reserved_property_names;
diff --git a/packages/php/woocommerce-analytics/tests/php/Order_Reference_Test.php b/packages/php/woocommerce-analytics/tests/php/Order_Reference_Test.php
new file mode 100644
index 00000000000..0cb0f6d8067
--- /dev/null
+++ b/packages/php/woocommerce-analytics/tests/php/Order_Reference_Test.php
@@ -0,0 +1,344 @@
+<?php
+/**
+ * Tests for Order_Reference.
+ *
+ * @package automattic/woocommerce-analytics
+ */
+
+namespace Automattic\Woocommerce_Analytics;
+
+use WC_Order;
+use WorDBless\BaseTestCase;
+
+/**
+ * Tests for Order_Reference.
+ */
+class Order_Reference_Test extends BaseTestCase {
+
+	/**
+	 * Reset the wc_get_orders() mock.
+	 */
+	public function set_up(): void {
+		parent::set_up();
+		$this->reset_orders_mock();
+	}
+
+	/**
+	 * Reset the wc_get_orders() mock.
+	 */
+	public function tear_down(): void {
+		$this->reset_orders_mock();
+		parent::tear_down();
+	}
+
+	/**
+	 * Clear the wc_get_orders() mock state.
+	 */
+	private function reset_orders_mock(): void {
+		global $wc_get_orders_mock_return, $wc_get_orders_calls;
+		$wc_get_orders_mock_return = array();
+		$wc_get_orders_calls       = array();
+	}
+
+	/**
+	 * An order with the given id and meta.
+	 *
+	 * @param int   $id   Order id.
+	 * @param array $meta Meta, by key.
+	 * @return WC_Order
+	 */
+	private function order( int $id, array $meta = array() ): WC_Order {
+		$order = new WC_Order();
+		$order->set_id( $id );
+		foreach ( $meta as $key => $value ) {
+			$order->update_meta_data( $key, $value );
+		}
+		return $order;
+	}
+
+	/**
+	 * The first reference is random, stored as a string and saved once; later calls reuse it.
+	 */
+	public function test_for_order_creates_the_reference_once_and_reuses_it(): void {
+		$order = $this->order( 10 );
+
+		$reference = Order_Reference::for_order( $order );
+
+		$this->assertGreaterThanOrEqual( 1, $reference );
+		$this->assertLessThanOrEqual( Order_Reference::MAX, $reference );
+		$this->assertSame( (string) $reference, $order->get_meta( Order_Reference::META_KEY ) );
+		$this->assertSame( array( true ), $order->meta_saves_skipping_order_save, 'Only the meta is saved, not the whole order.' );
+		$this->assertFalse( has_filter( 'woocommerce_orders_table_datastore_should_save_after_meta_change' ) );
+
+		$this->assertSame( $reference, Order_Reference::for_order( $order ) );
+		$this->assertSame( 1, $order->meta_saves, 'An existing reference must not be saved again.' );
+	}
+
+	/**
+	 * Another plugin's `__return_false` on the same filter is still registered after the save.
+	 */
+	public function test_for_order_keeps_another_plugins_identical_filter_callback(): void {
+		add_filter( 'woocommerce_orders_table_datastore_should_save_after_meta_change', '__return_false' );
+
+		try {
+			Order_Reference::for_order( $this->order( 10 ) );
+
+			$this->assertSame( 10, has_filter( 'woocommerce_orders_table_datastore_should_save_after_meta_change', '__return_false' ) );
+		} finally {
+			remove_filter( 'woocommerce_orders_table_datastore_should_save_after_meta_change', '__return_false' );
+		}
+	}
+
+	/**
+	 * A stored reference is reused even when a view-context filter hides it.
+	 */
+	public function test_for_order_reuses_a_reference_hidden_by_a_view_filter(): void {
+		$order = $this->order( 10, array( Order_Reference::META_KEY => '11' ) );
+		add_filter( 'woocommerce_order_get_' . Order_Reference::META_KEY, '__return_empty_string' );
+
+		try {
+			$this->assertSame( 11, Order_Reference::for_order( $order ) );
+			$this->assertSame( 0, $order->meta_saves );
+		} finally {
+			remove_filter( 'woocommerce_order_get_' . Order_Reference::META_KEY, '__return_empty_string' );
+		}
+	}
+
+	/**
+	 * An order that is not in the database yet keeps the reference in memory only.
+	 */
+	public function test_for_order_does_not_save_an_unsaved_order(): void {
+		$order = $this->order( 0 );
+
+		$reference = Order_Reference::for_order( $order );
+
+		$this->assertSame( $reference, Order_Reference::get( $order ) );
+		$this->assertSame( 0, $order->meta_saves );
+	}
+
+	/**
+	 * Stored values that are not a positive integer within range read as no reference.
+	 *
+	 * @dataProvider invalid_stored_values
+	 *
+	 * @param mixed $value Stored value.
+	 */
+	public function test_get_ignores_invalid_stored_values( $value ): void {
+		$this->assertNull( Order_Reference::get( $this->order( 10, array( Order_Reference::META_KEY => $value ) ) ) );
+	}
+
+	/**
+	 * Invalid stored values.
+	 *
+	 * @return array
+	 */
+	public function invalid_stored_values(): array {
+		return array(
+			'empty'        => array( '' ),
+			'zero'         => array( '0' ),
+			'negative'     => array( '-5' ),
+			'not a number' => array( 'abc' ),
+			'over the max' => array( '9007199254740992' ),
+			'too long'     => array( '12345678901234567890' ),
+			'array'        => array( array( '5' ) ),
+			'zero int'     => array( 0 ),
+			'over max int' => array( Order_Reference::MAX + 1 ),
+		);
+	}
+
+	/**
+	 * The largest reference reads back, stored as a string or an int.
+	 */
+	public function test_get_accepts_the_largest_reference(): void {
+		$this->assertSame( Order_Reference::MAX, Order_Reference::get( $this->order( 10, array( Order_Reference::META_KEY => (string) Order_Reference::MAX ) ) ) );
+		$this->assertSame( Order_Reference::MAX, Order_Reference::get( $this->order( 10, array( Order_Reference::META_KEY => Order_Reference::MAX ) ) ) );
+	}
+
+	/**
+	 * Forgetting removes only the package's reference, not Woo Ads' own, which Woo Ads erases itself.
+	 */
+	public function test_forget_removes_the_reference(): void {
+		$order = $this->order(
+			1,
+			array(
+				Order_Reference::META_KEY => '11',
+				'_woo_ads_order_ref'      => '22',
+			)
+		);
+
+		$this->assertTrue( Order_Reference::forget( $order ) );
+		$this->assertSame( '', $order->get_meta( Order_Reference::META_KEY ) );
+		$this->assertSame( '22', $order->get_meta( '_woo_ads_order_ref' ) );
+		$this->assertFalse( Order_Reference::forget( $order ) );
+		$this->assertFalse( Order_Reference::forget( 'not an order' ) );
+	}
+
+	/**
+	 * The stored key is removed even when a view-context filter hides its value, or the value is not a valid reference.
+	 */
+	public function test_forget_removes_the_key_whatever_its_value_reads_as(): void {
+		$filtered = $this->order( 1, array( Order_Reference::META_KEY => '11' ) );
+		$invalid  = $this->order( 2, array( Order_Reference::META_KEY => 'garbage' ) );
+		add_filter( 'woocommerce_order_get_' . Order_Reference::META_KEY, '__return_empty_string' );
+
+		try {
+			$this->assertTrue( Order_Reference::forget( $filtered ) );
+			$this->assertTrue( Order_Reference::forget( $invalid ) );
+		} finally {
+			remove_filter( 'woocommerce_order_get_' . Order_Reference::META_KEY, '__return_empty_string' );
+		}
+		$this->assertFalse( $filtered->meta_exists( Order_Reference::META_KEY ) );
+		$this->assertFalse( $invalid->meta_exists( Order_Reference::META_KEY ) );
+	}
+
+	/**
+	 * Loading the package registers the hooks, since consumers skip init() once a store stops tracking.
+	 */
+	public function test_loading_the_package_registers_the_hooks(): void {
+		remove_all_filters( 'wp_privacy_personal_data_erasers' );
+		remove_all_actions( 'woocommerce_privacy_before_remove_order_personal_data' );
+		remove_all_filters( 'wc_subscriptions_object_data' );
+
+		require __DIR__ . '/../../src/actions.php';
+
+		$this->assertNotFalse( has_filter( 'wp_privacy_personal_data_erasers', array( Order_Reference::class, 'register_eraser' ) ) );
+		$this->assertNotFalse( has_action( 'woocommerce_privacy_before_remove_order_personal_data', array( Order_Reference::class, 'forget' ) ) );
+		$this->assertNotFalse( has_filter( 'wc_subscriptions_object_data', array( Order_Reference::class, 'exclude_from_copy' ) ) );
+	}
+
+	/**
+	 * Loaded before WordPress's plugin API, the file queues the hooks for plugins_loaded instead of dropping them.
+	 */
+	public function test_loading_the_package_before_wordpress_queues_the_hooks(): void {
+		if ( ! function_exists( 'shell_exec' ) ) {
+			$this->markTestSkipped( 'Needs shell_exec to load the file in a fresh PHP process.' );
+		}
+		$file   = escapeshellarg( realpath( __DIR__ . '/../../src/actions.php' ) );
+		$script = escapeshellarg( 'require ' . $file . '; echo json_encode( $GLOBALS["wp_filter"] );' );
+		$output = shell_exec( escapeshellarg( PHP_BINARY ) . ' -r ' . $script ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.system_calls_shell_exec
+
+		$this->assertSame(
+			array(
+				'plugins_loaded' => array(
+					10 => array(
+						array(
+							'accepted_args' => 0,
+							'function'      => array( Order_Reference::class, 'init_hooks' ),
+						),
+					),
+				),
+			),
+			json_decode( (string) $output, true )
+		);
+	}
+
+	/**
+	 * Subscriptions copies a parent order's meta onto the subscription and its renewals; the reference must stay on the parent.
+	 */
+	public function test_subscriptions_does_not_copy_the_reference(): void {
+		Order_Reference::init_hooks();
+		$data = array(
+			Order_Reference::META_KEY => '11',
+			'_billing_email'          => 'shopper@example.com',
+		);
+
+		$this->assertSame(
+			array( '_billing_email' => 'shopper@example.com' ),
+			apply_filters( 'wc_subscriptions_object_data', $data, null, null, 'subscription' )
+		);
+		$this->assertSame( 'not an array', Order_Reference::exclude_from_copy( 'not an array' ) );
+	}
+
+	/**
+	 * The eraser is registered alongside the others.
+	 */
+	public function test_eraser_is_registered(): void {
+		Order_Reference::init_hooks();
+
+		$erasers = apply_filters( 'wp_privacy_personal_data_erasers', array( 'other' => array() ) );
+
+		$this->assertArrayHasKey( 'other', $erasers );
+		$this->assertSame( array( Order_Reference::class, 'erase' ), $erasers['woocommerce-analytics-order-reference']['callback'] );
+		$this->assertSame( 'not an array', Order_Reference::register_eraser( 'not an array' ) );
+	}
+
+	/**
+	 * The eraser removes the references of the shopper's orders, trashed ones included, and fully saves each.
+	 */
+	public function test_erase_removes_references_from_the_shoppers_orders(): void {
+		global $wc_get_orders_mock_return, $wc_get_orders_calls;
+		$with                      = $this->order( 1, array( Order_Reference::META_KEY => '11' ) );
+		$without                   = $this->order( 2 );
+		$wc_get_orders_mock_return = array( $with, $without );
+
+		$response = Order_Reference::erase( 'shopper@example.com', 1 );
+
+		$this->assertTrue( $response['items_removed'] );
+		$this->assertFalse( $response['items_retained'] );
+		$this->assertTrue( $response['done'] );
+		$this->assertCount( 1, $response['messages'] );
+		$this->assertNull( Order_Reference::get( $with ) );
+		$this->assertSame( 1, $with->saves, 'A full save bumps the modified date, so HPOS sync sees the removal.' );
+		$this->assertSame( 0, $with->meta_saves );
+		$this->assertSame( 0, $without->saves );
+		$this->assertSame( array( 'shopper@example.com' ), $wc_get_orders_calls[0]['args']['customer'] );
+		$this->assertSame( 1, $wc_get_orders_calls[0]['args']['page'] );
+		$this->assertSame(
+			array_merge( array_keys( wc_get_order_statuses() ), array( 'trash' ) ),
+			$wc_get_orders_calls[0]['args']['status']
+		);
+	}
+
+	/**
+	 * A registered shopper's orders are also found by account, not only by billing email.
+	 */
+	public function test_erase_also_looks_up_orders_by_the_shoppers_account(): void {
+		global $wc_get_orders_calls;
+		$user_id = wp_insert_user(
+			array(
+				'user_login' => 'shopper',
+				'user_email' => 'registered@example.com',
+				'user_pass'  => 'secret',
+			)
+		);
+		$this->assertIsInt( $user_id );
+
+		Order_Reference::erase( 'registered@example.com', 1 );
+
+		$this->assertSame( array( 'registered@example.com', $user_id ), $wc_get_orders_calls[0]['args']['customer'] );
+	}
+
+	/**
+	 * A full page asks WordPress for the next one; nothing found removes nothing.
+	 */
+	public function test_erase_pages_through_orders(): void {
+		global $wc_get_orders_mock_return, $wc_get_orders_calls;
+		$wc_get_orders_mock_return = array_map(
+			function ( $id ) {
+				return $this->order( $id );
+			},
+			range( 1, Order_Reference::ERASER_BATCH_SIZE )
+		);
+
+		$response = Order_Reference::erase( 'shopper@example.com', 2 );
+		Order_Reference::erase( 'shopper@example.com', 0 );
+
+		$this->assertFalse( $response['done'] );
+		$this->assertFalse( $response['items_removed'] );
+		$this->assertSame( array(), $response['messages'] );
+		$this->assertSame( array( 2, 1 ), array_column( array_column( $wc_get_orders_calls, 'args' ), 'page' ) );
+	}
+
+	/**
+	 * Without an email there is no shopper to look up, so no query runs.
+	 */
+	public function test_erase_does_nothing_without_an_email(): void {
+		global $wc_get_orders_calls;
+
+		$response = Order_Reference::erase( '', 1 );
+
+		$this->assertTrue( $response['done'] );
+		$this->assertFalse( $response['items_removed'] );
+		$this->assertCount( 0, $wc_get_orders_calls );
+	}
+}
diff --git a/packages/php/woocommerce-analytics/tests/php/Universal_Test.php b/packages/php/woocommerce-analytics/tests/php/Universal_Test.php
index 98adcefb008..289a9832f84 100644
--- a/packages/php/woocommerce-analytics/tests/php/Universal_Test.php
+++ b/packages/php/woocommerce-analytics/tests/php/Universal_Test.php
@@ -224,15 +224,173 @@ class Universal_Test extends BaseTestCase {
 		);
 	}

+	/**
+	 * An order with two line items that order_process() will load.
+	 *
+	 * @return WC_Order
+	 */
+	private function two_item_order(): WC_Order {
+		global $wc_get_order_mock_return;
+		$item = static function ( $product_id ) {
+			return new class( $product_id ) {
+				/**
+				 * Product id.
+				 *
+				 * @var int
+				 */
+				private $product_id;
+
+				/**
+				 * Constructor.
+				 *
+				 * @param int $product_id Product id.
+				 */
+				public function __construct( $product_id ) {
+					$this->product_id = $product_id;
+				}
+
+				/**
+				 * Product id.
+				 *
+				 * @return int
+				 */
+				public function get_product_id() {
+					return $this->product_id;
+				}
+
+				/**
+				 * Quantity.
+				 *
+				 * @return int
+				 */
+				public function get_quantity() {
+					return 1;
+				}
+			};
+		};
+
+		$order = new WC_Order();
+		$order->set_id( 77 );
+		$order->set_items( array( $item( 5 ), $item( 6 ) ) );
+		$wc_get_order_mock_return = $order;
+
+		return $order;
+	}
+
+	/**
+	 * Query params of each queued pixel.
+	 *
+	 * @return array[]
+	 */
+	private function queued_pixel_props(): array {
+		return array_map(
+			static function ( $url ) {
+				$props = array();
+				parse_str( (string) wp_parse_url( $url, PHP_URL_QUERY ), $props );
+				return $props;
+			},
+			$this->get_pixel_batch_queue()
+		);
+	}
+
+	/**
+	 * Every purchase line of an order carries the order's reference, and a second run reuses it.
+	 */
+	public function test_order_process_sends_the_same_order_reference_on_every_line(): void {
+		$_COOKIE['tk_ai'] = 'test-visitor-id-1234567890ab';
+		$this->reset_pixel_batch_queue();
+		$order = $this->two_item_order();
+
+		try {
+			( new Universal() )->order_process( 77 );
+			( new Universal() )->order_process( 77 );
+			$props = $this->queued_pixel_props();
+		} finally {
+			unset( $_COOKIE['tk_ai'] );
+			$this->reset_pixel_batch_queue();
+		}
+
+		$reference = $order->get_meta( Order_Reference::META_KEY );
+		$this->assertMatchesRegularExpression( '/^[1-9]\d{0,15}$/', $reference );
+		$this->assertCount( 4, $props );
+		foreach ( $props as $line ) {
+			$this->assertSame( 'woocommerceanalytics_product_purchase', $line['_en'] );
+			$this->assertSame( $reference, $line['order_id'] );
+			$this->assertSame( '123', $line['oi'], '`oi` is unchanged.' );
+		}
+	}
+
+	/**
+	 * A callback on the event props filter can replace the reference, as Woo Ads does.
+	 */
+	public function test_order_process_lets_the_event_props_filter_replace_the_order_reference(): void {
+		$_COOKIE['tk_ai'] = 'test-visitor-id-1234567890ab';
+		$this->reset_pixel_batch_queue();
+		$this->two_item_order();
+		$replace = static function ( $props, $event_name ) {
+			if ( 'woocommerceanalytics_product_purchase' === $event_name ) {
+				$props['order_id'] = '42';
+			}
+			return $props;
+		};
+		add_filter( 'jetpack_woocommerce_analytics_event_props', $replace, 10, 2 );
+
+		try {
+			( new Universal() )->order_process( 77 );
+			$props = $this->queued_pixel_props();
+		} finally {
+			remove_filter( 'jetpack_woocommerce_analytics_event_props', $replace, 10 );
+			unset( $_COOKIE['tk_ai'] );
+			$this->reset_pixel_batch_queue();
+		}
+
+		$this->assertSame( array( '42', '42' ), array_column( $props, 'order_id' ) );
+	}
+
+	/**
+	 * Without a visitor id no event goes out, so the order gets no reference.
+	 */
+	public function test_order_process_writes_no_reference_when_no_event_is_sent(): void {
+		$this->reset_pixel_batch_queue();
+		$order = $this->two_item_order();
+
+		( new Universal() )->order_process( 77 );
+
+		$this->assertSame( array(), $this->get_pixel_batch_queue() );
+		$this->assertSame( '', $order->get_meta( Order_Reference::META_KEY ) );
+		$this->assertSame( 0, $order->meta_saves );
+	}
+
+	/**
+	 * A shopper who denied statistics gets no event and no reference on their order.
+	 *
+	 * @runInSeparateProcess
+	 * @preserveGlobalState disabled
+	 */
+	public function test_order_process_writes_no_reference_without_consent(): void {
+		require_once __DIR__ . '/mocks/wp-has-consent-function.php';
+		$_COOKIE['tk_ai'] = 'test-visitor-id-1234567890ab';
+		$order            = $this->two_item_order();
+
+		( new Universal() )->order_process( 77 );
+
+		$this->assertSame( array(), $this->get_pixel_batch_queue() );
+		$this->assertSame( '', $order->get_meta( Order_Reference::META_KEY ) );
+	}
+
 	/**
 	 * Reset the WC_Analytics_Tracking::$pixel_batch_queue static so each
-	 * test starts from a known-empty state.
+	 * test starts from a known-empty state, along with the cached visitor id.
 	 */
 	private function reset_pixel_batch_queue(): void {
 		$reflection = new \ReflectionClass( WC_Analytics_Tracking::class );
 		$queue      = $reflection->getProperty( 'pixel_batch_queue' );
 		$queue->setAccessible( true );
 		$queue->setValue( null, array() );
+
+		$visitor = $reflection->getProperty( 'cached_visitor_id' );
+		$visitor->setAccessible( true );
+		$visitor->setValue( null, null );
 	}

 	/**
diff --git a/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Reserved_Props_Test.php b/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Reserved_Props_Test.php
index f44017d673c..eae97719fba 100644
--- a/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Reserved_Props_Test.php
+++ b/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Reserved_Props_Test.php
@@ -105,6 +105,8 @@ class WC_Analytics_Tracking_Reserved_Props_Test extends BaseTestCase {
 			'_en',
 			'_ts',
 			'browser_type',
+			// SERVER_EVENT_PROPERTIES.
+			'order_id',
 		);

 		$actual = WC_Analytics_Tracking::get_reserved_property_names();
@@ -284,6 +286,35 @@ class WC_Analytics_Tracking_Reserved_Props_Test extends BaseTestCase {
 		unset( $_COOKIE['tk_ai'] );
 	}

+	/**
+	 * A client cannot send an order reference, but a server-side filter callback can still add one.
+	 */
+	public function test_record_client_event_drops_a_client_order_reference_but_keeps_a_filtered_one(): void {
+		$_COOKIE['tk_ai'] = 'test-visitor-id-1234567890ab';
+		$this->reset_pixel_batch_queue();
+
+		WC_Analytics_Tracking::record_client_event( 'product_purchase', array( 'order_id' => '12345' ) );
+		$client_only = $this->get_queued_pixel_props();
+
+		$this->reset_pixel_batch_queue();
+		$add = static function ( $props ) {
+			$props['order_id'] = '42';
+			return $props;
+		};
+		add_filter( 'jetpack_woocommerce_analytics_event_props', $add );
+		try {
+			WC_Analytics_Tracking::record_client_event( 'product_purchase', array( 'order_id' => '12345' ) );
+			$filtered = $this->get_queued_pixel_props();
+		} finally {
+			remove_filter( 'jetpack_woocommerce_analytics_event_props', $add );
+			$this->reset_pixel_batch_queue();
+			unset( $_COOKIE['tk_ai'] );
+		}
+
+		$this->assertArrayNotHasKey( 'order_id', $client_only );
+		$this->assertSame( '42', $filtered['order_id'] ?? null );
+	}
+
 	/**
 	 * The three client-authoritative properties must survive to the pixel,
 	 * otherwise proxy-mode page attribution breaks: the server's values would
diff --git a/packages/php/woocommerce-analytics/tests/php/mocks/class-wc-order.php b/packages/php/woocommerce-analytics/tests/php/mocks/class-wc-order.php
index af6810c047a..0a565409808 100644
--- a/packages/php/woocommerce-analytics/tests/php/mocks/class-wc-order.php
+++ b/packages/php/woocommerce-analytics/tests/php/mocks/class-wc-order.php
@@ -31,6 +31,101 @@ if ( ! class_exists( 'WC_Order' ) ) {
 		 */
 		private $coupons = array();

+		/**
+		 * Order meta, by key.
+		 *
+		 * @var array
+		 */
+		private $meta = array();
+
+		/**
+		 * Number of save_meta_data() calls.
+		 *
+		 * @var int
+		 */
+		public $meta_saves = 0;
+
+		/**
+		 * For each save_meta_data() call, whether HPOS's save-after-meta-change filter returned false.
+		 *
+		 * @var bool[]
+		 */
+		public $meta_saves_skipping_order_save = array();
+
+		/**
+		 * Number of save() calls.
+		 *
+		 * @var int
+		 */
+		public $saves = 0;
+
+		/**
+		 * Set order ID for testing.
+		 *
+		 * @param int $id Order ID.
+		 */
+		public function set_id( $id ) {
+			$this->id = $id;
+		}
+
+		/**
+		 * Get a meta value, filtered in view context as WC_Data::get_meta() does.
+		 *
+		 * @param string $key     Meta key.
+		 * @param bool   $single  Unused; always single.
+		 * @param string $context 'view' or 'edit'.
+		 * @return mixed
+		 */
+		public function get_meta( $key, $single = true, $context = 'view' ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
+			$value = $this->meta[ $key ] ?? '';
+
+			return 'view' === $context ? apply_filters( 'woocommerce_order_get_' . $key, $value, $this ) : $value;
+		}
+
+		/**
+		 * Whether a meta key is set.
+		 *
+		 * @param string $key Meta key.
+		 * @return bool
+		 */
+		public function meta_exists( $key ) {
+			return array_key_exists( $key, $this->meta );
+		}
+
+		/**
+		 * Set a meta value.
+		 *
+		 * @param string $key   Meta key.
+		 * @param mixed  $value Meta value.
+		 */
+		public function update_meta_data( $key, $value ) {
+			$this->meta[ $key ] = $value;
+		}
+
+		/**
+		 * Delete a meta value.
+		 *
+		 * @param string $key Meta key.
+		 */
+		public function delete_meta_data( $key ) {
+			unset( $this->meta[ $key ] );
+		}
+
+		/**
+		 * Count meta saves.
+		 */
+		public function save_meta_data() {
+			++$this->meta_saves;
+			$this->meta_saves_skipping_order_save[] = false === apply_filters( 'woocommerce_orders_table_datastore_should_save_after_meta_change', true );
+		}
+
+		/**
+		 * Count full saves.
+		 */
+		public function save() {
+			++$this->saves;
+		}
+
 		/**
 		 * Get order ID.
 		 *
diff --git a/packages/php/woocommerce-analytics/tests/php/mocks/woocommerce-functions.php b/packages/php/woocommerce-analytics/tests/php/mocks/woocommerce-functions.php
index b97d7ae1f91..7f604ab4c50 100644
--- a/packages/php/woocommerce-analytics/tests/php/mocks/woocommerce-functions.php
+++ b/packages/php/woocommerce-analytics/tests/php/mocks/woocommerce-functions.php
@@ -45,6 +45,67 @@ if ( ! function_exists( 'wc_get_order' ) ) {
 	}
 }

+/**
+ * Orders wc_get_orders() returns.
+ *
+ * @var array
+ */
+global $wc_get_orders_mock_return;
+$wc_get_orders_mock_return = array();
+
+/**
+ * Arguments of each wc_get_orders() call, under `args`.
+ *
+ * @var array
+ */
+global $wc_get_orders_calls;
+$wc_get_orders_calls = array();
+
+if ( ! function_exists( 'wc_get_orders' ) ) {
+	/**
+	 * Mock wc_get_orders function.
+	 *
+	 * @param array $args Query arguments.
+	 * @return array The mocked orders.
+	 */
+	function wc_get_orders( $args = array() ) {
+		global $wc_get_orders_mock_return, $wc_get_orders_calls;
+		$wc_get_orders_calls[] = array( 'args' => $args );
+		return $wc_get_orders_mock_return;
+	}
+}
+
+if ( ! function_exists( 'wc_get_order_statuses' ) ) {
+	/**
+	 * Mock wc_get_order_statuses function: WooCommerce's default statuses, without trash.
+	 *
+	 * @return array
+	 */
+	function wc_get_order_statuses() {
+		return array(
+			'wc-pending'    => 'Pending payment',
+			'wc-processing' => 'Processing',
+			'wc-on-hold'    => 'On hold',
+			'wc-completed'  => 'Completed',
+			'wc-cancelled'  => 'Cancelled',
+			'wc-refunded'   => 'Refunded',
+			'wc-failed'     => 'Failed',
+		);
+	}
+}
+
+if ( ! function_exists( 'wc_get_product' ) ) {
+	/**
+	 * Mock wc_get_product function: no product.
+	 *
+	 * @param mixed $the_product Product id or object.
+	 * @return null
+	 */
+	function wc_get_product( $the_product = false ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
+		return null;
+	}
+}
+
 if ( ! function_exists( 'WC' ) ) {
 	/**
 	 * Mock WC function.