Commit 83892c13ad7 for woocommerce
commit 83892c13ad70799f759e42a7d362306a978a6d3b
Author: Luigi Teschio <gigitux@gmail.com>
Date: Mon Nov 23 13:31:00 2026 +0100
Use a cart-only token in checkout link URLs (#71222)
* Use a cart-only token in checkout link URLs
(cherry picked from commit 50bcc403f535cb02e74c2e0dfb6d95f1d985221e)
* Carry over the original checkout URL documentation
---------
Co-authored-by: Mike Jolley <mike.jolley@me.com>
diff --git a/docs/best-practices/urls-and-routing/checkout-urls.md b/docs/best-practices/urls-and-routing/checkout-urls.md
index b70d1392007..770ddb99786 100644
--- a/docs/best-practices/urls-and-routing/checkout-urls.md
+++ b/docs/best-practices/urls-and-routing/checkout-urls.md
@@ -5,7 +5,7 @@ sidebar_label: Checkout URLs
# Shareable Checkout URLs
-Custom checkout links automatically populate the cart with specific products and redirect customers straight to checkout with a unique session ID.
+Custom checkout links automatically populate the cart with specific products and redirect customers straight to checkout.
The custom checkout link path is `/checkout-link/` and is not customizable.
@@ -80,4 +80,6 @@ In this link:
## Sessions
-Once the user is redirected to the checkout page, the cart is populated with the products and coupon code. The final URL includes a `session` parameter storing the ID of the session. Future changes to the checkout will be persisted in the session, enabling persistent and shareable carts.
+Once the user is redirected to the checkout page, the cart is populated with the products and coupon code. For guests, the final URL includes a `session` parameter so the cart is kept if they open the page in another browser, for example when leaving an app's built-in browser. The cart is copied without the shopper's address or contact details.
+
+To share a cart with other people, share the `/checkout-link/` URL. Each person who opens it gets their own cart with the same products and coupon.
diff --git a/plugins/woocommerce/includes/class-wc-session-handler.php b/plugins/woocommerce/includes/class-wc-session-handler.php
index 578f31c1c85..5a06c5ac0db 100644
--- a/plugins/woocommerce/includes/class-wc-session-handler.php
+++ b/plugins/woocommerce/includes/class-wc-session-handler.php
@@ -133,13 +133,9 @@ class WC_Session_Handler extends WC_Session {
private function init_session_from_request() {
$session_token = is_string( $_GET['session'] ?? '' ) ? wc_clean( wp_unslash( $_GET['session'] ?? '' ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
- if ( empty( $session_token ) || ! CartTokenUtils::validate_cart_token( $session_token ) ) {
- return false;
- }
-
- $payload = CartTokenUtils::get_cart_token_payload( $session_token );
+ $token_customer_id = is_string( $session_token ) && '' !== $session_token ? CartTokenUtils::get_cart_link_customer_id( $session_token ) : '';
- if ( ! $this->is_customer_guest( $payload['user_id'] ) || ! $this->session_exists( $payload['user_id'] ) ) {
+ if ( ! $token_customer_id || ! $this->is_customer_guest( $token_customer_id ) || ! $this->session_exists( $token_customer_id ) ) {
return false;
}
@@ -148,14 +144,14 @@ class WC_Session_Handler extends WC_Session {
if ( $cookie ) {
// User owns this token. Return and use cookie session.
- if ( $cookie[0] === $payload['user_id'] ) {
+ if ( $cookie[0] === $token_customer_id ) {
return false;
}
$cookie_session_data = (array) $this->get_session( $cookie[0], array() );
// Cookie session was originally created via this token. Return and use cookie session to prevent creating a new clone.
- if ( isset( $cookie_session_data['previous_customer_id'] ) && $cookie_session_data['previous_customer_id'] === $payload['user_id'] ) {
+ if ( isset( $cookie_session_data['previous_customer_id'] ) && $cookie_session_data['previous_customer_id'] === $token_customer_id ) {
return false;
}
}
@@ -163,7 +159,7 @@ class WC_Session_Handler extends WC_Session {
// Generate new customer ID for the new session before cloning the data.
$this->_customer_id = $this->generate_customer_id();
$this->set_customer_session_cookie( true );
- $this->clone_session_data( $payload['user_id'] );
+ $this->clone_session_data( $token_customer_id );
return true;
}
diff --git a/plugins/woocommerce/phpstan-baseline.neon b/plugins/woocommerce/phpstan-baseline.neon
index 4e9e030cac3..dd2342fead1 100644
--- a/plugins/woocommerce/phpstan-baseline.neon
+++ b/plugins/woocommerce/phpstan-baseline.neon
@@ -14160,18 +14160,6 @@ parameters:
count: 1
path: includes/class-wc-session-handler.php
- -
- message: '#^Parameter \#1 \$cart_token of static method Automattic\\WooCommerce\\StoreApi\\Utilities\\CartTokenUtils\:\:get_cart_token_payload\(\) expects string, array\|string given\.$#'
- identifier: argument.type
- count: 1
- path: includes/class-wc-session-handler.php
-
- -
- message: '#^Parameter \#1 \$cart_token of static method Automattic\\WooCommerce\\StoreApi\\Utilities\\CartTokenUtils\:\:validate_cart_token\(\) expects string, array\|string given\.$#'
- identifier: argument.type
- count: 1
- path: includes/class-wc-session-handler.php
-
-
message: '#^Parameter \#1 \$customer_id of method WC_Session_Handler\:\:get_session\(\) expects string, string\|null given\.$#'
identifier: argument.type
diff --git a/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutLink.php b/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutLink.php
index 81ab5a9507a..1deda7f2691 100644
--- a/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutLink.php
+++ b/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutLink.php
@@ -65,6 +65,10 @@ class CheckoutLink {
return;
}
+ // The redirect depends on the visitor's session, so page caches must not store it.
+ \WC_Cache_Helper::set_nocache_constants();
+ nocache_headers();
+
if ( ! $this->validate_checkout_link() ) {
$redirect = add_query_arg( 'wc_error', rawurlencode( __( 'The provided checkout link was out of date or invalid. No products were added to the cart.', 'woocommerce' ) ), wc_get_cart_url() );
} else {
@@ -240,7 +244,7 @@ class CheckoutLink {
}
/**
- * Process the query params and return the checkout link to redirect to complete with session token.
+ * Process the query params and return the checkout link to redirect to complete with a cart link token.
*
* @return string The checkout link.
*/
@@ -328,14 +332,16 @@ class CheckoutLink {
'products',
'coupon',
'checkout-link',
+ 'session',
],
add_query_arg( wp_unslash( $_SERVER['QUERY_STRING'] ), '', $redirect_url ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
);
}
- // If the user is logged in, the session is tied to the user ID. Do not use a cart token.
+ // Logged-in sessions are tied to the user ID. Guests get a link token so the cart survives opening the URL in
+ // another browser, such as leaving an in-app browser. It can't be used as a Store API Cart-Token.
if ( ! is_user_logged_in() ) {
- $session_token = CartTokenUtils::get_cart_token( (string) wc()->session->get_customer_id() );
+ $session_token = CartTokenUtils::get_cart_link_token( (string) wc()->session->get_customer_id() );
$redirect_url = add_query_arg( 'session', $session_token, $redirect_url );
}
diff --git a/plugins/woocommerce/src/StoreApi/Utilities/CartTokenUtils.php b/plugins/woocommerce/src/StoreApi/Utilities/CartTokenUtils.php
index 17101725c0c..16160a6026e 100644
--- a/plugins/woocommerce/src/StoreApi/Utilities/CartTokenUtils.php
+++ b/plugins/woocommerce/src/StoreApi/Utilities/CartTokenUtils.php
@@ -31,6 +31,44 @@ class CartTokenUtils {
);
}
+ /**
+ * Generate a cart link token.
+ *
+ * Unlike a cart token, a link token can't be used as a Store API `Cart-Token`. It only lets another browser copy the
+ * cart through the `session` query arg, without the customer's details.
+ *
+ * @since 11.4.0
+ * @param string $customer_id The customer ID.
+ * @return string
+ */
+ public static function get_cart_link_token( string $customer_id ): string {
+ return JsonWebToken::create(
+ array(
+ 'user_id' => $customer_id,
+ 'exp' => self::get_cart_token_expiration(),
+ 'iss' => 'cart-link',
+ ),
+ self::get_cart_token_secret()
+ );
+ }
+
+ /**
+ * Get the customer ID from a token passed in the `session` query arg.
+ *
+ * Accepts cart link tokens and cart tokens, so integrations that pass a cart token in the query arg keep working.
+ *
+ * @since 11.4.0
+ * @param string $token The cart link token or cart token.
+ * @return string The customer ID, or an empty string if the token is not valid.
+ */
+ public static function get_cart_link_customer_id( string $token ): string {
+ if ( ! self::validate_token( $token, array( 'cart-link', 'store-api' ) ) ) {
+ return '';
+ }
+
+ return (string) ( JsonWebToken::get_parts( $token )->payload->user_id ?? '' );
+ }
+
/**
* Get the cart token sent with the current HTTP request.
*
@@ -46,11 +84,27 @@ class CartTokenUtils {
/**
* Validate the cart token.
*
+ * @since 11.4.0 Rejects tokens not issued by the Store API, such as cart link tokens.
* @param string $cart_token The cart token.
* @return bool
*/
public static function validate_cart_token( string $cart_token ): bool {
- return JsonWebToken::validate( $cart_token, self::get_cart_token_secret() );
+ return self::validate_token( $cart_token, array( 'store-api' ) );
+ }
+
+ /**
+ * Validate a token's signature and check it was issued by one of the given issuers.
+ *
+ * @param string $token The token.
+ * @param string[] $issuers Accepted `iss` claims.
+ * @return bool
+ */
+ private static function validate_token( string $token, array $issuers ): bool {
+ if ( ! JsonWebToken::validate( $token, self::get_cart_token_secret() ) ) {
+ return false;
+ }
+
+ return in_array( JsonWebToken::get_parts( $token )->payload->iss ?? '', $issuers, true );
}
/**
diff --git a/plugins/woocommerce/tests/legacy/unit-tests/session/class-wc-tests-session-handler.php b/plugins/woocommerce/tests/legacy/unit-tests/session/class-wc-tests-session-handler.php
index fd37c5d4555..5e70e823d3d 100644
--- a/plugins/woocommerce/tests/legacy/unit-tests/session/class-wc-tests-session-handler.php
+++ b/plugins/woocommerce/tests/legacy/unit-tests/session/class-wc-tests-session-handler.php
@@ -589,6 +589,59 @@ class WC_Tests_Session_Handler extends WC_Unit_Test_Case {
$this->assertSame( array( array( 'customer' ) ), $wpdb->get_results( $wpdb->prepare( "SELECT session_key FROM %i WHERE session_key IN ('guest', 'customer')", "{$wpdb->prefix}woocommerce_sessions" ), ARRAY_N ) );
}
+ /**
+ * Session tokens that can be passed in the `session` query arg.
+ *
+ * @return array<string, array<string>>
+ */
+ public function provide_session_query_tokens(): array {
+ return array(
+ 'cart link token' => array( 'cart-link' ),
+ 'cart token' => array( 'store-api' ),
+ );
+ }
+
+ /**
+ * @testdox A $token_type in the session query arg copies the guest's cart without their customer details.
+ * @dataProvider provide_session_query_tokens
+ *
+ * @param string $token_type Token issuer.
+ */
+ public function test_session_query_arg_copies_guest_cart_without_customer( string $token_type ) {
+ global $wpdb;
+
+ $guest_session_id = 't_' . wc_rand_hash( '', 30 );
+
+ $wpdb->insert(
+ $wpdb->prefix . 'woocommerce_sessions',
+ array(
+ 'session_key' => $guest_session_id,
+ 'session_value' => maybe_serialize(
+ array(
+ 'cart' => 'shared cart',
+ 'customer' => array( 'email' => 'guest@example.org' ),
+ )
+ ),
+ 'session_expiry' => time() + 50000,
+ ),
+ array( '%s', '%s', '%d' )
+ );
+
+ wp_set_current_user( 0 );
+ $_GET['session'] = 'cart-link' === $token_type ? CartTokenUtils::get_cart_link_token( $guest_session_id ) : CartTokenUtils::get_cart_token( $guest_session_id );
+ add_filter( 'woocommerce_set_cookie_enabled', '__return_false' );
+
+ $handler = new WC_Session_Handler();
+ $handler->init();
+
+ remove_filter( 'woocommerce_set_cookie_enabled', '__return_false' );
+ unset( $_GET['session'] );
+
+ $this->assertNotSame( $guest_session_id, $handler->get_customer_id(), 'The visitor should get a new session.' );
+ $this->assertSame( 'shared cart', $handler->get( 'cart' ), 'The cart should be copied.' );
+ $this->assertNull( $handler->get( 'customer' ), 'Customer details should not be copied.' );
+ }
+
/**
* Helper function to read the cookie name used by the handler under test.
*
diff --git a/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutLinkTest.php b/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutLinkTest.php
index 6a240922091..000ea5b443a 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutLinkTest.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/Domain/Services/CheckoutLinkTest.php
@@ -6,6 +6,7 @@ namespace Automattic\WooCommerce\Tests\Blocks\Domain\Services;
use Automattic\WooCommerce\Blocks\Domain\Services\CheckoutLink;
use Automattic\WooCommerce\Enums\ProductStatus;
use Automattic\WooCommerce\RestApi\UnitTests\Helpers\CouponHelper;
+use Automattic\WooCommerce\StoreApi\Utilities\CartTokenUtils;
/**
* Unit tests for CheckoutLink.
@@ -95,7 +96,7 @@ class CheckoutLinkTest extends \WC_Unit_Test_Case {
/**
* @testdox Adds legacy products, quantities, SKUs, variations, additional data, and a coupon from a checkout link.
*/
- public function test_products_and_coupon_are_added_and_token_in_url(): void {
+ public function test_products_and_coupon_are_added(): void {
$legacy_product = \WC_Helper_Product::create_simple_product();
$quantity_product = \WC_Helper_Product::create_simple_product();
$sku_product = \WC_Helper_Product::create_simple_product();
@@ -156,7 +157,31 @@ class CheckoutLinkTest extends \WC_Unit_Test_Case {
$this->assertSame( 'alpha,beta;gamma:delta', $cart_by_product[ $variable_product->get_id() ]['note'], 'Escaped delimiters should be retained in additional product data.' );
$this->assertArrayNotHasKey( 'nyp', $cart_by_product[ $variable_product->get_id() ]['variation'], 'Additional product data should not be treated as variation data.' );
$this->assertSame( [ 'test-coupon' ], WC()->cart->get_applied_coupons(), 'The checkout-link coupon should be applied.' );
- $this->assertStringContainsString( 'session=', $url, 'Guest checkout links should include a cart session token.' );
+ $this->assert_url_has_cart_link_token( $url );
+ }
+
+ /**
+ * @testdox Replaces an incoming session token with the guest's own cart link token.
+ */
+ public function test_incoming_session_token_is_replaced(): void {
+ $product = \WC_Helper_Product::create_simple_product();
+ $original_query = $_SERVER['QUERY_STRING'] ?? null; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- Saved only to restore it after the test.
+ $_GET['products'] = (string) $product->get_id();
+ $_SERVER['QUERY_STRING'] = 'products=' . $product->get_id() . '&session=example-token&utm_source=newsletter';
+
+ try {
+ $url = $this->get_checkout_link_service()->get_checkout_link_test();
+ } finally {
+ if ( null === $original_query ) {
+ unset( $_SERVER['QUERY_STRING'] );
+ } else {
+ $_SERVER['QUERY_STRING'] = $original_query;
+ }
+ }
+
+ $this->assertStringNotContainsString( 'example-token', $url, 'An incoming session token should not be forwarded to the checkout URL.' );
+ $this->assert_url_has_cart_link_token( $url );
+ $this->assertStringContainsString( 'utm_source=newsletter', $url, 'Other query args should still be forwarded.' );
}
/**
@@ -254,7 +279,7 @@ class CheckoutLinkTest extends \WC_Unit_Test_Case {
$this->assertSame( [ $simple_product->get_id() ], array_values( wp_list_pluck( WC()->cart->get_cart(), 'product_id' ) ), 'Only the resolvable product should be added to the cart.' );
$this->assertStringStartsWith( $variable_product->get_permalink(), $url, 'The shopper should be sent to the first product that needs options.' );
$this->assertStringContainsString( 'attribute_pa_colour=blue', $url, 'Attributes of the first product that needs options should be preselected.' );
- $this->assertStringContainsString( 'session=', $url, 'Guests should keep the cart through the session token.' );
+ $this->assert_url_has_cart_link_token( $url );
$notices = wc_get_notices( 'error' );
@@ -299,6 +324,21 @@ class CheckoutLinkTest extends \WC_Unit_Test_Case {
$this->assertSame( 'This item is not available for purchase.', $query['wc_error'], 'The add to cart error should not name the unpublished product or its attributes.' );
}
+ /**
+ * Assert the URL carries a cart link token for the current session, not a Store API cart token.
+ *
+ * @param string $url The checkout link redirect URL.
+ */
+ private function assert_url_has_cart_link_token( string $url ): void {
+ wp_parse_str( (string) wp_parse_url( $url, PHP_URL_QUERY ), $query );
+
+ $token = (string) ( $query['session'] ?? '' );
+
+ $this->assertNotSame( '', $token, 'Guest checkout links should include a session token so the cart can move to another browser.' );
+ $this->assertSame( (string) WC()->session->get_customer_id(), CartTokenUtils::get_cart_link_customer_id( $token ), 'The token should name the guest session.' );
+ $this->assertFalse( CartTokenUtils::validate_cart_token( $token ), 'The token should not be usable as a Store API Cart-Token.' );
+ }
+
/**
* @testdox Strips cart item data for sold-individually products and variations by default, restores it only where the override filter allows, and still blocks a later plain add.
*/
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/SessionHandlerTest.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/SessionHandlerTest.php
index edfb4ed84f6..ea8caabce15 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/SessionHandlerTest.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/SessionHandlerTest.php
@@ -141,6 +141,18 @@ class SessionHandlerTest extends WC_Unit_Test_Case {
$this->assertSame( $customer_id, $handler->get_customer_id(), 'A customer token should address its own session' );
}
+ /**
+ * @testdox A cart link token sent as a Cart-Token does not load the session it names.
+ */
+ public function test_cart_link_token_does_not_load_the_session_it_names(): void {
+ $_SERVER['HTTP_CART_TOKEN'] = CartTokenUtils::get_cart_link_token( 't_guest_session' );
+
+ $handler = new SessionHandler();
+ $handler->init();
+
+ $this->assertNotSame( 't_guest_session', $handler->get_customer_id(), 'A link token should not address the session it names' );
+ }
+
/**
* @testdox Persisted session changes exclude unsaved changes made by the current request.
*/
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/CartTokenUtilsTests.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/CartTokenUtilsTests.php
index 128ba462b39..c261f8bcd28 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/CartTokenUtilsTests.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/CartTokenUtilsTests.php
@@ -80,4 +80,53 @@ class CartTokenUtilsTests extends TestCase {
$token = \Automattic\WooCommerce\StoreApi\Utilities\JsonWebToken::create( $payload, $secret );
$this->assertFalse( CartTokenUtils::validate_cart_token( $token ) );
}
+
+ /**
+ * @testdox A cart link token names the session but is not a valid Store API cart token.
+ */
+ public function test_cart_link_token_is_not_a_cart_token() {
+ $token = CartTokenUtils::get_cart_link_token( 't_link' );
+
+ $this->assertSame( 't_link', CartTokenUtils::get_cart_link_customer_id( $token ), 'A link token should name its session.' );
+ $this->assertFalse( CartTokenUtils::validate_cart_token( $token ), 'A link token should not validate as a cart token.' );
+ $this->assertSame( '', CartTokenUtils::get_cart_token_payload( $token )['user_id'], 'A link token should not expose a cart token payload.' );
+ }
+
+ /**
+ * @testdox Cart tokens are still accepted where a cart link token is expected.
+ */
+ public function test_cart_token_is_accepted_as_cart_link_token() {
+ $token = CartTokenUtils::get_cart_token( 't_headless' );
+
+ $this->assertSame( 't_headless', CartTokenUtils::get_cart_link_customer_id( $token ) );
+ }
+
+ /**
+ * @testdox Expired, unsigned, or unknown-issuer tokens are rejected where a cart link token is expected.
+ */
+ public function test_invalid_tokens_are_rejected_as_cart_link_tokens() {
+ $secret = '@' . wp_salt();
+
+ $expired = \Automattic\WooCommerce\StoreApi\Utilities\JsonWebToken::create(
+ [
+ 'user_id' => 't_expired',
+ 'exp' => time() - 100,
+ 'iss' => 'cart-link',
+ ],
+ $secret
+ );
+ $other = \Automattic\WooCommerce\StoreApi\Utilities\JsonWebToken::create(
+ [
+ 'user_id' => 't_other',
+ 'exp' => time() + 100,
+ 'iss' => 'other',
+ ],
+ $secret
+ );
+
+ $this->assertSame( '', CartTokenUtils::get_cart_link_customer_id( $expired ), 'Expired link tokens should be rejected.' );
+ $this->assertSame( '', CartTokenUtils::get_cart_link_customer_id( $other ), 'Tokens from other issuers should be rejected.' );
+ $this->assertSame( '', CartTokenUtils::get_cart_link_customer_id( 'invalid.token.value' ), 'Malformed tokens should be rejected.' );
+ $this->assertFalse( CartTokenUtils::validate_cart_token( $other ), 'Tokens from other issuers should not validate as cart tokens.' );
+ }
}