Magento – n event for apply coupon action in cart

addtocartcartcouponevent-observerproduct

I want to add a product to cart automatically when a coupon is applied. When the coupon is applied the product should be added to cart showing its price and a discount of the price of the product needs to be applied.

What I tried is created a coupon code which offers a fixed amount discount which is the price of the product that I want to add to cart. And then I observed the event salesrule_validator_process to check the coupon code applied and tried to add the product to cart. But when the coupon is applied in the cart the above event is fired thrice, so 3 quantities of the product is added to cart. Also every time the cart page is refreshed 2 quantities of the product is again added to cart.

EDIT :
How do I remove the product from cart when the coupon is cancelled.

Is there any event which gets fired only once when the coupon is applied or is there any other better method to attain what I want?

Best Answer

class NameSpace_Module_Model_Observer
{
    $productId = 1;
    $couponId = 'xyz';

    public function yourObserverMethod($observer)
    {
     $quote = $event->getQuote();
     $item = $event->getItem();
        // add
        if ($quote->getCouponCode() == $this->couponId && !in_array($this->productId, $item->getAllIds())){
            // add product
        }

         //remove
        if($quote->getCouponCode() != $this->couponId && in_array($this->productId, $item->getAllIds()){
             // remove product
        }
    }
}

See

Mage::dispatchEvent('salesrule_validator_process', array(
    'rule'    => $rule,
    'item'    => $item,
    'address' => $address,
    'quote'   => $quote,
    'qty'     => $qty,
    'result'  => $result,
));