Code Programmatically — Magento 2 Get Coupon
Note: Magento does not store per‑item coupon codes; coupons apply at the entire quote/order level. Create a reusable service in your custom module.
use Magento\Quote\Model\QuoteFactory; public function getCouponCodeFromQuote(QuoteFactory $quoteFactory, $quoteId)
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();
Often needed for order export, invoices, or customer history pages. magento 2 get coupon code programmatically
class GetCoupon implements HttpGetActionInterface
public function __construct( CartRepositoryInterface $quoteRepository, OrderRepositoryInterface $orderRepository ) $this->quoteRepository = $quoteRepository; $this->orderRepository = $orderRepository;
<?php declare(strict_types=1); namespace YourNamespace\YourModule\Model; Note: Magento does not store per‑item coupon codes;
use Magento\Quote\Api\CartRepositoryInterface; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Framework\Exception\NoSuchEntityException;
<?php namespace YourNamespace\YourModule\Controller\Index; use Magento\Framework\App\Action\HttpGetActionInterface; use Magento\Framework\Controller\Result\JsonFactory; use YourNamespace\YourModule\Model\GetCouponCodeService;
$collection = $orderCollectionFactory->create() ->addFieldToFilter('entity_id', ['in' => $orderIds]) ->addFieldToSelect(['entity_id', 'coupon_code']); isLoggedIn()) $quote = $this->
try $order = $this->orderRepository->get($orderId); return $order->getCouponCode(); catch (NoSuchEntityException $e) return null;
public function getAppliedCouponForItem($itemId)