I am trying to intercept add to cart button.
What I intend to do:
If customer is not logged in, throw error message. Else if customer is logged in, add item to cart.
I did it in following way. I got the error message Cannot add to cart.
as expector for customer that is not logged in. But I can't get user to add the product if the customer is logged in. I get the error message We can't add this item to your shopping cart right now.
.
What am I doing it wrong? Note that I can add the particular product to cart if i commented out the logic in this plugin.
=============================================================================
Note updated code as advise. It seems like can't get customer session with following code. Everything works correctly if i commented out the customer session \Magento\Customer\Model\Session
and related code to check if customer is log in.
use Magento\Framework\Exception\LocalizedException;
class Cart
{
protected $session;
public function __construct(
\Magento\Customer\Model\Session $session
) {
$this->session = $session;
}
public function beforeAddProduct(
\Magento\Checkout\Model\Cart $subject,
$productInfo,
$requestInfo) {
if (!$this->session->isLoggedIn()) {
throw new LocalizedException(__('Cannot add to cart.'));
return [$productInfo, $requestInfo];
}
return [$productInfo, $requestInfo];
}
}
protected $session
variable.