• DE
  • EN
  • ES
  • NL

Blog

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


This article originally appeared on the Magentron blog as Programmatically creating a coupon (including the rule) with conditions in Magento.

Posted on Tuesday, May 22nd, 2012 by Jeroen Derks.

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!

Need help with PHP, Magento or Laravel? Feel free to get in touch.