Programmatically create auto generated coupon codes in Magento?

若如初见. 提交于 2019-11-30 00:58:39

Thanks to a nifty post I found while googling this (http://fragmentedthought.com/fragments/programatically-creating-sales-rule-coupon-code), I answered my own question:

// Get the rule in question
$rule = Mage::getModel('salesrule/rule')->load(21); //21 = ID of coupon in question

// Define a coupon code generator model instance
// Look at Mage_SalesRule_Model_Coupon_Massgenerator for options
$generator = Mage::getModel('salesrule/coupon_massgenerator');

$parameters = array(
    'count'=>5,
    'format'=>'alphanumeric',
    'dash_every_x_characters'=>4,
    'prefix'=>'ABCD-EFGH-',
    'suffix'=>'-WXYZ',
    'length'=>8
);

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

This successfully generated the following codes:

ABCD-EFGH-ZC6V-ZJWD-WXYZ
ABCD-EFGH-4XMX-353L-WXYZ
ABCD-EFGH-XCJB-5GQI-WXYZ
ABCD-EFGH-UEAO-L1NJ-WXYZ
ABCD-EFGH-59B3-50T2-WXYZ
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!