Magento 2 — Get Coupon Code Programmatically
<?php namespace YourNamespace\YourModule\Controller\Index; use Magento\Framework\App\Action\HttpGetActionInterface; use Magento\Framework\Controller\Result\JsonFactory; use YourNamespace\YourModule\Model\GetCouponCodeService;
try $order = $this->orderRepository->get($orderId); return $order->getCouponCode(); catch (NoSuchEntityException $e) return null;
public function __construct( GetCouponCodeService $couponService, JsonFactory $resultJsonFactory ) $this->couponService = $couponService; $this->resultJsonFactory = $resultJsonFactory; magento 2 get coupon code programmatically
private CartRepositoryInterface $quoteRepository; private OrderRepositoryInterface $orderRepository;
public function execute()
public function fromQuote(int $quoteId): ?string
private CollectionFactory $couponCollectionFactory; ?php namespace YourNamespace\YourModule\Controller\Index
If you need to know which coupon affected a specific cart item (useful for per‑item discount debugging).