Magento 2 Get Coupon Code Programmatically ❲RELIABLE❳

$this->couponCollectionFactory = $couponCollectionFactory;

private OrderRepositoryInterface $orderRepository;

public function __construct( CartRepositoryInterface $quoteRepository, OrderRepositoryInterface $orderRepository ) $this->quoteRepository = $quoteRepository; $this->orderRepository = $orderRepository; magento 2 get coupon code programmatically

public function getAppliedCouponForItem($itemId)

try $order = $this->orderRepository->get($orderId); return $order->getCouponCode(); catch (NoSuchEntityException $e) return null; couponCollectionFactory = $couponCollectionFactory

Often needed for order export, invoices, or customer history pages.

<?php namespace YourNamespace\YourModule\Model; use Magento\Sales\Api\OrderRepositoryInterface; private OrderRepositoryInterface $orderRepository

private CartRepositoryInterface $quoteRepository; private CustomerSession $customerSession; private CheckoutSession $checkoutSession;

$result = []; foreach ($collection as $order) $result[$order->getId()] = $order->getCouponCode();

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.