Coupon Code Programmatically - Magento 2 Get
Coupon Code Programmatically - Magento 2 Get
public function __construct( CartRepositoryInterface $quoteRepository, OrderRepositoryInterface $orderRepository ) $this->quoteRepository = $quoteRepository; $this->orderRepository = $orderRepository;
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.
return $quote->getCouponCode();
class GetCouponCodeService
public function __construct( GetCouponCodeService $couponService, JsonFactory $resultJsonFactory ) $this->couponService = $couponService; $this->resultJsonFactory = $resultJsonFactory; magento 2 get coupon code programmatically
public function fromOrder(int $orderId): ?string
<?php namespace YourNamespace\YourModule\Controller\Index; use Magento\Framework\App\Action\HttpGetActionInterface; use Magento\Framework\Controller\Result\JsonFactory; use YourNamespace\YourModule\Model\GetCouponCodeService; OrderRepositoryInterface $orderRepository ) $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;
try $order = $this->orderRepository->get($orderId); return $order->getCouponCode(); catch (\Exception $e) return null; quoteRepository = $quoteRepository
private CartRepositoryInterface $quoteRepository; private OrderRepositoryInterface $orderRepository;