Magento | 2 Get Coupon Code Programmatically
try $quote = $this->quoteRepository->get($quoteId); return $quote->getCouponCode(); catch (NoSuchEntityException $e) return null;
use Magento\Quote\Model\QuoteFactory; public function getCouponCodeFromQuote(QuoteFactory $quoteFactory, $quoteId)
class GetAllCouponCodes
<?php namespace YourNamespace\YourModule\Controller\Index; use Magento\Framework\App\Action\HttpGetActionInterface; use Magento\Framework\Controller\Result\JsonFactory; use YourNamespace\YourModule\Model\GetCouponCodeService; magento 2 get coupon code programmatically
try $order = $this->orderRepository->get($orderId); return $order->getCouponCode(); catch (\Exception $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;
class GetCouponFromOrder
public function __construct( CartRepositoryInterface $quoteRepository, CustomerSession $customerSession, CheckoutSession $checkoutSession ) $this->quoteRepository = $quoteRepository; $this->customerSession = $customerSession; $this->checkoutSession = $checkoutSession;
private GetCouponCodeService $couponService; private JsonFactory $resultJsonFactory;
$this->couponCollectionFactory = $couponCollectionFactory; try $quote = $this->
$result = $this->resultJsonFactory->create(); $couponCode = $this->couponService->fromCurrentSession(); return $result->setData([ 'success' => true, 'coupon_code' => $couponCode ?: 'No coupon applied' ]);
private CartRepositoryInterface $quoteRepository; private CustomerSession $customerSession; private CheckoutSession $checkoutSession;
return $quote->getCouponCode();
