Magento has this facility in-built since 1.7CE.
The class Mage_SalesRule_Model_Coupon_Massgenerator
. To make use of it on your own you can instantiate the class:
$generator = Mage::getModel('salesrule/coupon_massgenerator');
You need to set some options:
$data = array(
'max_probability' => .25,
'max_attempts' => 10,
'uses_per_customer' => 1,
'uses_per_coupon' => 1,
'qty' => 5, //number of coupons to generate
'length' => 14, //length of coupon string
'to_date' => '2013-12-31', //ending date of generated promo
/**
* Possible values include:
* Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHANUMERIC
* Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHABETICAL
* Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_NUMERIC
*/
'format' => Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHANUMERIC,
'rule_id' => 1234 //the id of the rule you will use as a template
);
Validate that the $data is correct:
$generator->validateData($data);
And then save those options to the generator:
$generator->setData($data);
And now, GENERATE!
$generator->generatePool();
They're populated into salesrule_coupon
:
It works reasonably well - you'll have to fetch back out which coupons were generated though. To do that, you may look under "Manage Coupon Codes" tab of the shopping cart rules:
If you need to get them programmatically:
$salesRule = Mage::getModel('salesrule/rule')->load($data['rule_id']);
$collection = Mage::getResourceModel('salesrule/coupon_collection')
->addRuleToFilter($salesRule)
->addGeneratedCouponsFilter();
You can get a count of how many were generated successfully if you need:
$generator->getGeneratedCount();