Magento 2 Get Coupon Code Programmatically ✦ Bonus Inside
class GetAllCouponCodes
use Magento\Quote\Model\QuoteFactory; public function getCouponCodeFromQuote(QuoteFactory $quoteFactory, $quoteId)
<?php declare(strict_types=1); namespace YourNamespace\YourModule\Model;
Often needed for order export, invoices, or customer history pages. magento 2 get coupon code programmatically
$this->orderRepository = $orderRepository;
If you need to know which coupon affected a specific cart item (useful for per‑item discount debugging).
private CartRepositoryInterface $quoteRepository; private CustomerSession $customerSession; private CheckoutSession $checkoutSession; Often needed for order export
$this->couponCollectionFactory = $couponCollectionFactory;
class GetCouponCodeService
// 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(); or customer history pages. $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;
<?php namespace YourNamespace\YourModule\Model; use Magento\Sales\Api\OrderRepositoryInterface;
class GetCouponFromOrder
use Magento\Quote\Api\CartRepositoryInterface; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Framework\Exception\NoSuchEntityException;
