Magento 2 Get Coupon Code Programmatically Page

use Magento\Quote\Api\CartRepositoryInterface; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Framework\Exception\NoSuchEntityException;

class GetAllCouponCodes

public function getAppliedCouponForItem($itemId)

<?php declare(strict_types=1); namespace YourNamespace\YourModule\Model; magento 2 get coupon code programmatically

public function fromCurrentSession( \Magento\Checkout\Model\Session $checkoutSession, \Magento\Customer\Model\Session $customerSession ): ?string if ($customerSession->isLoggedIn()) $quote = $this->quoteRepository->getActiveForCustomer($customerSession->getCustomerId()); else $quote = $checkoutSession->getQuote(); return $quote->getCouponCode();

public function __construct(CollectionFactory $couponCollectionFactory)

class GetCouponCodeService

private OrderRepositoryInterface $orderRepository;

class GetCoupon implements HttpGetActionInterface

try $order = $this->orderRepository->get($orderId); return $order->getCouponCode(); catch (NoSuchEntityException $e) return null; isLoggedIn()) $quote = $this-&gt

private CollectionFactory $couponCollectionFactory;

<?php namespace YourNamespace\YourModule\Model; use Magento\SalesRule\Model\ResourceModel\Coupon\CollectionFactory;

Scroll to Top