Often needed for order export, invoices, or customer history pages.
public function __construct( CartRepositoryInterface $quoteRepository, OrderRepositoryInterface $orderRepository ) $this->quoteRepository = $quoteRepository; $this->orderRepository = $orderRepository; magento 2 get coupon code programmatically
public function __construct(CollectionFactory $couponCollectionFactory) Often needed for order export, invoices, or customer
public function fromOrder(int $orderId): ?string Often needed for order export
try $quote = $this->quoteRepository->get($quoteId); return $quote->getCouponCode(); catch (NoSuchEntityException $e) return null;
$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;
$this->orderRepository = $orderRepository;