I've created a program to automatically create coupon codes based on certain criteria for a user, the code generation works fine, and I can test that by sending the coupon code in through the URL(like this ?code=34o77134iy3). Copying and pasting that code and then pressing "apply discount"(34o77134iy3 in this case) applies the code correctly, but the code below does not apply it automatically.

$coupon = "34o77134iy3";


Edit: Upon further investigation, the ->collectTotals() line is what is resetting it to nothing.

Dumping ->getCouponCode() gives the coupon code until that is run.

I can also use the post coupon code to apply it but for some reason, I can't use any other method.

1 Answer 1


The below is the core code in Magento that validates the coupon submission in the cart.

As you can see, you might want to check the quote coupon code is the same as what you did submit and that is what will tell you whether the code is valid and successfully applied.

$codeLength = strlen($couponCode);
$isCodeLengthValid = $codeLength && $codeLength <= Mage_Checkout_Helper_Cart::COUPON_CODE_MAX_LENGTH;

$this->_getQuote()->setCouponCode($isCodeLengthValid ? $couponCode : '')

if ($codeLength) {
       if ($isCodeLengthValid && $couponCode == $this->_getQuote()->getCouponCode()) {
       $this->__('Coupon code "%s" was applied.', Mage::helper('core')->escapeHtml($couponCode))
} else {
       $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->escapeHtml($couponCode))
  • So basically just var_dump $quote->getCouponCode() and compare the result to what I passed in through $coupon?
    – joeybab3
    Commented Jul 17, 2019 at 20:05
  • Dumping Mage::getSingleton('checkout/cart')->getQuote()->getCouponCode() reveals an empty string, so it isn't being set successfully using the code I posted above.
    – joeybab3
    Commented Jul 17, 2019 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.