Magento 2 Get Coupon Code Programmatically -
<?php namespace YourNamespace\YourModule\Model; use Magento\SalesRule\Model\ResourceModel\Coupon\CollectionFactory;
// 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 __construct(CollectionFactory $couponCollectionFactory)
return $result; Useful for generating a dropdown of all existing coupon codes in admin or API. magento 2 get coupon code programmatically
public function getCurrentQuoteCouponCode(): ?string
use Magento\Quote\Model\QuoteFactory; public function getCouponCodeFromQuote(QuoteFactory $quoteFactory, $quoteId)
$collection = $orderCollectionFactory->create() ->addFieldToFilter('entity_id', ['in' => $orderIds]) ->addFieldToSelect(['entity_id', 'coupon_code']); ?php namespace YourNamespace\YourModule\Model
public function __construct( GetCouponCodeService $couponService, JsonFactory $resultJsonFactory ) $this->couponService = $couponService; $this->resultJsonFactory = $resultJsonFactory;
$this->couponCollectionFactory = $couponCollectionFactory;
try $quote = $this->quoteRepository->get($quoteId); return $quote->getCouponCode(); catch (NoSuchEntityException $e) return null; // For logged-in customers if ($this->
return $quote->getCouponCode();
public function __construct( CartRepositoryInterface $quoteRepository, CustomerSession $customerSession, CheckoutSession $checkoutSession ) $this->quoteRepository = $quoteRepository; $this->customerSession = $customerSession; $this->checkoutSession = $checkoutSession;