Programmatically creating a coupon (including the rule) with conditions in Magento

Posted on Tue May 22, 2012 by Jeroen Derks There have been 9 comment(s)

For one of my projects I needed to programmatically create a random coupon for a specific product in Magento. Since I did not find an exact sample that I could use I decided to post my solution here.

NB: Please note that this post is a work-in-progress, your mileage may vary, so please test thorougly before using this solution in a production environment.
Please let me know if you find any problems with this solution. Thanks!

<?php
    // load product
    /** @var Mage_Catalog_Model_Product $product */
    $product = Mage::getModel('catalog/product')
                    ->setStoreId($storeId)
                    ->load($productId);

    // set length of coupon code
    /** @var Mage_SalesRule_Model_Coupon_Codegenerator $generator */
    $generator = Mage::getModel('salesrule/coupon_codegenerator')
                        ->setLength(8);
    /** @var Mage_SalesRule_Model_Rule_Condition_Product $conditionProduct */
    $conditionProduct = Mage::getModel('salesrule/rule_condition_product')
                                                ->setType('salesrule/rule_condition_product')
                                                ->setAttribute('sku')
                                                ->setOperator('==')
                                                ->setValue($product->getSku());
                                                
    /** @var Mage_SalesRule_Model_Rule_Condition_Product_Found $conditionProductFound */
    $conditionProductFound = Mage::getModel('salesrule/rule_condition_product_found')
                                            ->setConditions(array($conditionProduct));
    /** @var Mage_SalesRule_Model_Rule_Condition_Combine $condition */
    $condition = Mage::getModel('salesrule/rule_condition_combine')
                    ->setConditions(array($conditionProductFound));
                                                
    /** @var Mage_SalesRule_Model_Coupon $coupon */
    $coupon = Mage::getModel('salesrule/coupon');
    // try to generate unique coupon code
    $attempts = 0;
    do {
        if ($attempts++ >= 8) {
            Mage::throwException(Mage::helper('mymodule')->__('Unable to create requested Coupons. Please try again.'));
        }
        $code = $generator->generateCode();
    } while ($coupon->getResource()->exists($code));

    // create rule
    /** @var Mage_SalesRule_Model_Rule $rule */
    $rule = Mage::getModel('salesrule/rule');
    $rule->setName(Mage::helper('mymodule')->__('Name of the coupon'))
        ->setDescription($rule->getName())
        ->setFromDate(date('Y-m-d'))
        ->setCustomerGroupIds($this->_getCustomerGroups())
        ->setIsActive(1)
        ->setConditionsSerialized(serialize($condition->asArray()))
        //->setActionsSerialized     
        //->setStopRulesProcessing 
        //->setIsAdvanced                     
        ->setSimpleAction(Mage_SalesRule_Model_Rule::BY_FIXED_ACTION)
        ->setDiscountAmount($product->getFinalPrice())
        ->setDiscountQty(1)
        //->setDiscountStep                     
        ->setStopRulesProcessing(0)
        ->setIsRss(0)
        ->setWebsiteIds(array(1))
        ->setCouponType(Mage_SalesRule_Model_Rule::COUPON_TYPE_SPECIFIC)
        ->setConditions($condition)
        ->save();            
    
    // create coupon
    $coupon->setId(null)
        ->setRuleId($rule->getRuleId())
        ->setCode($code)
        ->setUsageLimit(1)
        //->setUsagePerCustomer
        //->setTimesUsed
        //->setExpirationDate
        ->setIsPrimary(1)
        ->setCreatedAt(time())
        ->setType(Mage_SalesRule_Helper_Coupon::COUPON_TYPE_SPECIFIC_AUTOGENERATED)
        ->save();

Please let me know if this works for you or not!


This post was posted in Magento, Development

9 Responses to Programmatically creating a coupon (including the rule) with conditions in Magento

  • I am very new to magento. I would like to know if you can guide me a bit on my scenario. I have an existing Shopping Cart Price rule setup in magento. I just need to generate more coupons programatically for this price rule.

    Actually, we want to send coupon code to our customer. We want to make if fail safe, We currently pick an unused coupon from DB and send the code in email. We want the ability to generate the coupon on the fly if there are no more coupon codes available in DB that can be used.

    Please help on this

    Posted on Fri July 27, 2012 at 23:04

  • Thanks for your message. Using (parts of) the code in this example you should be able to create a new coupon on the fly when you need it. Good luck!

    Posted on Sun July 29, 2012 at 15:08

  • Very Nice Article Jeroen..

    www.ilovemagento.com

    Posted on Sat September 15, 2012 at 11:10

  • Kalpesh says:

    This one is really good. I came across this requirement in past, it consumed much time. You should have posted this early :P

    Posted on Thu October 11, 2012 at 12:21

  • Hi Jeroen ,

    Nice magento article, thanks for sharing this information. Looking forward for more posts like this.








    Magento Developers

    Posted on Sat July 20, 2013 at 11:47

  • Adam says:

    Came across this as this is what I'm trying to do and have little knowledge of Magento programming.

    Looking through your code i understand all of it except this bit

    $rule->setName(Mage::helper('mymodule')->__('Name of the coupon'))

    What goes in the mymodule helper?

    Posted on Tue March 25, 2014 at 10:15

  • Lindsey says:

    Thanks for the article! I found it while looking how to create coupons in Magento for Groupon deals. I've also found one good extension generate and import coupons by amasty, it can show all the usage info for each coupon. Do you have experience with it or can you recommend anything else?
    Thanks

    Posted on Mon December 15, 2014 at 11:44

  • HI ,

    Please find the below link for Creating Shopping Cart Rules Programatically

    http://www.demacmedia.com/magento-commerce/mini-tutorial-creating-shopping-cart-rules-programatically/

    Posted on Wed August 19, 2015 at 15:59

  • Rocky says:

    Hey it give error like SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails please help !!

    Posted on Tue February 23, 2016 at 11:44

Comments