cancel
Showing results for 
Search instead for 
Did you mean: 

Adding a product to cart from external website (Magento 2.4.0)

Adding a product to cart from external website (Magento 2.4.0)

Hi everyone,

 

I'm having some issues creating and redirecting a user to a cart from an external catalogue.

 

I'm using an interactive catalogue (external website) where a client can add products to a temporary cart. When clicking checkout on this external catalogue, XML is posted to my controller (on my Magento 2.4.0 website).

 

- I'm able to grab the correct information from the XML

- I think that I'm able to build the cart (Debugging from getQuote(), I see my items correctly)

 

But when the user is redirected to the /checkout/cart page, the cart is empty.

My guess is that I'm building the cart in a different session ID?

 

During debugging, I rewrote almost all my code to use a solution proposed in

another post , and tweaked it to my needs and some errors I was getting.

 

Here is my code :

 

 

<?php /**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Mycompany\MyModule\Controller\Checkout;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\Result\RedirectFactory;

class View extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface{
    /**
     * @var \Magento\Checkout\Model\Cart
     */
    protected $cart;
    /**
     * @var \Magento\Catalog\Model\Product
     */
    protected $product;
    /**
     * @var \Magento\Framework\Controller\ResultFactory;
     */
    protected $resultFactory;
    /**
     * @var \Magento\Framework\Controller\Result\ResultFactory;
     */
    protected $resultRedirectFactory;
    public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
    {
    return null;
    }
    public function validateForCsrf(RequestInterface $request): ?bool
    {
    return true;
    }
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Framework\Controller\Result\Redirect $resultRedirectFactory,
        \Magento\Framework\Controller\ResultFactory $resultFactory,
        \Magento\Catalog\Model\Product $product,
        \Magento\Checkout\Model\Cart $cart
    ) {
        $this->resultFactory = $resultFactory;
        $this->resultPageFactory = $resultPageFactory;
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->cart = $cart;
        $this->product = $product;
        parent::__construct($context);
    }
    public function execute()
    {
        $rawdata = file_get_contents("php://input");
        $new = simplexml_load_string($rawdata);
        $con = json_encode($new);
        $newArr = json_decode($con, true);
        //Build the cart
        $cartitems = [];
        foreach($new->lineitems->item as $item){
                $product = [];
                $product[] = $item->qty;
                $product[] = $item->sku;
                $cartitems[] = $product;
        }
        try {
                foreach($cartitems as $citem){
                        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                        $productId = $objectManager->get('Magento\Catalog\Model\Product')->getIdBySku($citem[1]);
                        $qty = $citem[0];
                        $id = $citem[1];
                        $params = array();
                        $params['qty'] = $qty;
                        $_product = $this->product->load($productId);
                        if ($_product) {
                                $this->cart->addProduct($_product, $params);
                                $this->cart->save();
                        }
                }
                $this->messageManager->addSuccess(__('Add to cart successfully.'));
        }
        catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addException(
                $e,
                __('%1', $e->getMessage())
                );
        }
        catch (\Exception $e) {
                $this->messageManager->addException($e, __('error.'));
        }

// START DEBUG
// Check what is in the cart
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
// get quote items collection
$itemsCollection = $cart->getQuote()->getItemsCollection();
// get array of all items what can be display directly
$itemsVisible = $cart->getQuote()->getAllVisibleItems();
// get quote items array
$items = $cart->getQuote()->getAllItems();
foreach($items as $item) {
    echo 'ID: '.$item->getProductId().'<br />';
    echo 'Name: '.$item->getName().'<br />';
    echo 'Sku: '.$item->getSku().'<br />';
    echo 'Quantity: '.$item->getQty().'<br />';
    echo 'Price: '.$item->getPrice().'<br />';
    echo "<br />";
}
// END DEBUG

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$carturl = 'https://'.$_SERVER['SERVER_NAME'].'/checkout/cart/';
header("Location: ".$carturl, true, 301);
echo $carturl;
exit;
    }
}

 

 

I tried various redirection methods, but with the catalogue solution I'm using I need to output the cart URL in the browser in order to redirect correctly. Hence the echo $carturl;

 

Any help would be greatly appreciated Smiley Happy Thank you!

 

2 REPLIES 2

Re: Adding a product to cart from external website (Magento 2.4.0)

I have exactly the same problem. Anyone got a suggestion? This is quiet a common issue 

I'm having the same problem as the others. I am also encountering this issue.myaccountaccess Dont know why its hapenning. pleased to see your issue as I think I have the same problem I am also confused and in need of light on this same issue. Need help.

Re: Adding a product to cart from external website (Magento 2.4.0)

Hi everyone,

 

I'm having some issues creating and redirecting a user to a cart from an external catalogue.

 

I'm using an interactive catalogue (external website) where a client can add products to a temporary cart. When clicking checkout on this external catalogue, XML is posted to my controller (on my Magento 2.4.0 website) myaccountaccess

 

- I'm able to grab the correct information from the XML

- I think that I'm able to build the cart (Debugging from getQuote(), I see my items correctly)