2

Hello I want to get the coupon code in a plugin. My code is:

  private $logger;
  private $checkoutSession;

  public function __construct(
    \Psr\Log\LoggerInterface $logger,
    \Magento\Checkout\Model\Session $checkoutSession
  ){
    $this->logger = $logger;
    $this->checkoutSession = $checkoutSession;
  }
  public function beforePlaceOrder(\Magento\Quote\Model\QuoteManagement $subject, $cartId, ?\Magento\Quote\Api\Data\PaymentInterface $paymentMethod = null){
    $this->logger->debug("Before Place Order");
    $order = $this->checkoutSession->getLastRealOrder();
    $orderId=$order->getEntityId();
    $couponCode = $order->getCouponCode();
    $this->logger->debug($couponCode);
  }

But $couponCode is empty.

Can someone help me?

thank you in advance

1 Answer 1

1

You don't need use checkout session \Magento\Checkout\Model\Session.

From Magento\Quote\Model\QuoteManagement and Magento\Quote\Api\CartRepositoryInterface can get coupon code .

   private $logger;
  private $quoteRepository;

  public function __construct(
    \Psr\Log\LoggerInterface $logger,
    \Magento\Quote\Api\CartRepositoryInterface $quoteRepository
  ){
    $this->logger = $logger;
    $this->quoteRepository = $quoteRepository;
  }
  public function beforePlaceOrder(
    \Magento\Quote\Model\QuoteManagement $subject,
     $cartId, 
    \Magento\Quote\Api\Data\PaymentInterface $paymentMethod = null
){
    $this->logger->debug("Before Place Order");
    $quote = $this->quoteRepository->getActive($cartId);

    if($quote->getId()){
        $couponCode = $quote->getCouponCode();
        $this->logger->debug($couponCode);
    }       

  }
1
  • thanks a lot! It works!
    – vDrews
    Commented Jun 20, 2019 at 11:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.