I want to make a coupon time bound if a user registers on the website I will send him a coupon e.g. : CHJU20 that will be valid for only one month from the date of registering.

It should not apply after 1 month. Now if a new customer registers the same should happen with him too

1 Answer 1


I have created coupon code programmatically.

First of all you need to create shopping cart price rule in Magento Admin >> Promotions >> Shopping Cart Price Rules

Make sure coupon code should be auto generated. So you must have to select Use Auto Generation as per below screen shot.

enter image description here

Then you can use below code.

$rule = Mage::getModel('salesrule/rule')->load(1); //1 = ID of coupon 
$generator = Mage::getModel('salesrule/coupon_massgenerator');
$parameters = array(
    'count' => 1,
    'format' => 'alphanumeric',
    'prefix' => 'A', // if you require
    'suffix' => 'B', // if you require
    'length' => 6,
    'from_date' => '18/11/2017',
    'to_date' => '12/12/2017', // if require end date

if( !empty($parameters['format']) ){
  switch( strtolower($parameters['format']) ){
    case 'alphanumeric':
    case 'alphanum':
      $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHANUMERIC );
    case 'alphabetical':
    case 'alpha':
      $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHABETICAL );
    case 'numeric':
    case 'num':
      $generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_NUMERIC );
$generator->setLength(!empty($parameters['length']) ? (int) $parameters['length'] : 6);
$generator->setPrefix(!empty($parameters['prefix']) ? $parameters['prefix'] : '');
$generator->setSuffix(!empty($parameters['suffix']) ? $parameters['suffix'] : '');

$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();
  $code = $coupon->getCode();
  $codes[] = $code;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.