try $order = $this->orderRepository->get($orderId); return $order->getCouponCode(); catch (NoSuchEntityException $e) return null;
$quote = $quoteFactory->create()->load($quoteId); return $quote->getCouponCode();
public function getAppliedCouponForItem($itemId)
<?php namespace YourNamespace\YourModule\Model; use Magento\SalesRule\Model\ResourceModel\Coupon\CollectionFactory; 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 getCouponCodeByOrderId(int $orderId): ?string
class GetAllCouponCodes
If you need to know which coupon affected a specific cart item (useful for per‑item discount debugging).
public function __construct( CartRepositoryInterface $quoteRepository, CustomerSession $customerSession, CheckoutSession $checkoutSession ) $this->quoteRepository = $quoteRepository; $this->customerSession = $customerSession; $this->checkoutSession = $checkoutSession;
$collection = $orderCollectionFactory->create() ->addFieldToFilter('entity_id', ['in' => $orderIds]) ->addFieldToSelect(['entity_id', 'coupon_code']); try $order = $this->
$collection = $this->couponCollectionFactory->create(); $collection->addFieldToSelect(['code', 'usage_limit', 'times_used', 'expiration_date']); $coupons = []; foreach ($collection as $coupon) $coupons[] = [ 'code' => $coupon->getCode(), 'usage_limit' => $coupon->getUsageLimit(), 'times_used' => $coupon->getTimesUsed(), 'expires_at' => $coupon->getExpirationDate() ]; return $coupons;
// For logged-in customers if ($this->customerSession->isLoggedIn()) $customerId = $this->customerSession->getCustomerId(); $quote = $this->quoteRepository->getActiveForCustomer($customerId); else // For guest customers $quote = $this->checkoutSession->getQuote();
public function execute()
class GetCouponFromOrder