0

i want to apply coupon code from external script, that will set code and discount amount to quote and final result will be saved quote with new total. I have done following but not saving quote.

        $quoteid = "53701";
    $couponCode = "Discount99";
    $oCoupon = Mage::getModel('salesrule/coupon')->load(trim($couponCode), 'code');
    $oRule = Mage::getModel('salesrule/rule')->load($oCoupon->getRuleId());

    if($oRule->getRuleId() && $oRule->getRuleId() > 0){
        try{
            $quoteObj = Mage::getModel('sales/quote')->setCouponCode($oCoupon)->load($quoteid);
            $quoteObj->setTotalsCollectedFlag(true)
                ->collectTotals()
                ->save();
            $returndata["success"] = "1";
            $returndata["message"] = "Coupon Applied Successfully";
            $returndata["data"]["discount_amount"] = $oRule->getDiscountAmount();
        }catch (Exception $e){
            $returndata["success"] = "0";
            $returndata["message"] = "Cart Coupon update Failed";
            $returndata["data"] = null;
        }
    }else{
        $returndata["success"] = "0";
        $returndata["message"] = "Invalid Coupon";
        $returndata["data"] = null;
    }
    echo json_encode($returndata);
    exit;
1

You can do this following way..

$quoteid = '53703';
$couponCode = "cvpcode2013";

$oCoupon = Mage::getModel('salesrule/coupon')->load(trim($couponCode), 'code');
$oRule = Mage::getModel('salesrule/rule')->load($oCoupon->getRuleId());

if($oRule->getRuleId() && $oRule->getRuleId() > 0){
    try{
        $quote = $this->_getQuote($quoteid,Mage::app()->getStore()->getStoreId());
        $quote->setCouponCode($couponCode);
        $quote->setTotalsCollectedFlag(false)->collectTotals();
        $quote->collectTotals();
        $quote->save();
    }catch (Exception $e){
            echo $e->getMessage();
    }
}else{
    // invalid coupon
}

// create new function 

protected function _getQuote($quoteId, $store = null)
{

        $quote = Mage::getModel("sales/quote");
        if (!(is_string($store) || is_integer($store))) {
            $quote->loadByIdWithoutStore($quoteId);
        } else {
            $storeId = $store;

            $quote->setStoreId($storeId)
                    ->load($quoteId);
        }
        if (is_null($quote->getId())) {
            $this->_fault('quote_not_exists');
        }

        return $quote;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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