Magento - Programmatically Creating A Sales Rule Coupon Code
By Lance Gliser
Published:
Heads up! This content is more than six months old. Take some time to verify everything still works as expected.
Had a request today for the system a Magento system to automatically create a coupon code using an existing sales rule (shopping cart rule). They wanted to control the requirements and logic in Magento's admin, but let a third party create coupon codes as required.
Version 2 - Formatted
// Get the rule in question $rule = Mage::getModel('salesrule/rule')->load(4); // Define a coupon code generator // Look at Mage_SalesRule_Model_Coupon_Massgenerator for options $generator = Mage::getModel('salesrule/coupon_massgenerator'); if( !empty($parameters['format']) ){ switch( strtolower($parameters['format']) ){ case 'alphanumeric': case 'alphanum': $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHANUMERIC ); break; case 'alphabetical': case 'alpha': $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHABETICAL ); break; case 'numeric': case 'num': $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_NUMERIC ); break; } } $generator->setDash( !empty($parameters['dash_every_x_characters'])? (int) $parameters['dash_every_x_characters'] : 0); $generator->setLength( !empty($parameters['length'])? (int) $parameters['length'] : 6); $generator->setPrefix( !empty($parameters['prefix'])? $parameters['prefix'] : ''); $generator->setSuffix( !empty($parameters['suffix'])? $parameters['suffix'] : ''); // Set the generator, and coupon type so it's able to generate $rule->setCouponCodeGenerator($generator); $rule->setCouponType( Mage_SalesRule_Model_Rule::COUPON_TYPE_AUTO ); // Get as many coupons as you required $count = !empty($parameters['count'])? (int) $parameters['count'] : 1; $codes = array(); for( $i = 0; $i < $count; $i++ ){ $coupon = $rule->acquireCoupon(); $coupon ->setType(Mage_SalesRule_Helper_Coupon::COUPON_TYPE_SPECIFIC_AUTOGENERATED) ->save(); $code = $coupon->getCode(); $codes[] = $code; } return $codes;
Version 1
// Get the rule in question $rule = Mage::getModel('salesrule/rule')->load(3); // Define a coupon code generator $generator = Mage::getModel('salesrule/coupon_codegenerator'); // Look at Mage_SalesRule_Model_Coupon_Codegenerator for options // Set the generator, and coupon type so it's able to generate $rule->setCouponCodeGenerator($generator); $rule->setCouponType( Mage_SalesRule_Model_Rule::COUPON_TYPE_AUTO ); // Get as many coupons as you required $coupon = $rule->acquireCoupon(); print $coupon->getCode();