Search code examples
shopware6shopware6-api

Merge API context with session


I have the following problem: I have a landing page which is outside of shopware context. I have add to cart buttons and want to add products to a cart.

What I can do and works:

  • create api context
  • create cart
  • add product

What doesn't work yet - interaction with the shop:

  • Use the cart which already exists to start with
  • Continue with the cart which we created and use the normal checkout

Solution

  • The solution is to get the context from the session (this depends on the same php context … cookies, same donain, etc.). I hacked it this way:

    <?php
    
    declare(strict_types=1);
    
    function generateRandomString()
    {
        $characters = implode('', range('a', 'z')) . implode('', range('A', 'Z')) . implode('', range(0, 9));
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < 32; $i++) {
            $randomString .= $characters[random_int(0, $charactersLength - 1)];
        }
    
        return $randomString;
    }
    
    session_name('session-');
    session_start();
    if (!isset($_SESSION['_sf2_attributes']['sw-context-token'])) {
        $_SESSION['_sf2_attributes']['sw-context-token'] = generateRandomString();
    }
    ?>
    
    
    <script>
       const context = <?php echo json_encode($_SESSION['_sf2_attributes']['sw-context-token'], JSON_THROW_ON_ERROR)?>;
    </script>
    

    This context is then used in the API calls. And it works like a charm.