magento 2.3 - Get cart info after user login
-
13-04-2021 - |
Pregunta
my goal is to modify info on cart after user has logged in, either from account page or cart popup. So, I created a new module for this, using the event "customer_login" but it does not seem to work. Could you please let me know if this is the right event to use to intervene on cart after login?
Thank you very much for your help
events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_login">
<observer name="cart_preorder" instance="Vendor\Module\Observer\CustomObserver"/>
</event>
</config>
module.xml
---
<sequence>
<module name="Magento_Checkout" />
</sequence>
---
Observer
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Checkout\Helper\Cart;
class CustomObserver implements ObserverInterface
{
protected $cartHelper;
public function __construct(
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Quote\Api\CartRepositoryInterface $quoteRepository
) {
$this->checkoutSession = $checkoutSession;
$this->quoteRepository = $quoteRepository;
}
public function execute(Observer $observer)
{
$customer = $observer->getEvent()->getCustomer();
$customerId = $customer->getId();
die(print_r($customerId));
if($customerId){
$customerQuote = $this->quoteRepository->getForCustomer($customerId);
$cartItems = $customerQuote->getAllItems();
die($cartItems);
}
}
}
Solución
Use customer_data_object_login event.
Check the following class:
vendor/magento/module-customer/Model/AccountManagement.php
public function authenticate($username, $password)
{
try {
$customer = $this->customerRepository->get($username);
} catch (NoSuchEntityException $e) {
throw new InvalidEmailOrPasswordException(__('Invalid login or password.'));
}
$customerId = $customer->getId();
if ($this->getAuthentication()->isLocked($customerId)) {
throw new UserLockedException(__('The account is locked.'));
}
try {
$this->getAuthentication()->authenticate($customerId, $password);
} catch (InvalidEmailOrPasswordException $e) {
throw new InvalidEmailOrPasswordException(__('Invalid login or password.'));
}
if ($customer->getConfirmation() && $this->isConfirmationRequired($customer)) {
throw new EmailNotConfirmedException(__("This account isn't confirmed. Verify and try again."));
}
$customerModel = $this->customerFactory->create()->updateData($customer);
$this->eventManager->dispatch(
'customer_customer_authenticated',
['model' => $customerModel, 'password' => $password]
);
$this->eventManager->dispatch('customer_data_object_login', ['customer' => $customer]);
return $customer;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange