Automatically add coupon in add to cart

You want to offer a product with a coupon discount but would like this done in one step. What you do not want is the customer having to click on a link to add the product to the cart and then have to enter the coupon code. This could be used in an email or some other promotion.

We can go about adding products to cart with coupons. One of the simplest and most effective ways is to use Magento’s observer and event handler. In this case we observer the checkout_cart_add_product_complete event and check for a coupon code. The end result is a url ending with /checkout/cart/add/product/27?coupon_code=abc123

This will take the coupon code and validate/apply it to the product in the cart before displaying the Magento cart page.

We will use the MCorner namespace for this example.
To start create the file app/etc/modules/MCorner_Checkout.xml to enable the module.

<?xml version="1.0"?>

Next create the following directory path app/code/community/MCorner/Checkout/etc.
Create the file config.xml with the following in it. This listens for the event and triggers the apply coupon functionality.

<?xml version="1.0"?>

Now create the directory app/code/community/MCorner/Checkout/Model.
Create the file Observer.php with the following in it. This is the Observer that actually tries to apply the coupon to the cart.


class MCorner_Checkout_Model_Observer extends Varien_Object

	public function applyCoupon(Varien_Event_Observer $observer) {
		$response = $observer->getResponse();
		$request  = $observer->getRequest();
		$couponCode = (string)$request->getParam('coupon_code');
		if (!$couponCode or !strlen($couponCode)) {
		$session    = Mage::getSingleton('checkout/session');
		$cart       = Mage::getSingleton('checkout/cart')->getQuote();
		$cart->setCouponCode(strlen($couponCode) ? $couponCode : '')

Clear your cache, confirm you have a coupon setup and that’s it.
Just a note you will need a valid coupon for the product or cart.