I am struggling to empty the cart by email in the API.
The store is multi-website and my API endpoint works in that it takes an email and returns a message. The customer ID is retrieved but the basket (or baskets, since it is for multi-store) just don't empty.
Note this is over the API and I don't have a logged in session to work with.
use Magento\Customer\Model\CustomerFactory;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Store\Model\Group;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
class Emptybasket implements \Company\Module\Api\EmptybasketInterface
{
protected $_customer;
protected $_storeManager;
protected $quoteRepository;
public function __construct(
CartRepositoryInterface $quoteRepository,
CustomerFactory $customer,
StoreManagerInterface $storeManager
) {
$this->quoteRepository = $quoteRepository;
$this->_customer = $customer;
$this->_storeManager = $storeManager;
}
/**
* {@inheritdoc}
*/
public function postEmptybasket($param)
{
$emptied = false;
$message = '';
try {
$websites = $this->_storeManager->getWebsites();
foreach ($websites as $website) {
$customer = $this->_customer->create()->setWebsiteId($website->getId())->loadByEmail($param);
$customerId = $customer->getId();
if ($customerId) {
$defaultGroup = $website->getDefaultGroup();
if ($defaultGroup instanceof Group) {
$storeId = $defaultGroup->getDefaultStoreId();
} else {
$storeId = Store::DEFAULT_STORE_ID;
}
try {
$cart = $this->quoteRepository->getForCustomer($customerId, [$storeId]);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
continue;
}
$cart->removeAllItems();
$this->quoteRepository->save($cart);
$emptied = true;
}
}
} catch (\Magento\Framework\Exception\NoSuchEntityException $exception) {
$message .= "Computer said no: " . $exception->getMessage();
} catch (\Magento\Framework\Exception\LocalizedException $exception) {
$message .= "Magento said no: " . $exception->getMessage();
}
if ($emptied) {
return "Basket emptied for " . $param;
}
return 'Basket for ' . $param . ' not found. ' . $message;
}
}