Skip to content

Conversation

@chihsuan
Copy link
Member

@chihsuan chihsuan commented Jan 8, 2026

Related to WOOA7S-929

Problem

The product_checkout event currently fires every time the checkout page loads, causing duplicate events on page refresh. This is inconsistent with the product_purchase event, which only fires on the final purchase. Since two events are often analyzed together, this inconsistency can lead to misleading insights.

Current behavior:

  • User visits checkout → event fires ✓
  • User refreshes page → event fires again ✗ (duplicate)
  • User refreshes again → event fires again ✗ (duplicate)

Expected behavior:

  • User visits checkout → event fires ✓
  • User refreshes page → no event (same cart, same session)
  • User modifies cart → event fires again ✓ (cart changed)

Proposed changes:

  • Deduplicate product_checkout events using WC Session storage to track if checkout has already been recorded for the current cart state
  • Fire product_checkout PHP-side via record_event() for consistency with product_purchase event (both now fire server-side)
  • Reset tracking state automatically when cart changes (add/remove items, quantity updates) via WooCommerce hooks
  • Include JS session ID tracking for sessionTracking feature support - when a new JS session starts, events fire again to capture the new session

Technical approach

  1. Store a wca_checkout_tracked flag in WC Session when product_checkout fires
  2. On subsequent checkout page loads, check if flag is set - if so, skip firing events
  3. Hook into cart modification actions to reset the flag when cart changes
  4. Optionally track JS session ID to detect session changes (when ClickHouse/sessionTracking is enabled)

Other information:

  • Have you written new tests for your changes, if applicable?
  • Have you checked the E2E test CI results, and verified that your changes do not break them?
  • Have you tested your changes on WordPress.com, if applicable (if so, you'll see a generated comment below with a script to run)?

Jetpack product discussion

Does this pull request change what data or activity we track or use?

No, this PR does not change what data we track. It reduces duplicate events while preserving meaningful tracking:

  • Events still fire on first checkout page visit
  • Events still fire when cart changes (add/remove/quantity update)
  • Events still fire when JS session changes (if sessionTracking is enabled)

Testing instructions:

  1. Set up a WooCommerce store with Jetpack connected and WooCommerce Analytics enabled
  2. Add the following code snippet to your theme's functions.php or use a code snippet plugin:
add_filter( 'jetpack_woocommerce_analytics_event_props', function( $event_properties, $event_name ) {
    error_log( 'Tracks event: ' . $event_name );
    return $event_properties;
}, 10, 2 );
  1. Add a product to cart
  2. Go to checkout page - product_checkout event should fire (check debug.log)
  3. Refresh checkout page - event should NOT fire again
  4. Go back to cart, change quantity, return to checkout - event SHOULD fire again
  5. Go back to cart, add another product, return to checkout - event SHOULD fire again
  6. Change woocommerceanalytics_session cookie session id value (simulate new session)
  7. Go to checkout page - event SHOULD fire again
Scenario Expected
First checkout page load Events fire for each item
Page refresh (same cart, same session) No events fire
Add/remove item, return to checkout Events fire again
Change quantity, return to checkout Events fire again
JS session expires (if sessionTracking enabled) Events fire again

Copilot AI review requested due to automatic review settings January 8, 2026 09:44
@chihsuan chihsuan added the [Status] Needs Review This PR is ready for review. label Jan 8, 2026
@chihsuan chihsuan self-assigned this Jan 8, 2026
@github-actions
Copy link
Contributor

github-actions bot commented Jan 8, 2026

Are you an Automattician? Please test your changes on all WordPress.com environments to help mitigate accidental explosions.

  • To test on WoA, go to the Plugins menu on a WoA dev site. Click on the "Upload" button and follow the upgrade flow to be able to upload, install, and activate the Jetpack Beta plugin. Once the plugin is active, go to Jetpack > Jetpack Beta, select your plugin (Jetpack), and enable the fix/deduplicate-product-checkout-event branch.
  • To test on Simple, run the following command on your sandbox:
bin/jetpack-downloader test jetpack fix/deduplicate-product-checkout-event

Interested in more tips and information?

  • In your local development environment, use the jetpack rsync command to sync your changes to a WoA dev blog.
  • Read more about our development workflow here: PCYsg-eg0-p2
  • Figure out when your changes will be shipped to customers here: PCYsg-eg5-p2

@github-actions
Copy link
Contributor

github-actions bot commented Jan 8, 2026

Thank you for your PR!

When contributing to Jetpack, we have a few suggestions that can help us test and review your patch:

  • ✅ Include a description of your PR changes.
  • ✅ Add a "[Status]" label (In Progress, Needs Review, ...).
  • ✅ Add a "[Type]" label (Bug, Enhancement, Janitorial, Task).
  • ✅ Add testing instructions.
  • ✅ Specify whether this PR includes any changes to data or privacy.
  • ✅ Add changelog entries to affected projects

This comment will be updated as you work on your PR and make changes. If you think that some of those checks are not needed for your PR, please explain why you think so. Thanks for cooperation 🤖


Follow this PR Review Process:

  1. Ensure all required checks appearing at the bottom of this PR are passing.
  2. Make sure to test your changes on all platforms that it applies to. You're responsible for the quality of the code you ship.
  3. You can use GitHub's Reviewers functionality to request a review.
  4. When it's reviewed and merged, you will be pinged in Slack to deploy the changes to WordPress.com simple once the build is done.

If you have questions about anything, reach out in #jetpack-developers for guidance!

@github-actions github-actions bot added [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. and removed [Status] Needs Review This PR is ready for review. labels Jan 8, 2026
@chihsuan chihsuan force-pushed the fix/deduplicate-product-checkout-event branch from 6db6d3c to fa497be Compare January 8, 2026 09:49
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR implements deduplication for product_checkout events to prevent them from firing on every page refresh during a checkout session. The changes introduce session-based tracking that fires events once per cart state and optionally tracks JS session changes when ClickHouse is enabled.

Key changes:

  • Adds WC Session-based deduplication to track checkout events once per cart state
  • Implements JS session ID tracking for sessionTracking feature support
  • Automatically resets tracking state when cart changes (add/remove items, quantity updates)

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
projects/packages/woocommerce-analytics/src/class-universal.php Adds deduplication logic with should_track_checkout, mark_checkout_tracked, and reset_checkout_tracking_state methods; updates checkout_process to fire events via record_event() with session-based checks
projects/packages/woocommerce-analytics/src/class-woo-analytics-trait.php Adds get_js_session_id() method and JS_SESSION_COOKIE_NAME constant to support JS session tracking
projects/packages/woocommerce-analytics/tests/php/mocks/woocommerce-functions.php Adds mock WC instance management for testing session functionality
projects/packages/woocommerce-analytics/tests/php/mocks/class-wc-session.php Introduces mock WC_Session class for testing session storage
projects/packages/woocommerce-analytics/tests/php/bootstrap.php Includes new WC_Session mock in test bootstrap
projects/packages/woocommerce-analytics/tests/php/Universal_Test.php Adds tests for reset_checkout_tracking_state and validates session key constants
projects/packages/woocommerce-analytics/changelog/fix-deduplicate-product-checkout-event Documents the change as a patch-level modification
Comments suppressed due to low confidence (3)

projects/packages/woocommerce-analytics/src/class-woo-analytics-trait.php:342

  • The get_js_session_id method lacks test coverage. Consider adding tests to verify: (1) returns null when ClickHouse is disabled, (2) returns null when cookie is not set, (3) correctly extracts session_id from valid cookie JSON, (4) handles invalid JSON gracefully. This is particularly important given the security and error-handling concerns around cookie parsing.
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- We're just reading and JSON-decoding the cookie.
		$cookie_value = wp_unslash( $_COOKIE[ $cookie_name ] );
		$cookie_data  = json_decode( urldecode( $cookie_value ), true );
		return $cookie_data['session_id'] ?? null;
	}

	/**
	 * Gather relevant product information
	 *
	 * @param \WC_Product $product product.
	 * @return array
	 */

projects/packages/woocommerce-analytics/src/class-woo-analytics-trait.php:341

  • Reading the cookie value with wp_unslash is appropriate, but the phpcs ignore comment claims the input doesn't need sanitization because "we're just reading and JSON-decoding the cookie". However, the cookie value comes from the client and could be maliciously crafted. While json_decode is generally safe, the decoded value should be validated. Consider adding explicit type checking to ensure the decoded value is an array and that the session_id field, if present, is a string to prevent unexpected behavior from malicious input.
	 * Gather relevant product information
	 *
	 * @param \WC_Product $product product.
	 * @return array

projects/packages/woocommerce-analytics/src/class-woo-analytics-trait.php:341

  • The get_js_session_id method does not validate that the JSON decoding was successful before attempting to access the array. If the cookie contains invalid JSON, json_decode returns null, and attempting to access $cookie_data['session_id'] will cause a PHP warning about trying to access an array offset on null. Add a check to ensure $cookie_data is an array before accessing its elements.
	 * @param \WC_Product $product product.
	 * @return array

@jp-launch-control
Copy link

jp-launch-control bot commented Jan 8, 2026

Code Coverage Summary

Coverage changed in 2 files.

File Coverage Δ% Δ Uncovered
projects/packages/woocommerce-analytics/src/class-universal.php 22/392 (5.61%) 4.78% 13 💔
projects/packages/woocommerce-analytics/src/class-woo-analytics-trait.php 7/275 (2.55%) 2.55% 1 ❤️‍🩹

Full summary · PHP report · JS report

If appropriate, add one of these labels to override the failing coverage check: Covered by non-unit tests Use to ignore the Code coverage requirement check when E2Es or other non-unit tests cover the code Coverage tests to be added later Use to ignore the Code coverage requirement check when tests will be added in a follow-up PR I don't care about code coverage for this PR Use this label to ignore the check for insufficient code coveage.

@chihsuan chihsuan force-pushed the fix/deduplicate-product-checkout-event branch from fa497be to b809f3b Compare January 8, 2026 10:04
Copilot AI review requested due to automatic review settings January 8, 2026 10:14
@github-actions github-actions bot added the Docs label Jan 8, 2026
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Copy link
Contributor

Copilot AI commented Jan 8, 2026

@chihsuan I've opened a new pull request, #46498, to work on those changes. Once the pull request is ready, I'll request review from you.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

Copilot AI review requested due to automatic review settings January 8, 2026 10:34
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Copilot AI review requested due to automatic review settings January 8, 2026 10:46
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

chihsuan and others added 8 commits January 9, 2026 11:16
- Fire product_checkout PHP-side via record_event() for consistency with product_purchase
- Add session-based deduplication to prevent duplicate events on page refresh
- Reset tracking state when cart changes (add/remove items, quantity updates)
- Include JS session ID tracking for sessionTracking feature support
- Add unit tests for reset_checkout_tracking_state and session key constants

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…s-trait.php

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
…s-trait.php

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
WC_Session::save_data() is not declared on the abstract class.
WooCommerce automatically saves session data at request end via shutdown hook.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Initial plan

* Add comprehensive tests for checkout deduplication logic

Co-authored-by: chihsuan <4344253+chihsuan@users.noreply.github.com>

* Refactor cookie setup into helper methods to reduce duplication

Co-authored-by: chihsuan <4344253+chihsuan@users.noreply.github.com>

* Address code review feedback: improve test patterns

Co-authored-by: chihsuan <4344253+chihsuan@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: chihsuan <4344253+chihsuan@users.noreply.github.com>
Add a helper method that conditionally calls setAccessible() only on PHP < 8.1,
where it's required for private method access. PHP 8.1+ makes private/protected
methods accessible by default via reflection, and PHP 8.5+ deprecates the method.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings January 9, 2026 03:16
@chihsuan chihsuan force-pushed the fix/deduplicate-product-checkout-event branch from d7bd5b3 to 3eba662 Compare January 9, 2026 03:16
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated no new comments.

Simplified the condition for detecting session changes by removing the check for a current session ID. Now, it directly compares the current session ID with the last session ID to determine if a new session has started.
@chihsuan chihsuan added [Type] Enhancement Changes to an existing feature — removing, adding, or changing parts of it [Status] Needs Review This PR is ready for review. and removed [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. labels Jan 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Docs [Feature] WooCommerce Analytics [Package] WooCommerce Analytics Enhanced analytics for WooCommerce users [Status] Needs Review This PR is ready for review. [Tests] Includes Tests [Type] Enhancement Changes to an existing feature — removing, adding, or changing parts of it

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants