- 🇨🇦Canada leducdubleuet Chicoutimi QC
Nowadays with current versions, the solution proposed here is not working anymore. The $session->migrate() does not seem to do anything when the session is not already started...
In case anybody lands here with that same problem, here is an example of what worked for me :
// Step 1: Ensure the session is started for anonymous users. if ($current_user->isAnonymous()) { $session = \Drupal::service('session'); // If the session is not started, forcefully start it. if (!$session->isStarted()) { session_start(); } } // Step 2: Check if there's an existing cart order for the current user session. /* @var \Drupal\commerce_cart\CartProviderInterface $cart_provider */ $cart_provider = \Drupal::service('commerce_cart.cart_provider'); /* @var \Drupal\commerce_cart\CartManagerInterface $cart_manager */ $cart_manager = \Drupal::service('commerce_cart.cart_manager'); // Get the current cart if any $order = $cart_provider->getCart('default'); // If there's an existing cart order, empty it. if (!empty($order)) { $cart_manager->emptyCart($order); } else { // Create a new empty cart if it doesn't exist. $order = $cart_provider->createCart('default'); } $checkout_url = '/checkout/' . $order->id(); $response = new RedirectResponse($checkout_url); $response->send();
This starts the session first when it was not already to fix the access denied on the checkout for anonymous users!
The call to createCart() adds the order id to user's cart session, no need to do that manually.
Hope this helps!
Thanks!