Coupon code generation using Magento

Hello All,

I am writing here a script that will help you generate random coupon codes using Magento’s existing modules

$format = Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHANUMERIC;
$charset = Mage::helper('salesrule/coupon')->getCharset($format);
$del = Mage::helper('salesrule/coupon')->getCodeSeparator();

$l = 6; //length of the coupon code
$d = 0;
$pre = 'TT'; //prefix to be used
$suf = 'SS'; //suffix to be used
$storeCodes = array();
for($i=0;$i<100;$i++)
{
    //echo $i.'<br/>';
    $storeCodes[$i][0] = re($l,$d,$pre,$suf,$charset,$del);
}


function re($l,$d,$pre,$suf,$charset,$del)
{
    $length  = max(1,$l);
    $split   = max(0,$d);
    $suffix  = $suf;
    $prefix  = $pre;

    $splitChar = $del;

    $code = '';
    $charsetSize = count($charset);
    for ($i=0; $i<$length; $i++) {
        $char = $charset[mt_rand(0, $charsetSize - 1)];
        if ($split > 0 && ($i % $split) == 0 && $i != 0) {
            $char = $splitChar . $char;
        }
        $code .= $char;
    }

    $code = $prefix . $code . $suffix;
    return $code;
}

print_r($storeCodes);

Hope this is helpful

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top