0

I have tried every different combo of model that returns a quote in order to try and find the one that has the quote for the current customer's cart.

So far none of them work, and I can't figure out why this might be.

Essentially I'm running an external script in the misc directory that sets a generated coupon code on the current cart, but none of the following set the code correctly and I have to default to redirecting to /checkout/cart/coupon/post or whatever the correct url is for that.

Here are the different models I have tried for getting the session:

$session = Mage::getSingleton("customer/session");
$session = Mage::getSingleton('checkout/session');
$session = Mage::getSingleton('core/session');
$session = Mage::getSingleton("core/session",  array("name"=>"frontend"));

And these are the different method's I've tried to run on the quote:

$quote->getShippingAddress()->setCollectShippingRates(true);
$quote->setCartCouponCode($coupon);
$quote->setCouponCode($coupon);
$quote->collectTotals();
$quote->save();

They don't fail but they also do not set the code correctly.

1 Answer 1

0

Try this:

<?php
$mageFilename = 'app/Mage.php';
if (!file_exists($mageFilename)) {
    echo $mageFilename . " was not found";
    exit;
}
require_once $mageFilename;
Mage::app();

// This has to run to authenticate customer and checkout session calls.
Mage::getSingleton('core/session', array('name' => 'frontend'));

$quote = Mage::getSingleton('checkout/session')->getQuote();

$couponCode = "COUPON_TEST"; // Make sure to use the valid coupon here

$quote->getShippingAddress()->setCollectShippingRates(true);
$quote->setCouponCode($couponCode);
$quote->setTotalsCollectedFlag(false);
$quote->collectTotals();

$quote->save();

die("Applied coupon $couponCode successfully!");
15
  • Rather than echo $couponcode, it might be better to echo $quote->getCouponCode() since that's usually where I figure out it didn't set correctly but thanks I will try this now.
    – joeybab3
    Commented Aug 15, 2019 at 16:51
  • Unfortunately, this did not apply a coupon code for me it still has no coupon code when getting to checkout :(
    – joeybab3
    Commented Aug 15, 2019 at 17:09
  • Did you use the correct coupon code instead of "COUPON_TEST"?
    – Toan Tam
    Commented Aug 15, 2019 at 17:14
  • Yes, I cut and pasted all parts of your code but replaced $couponCode with my own variable that I know contains a working code because it can be passed through the url to be applied.
    – joeybab3
    Commented Aug 15, 2019 at 17:15
  • I tested it and it worked fine on my end. Did you try to create a file in the webroot folder and then testing it?
    – Toan Tam
    Commented Aug 15, 2019 at 17:31

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.