magento 后台有相应的优惠券等功能,如果我们需要自己开发该类功能,不用后台功能,更简洁的应在magento主题模板上。可以采用以下代码:
<?php
// load product
/** @var Mage_Catalog_Model_Product $product */
$product = Mage::getModel('catalog/product')
->setStoreId($storeId)
->load($productId);
// set length of coupon code
/** @var Mage_SalesRule_Model_Coupon_Codegenerator $generator */
$generator = Mage::getModel('salesrule/coupon_codegenerator')
->setLength(8);
/** @var Mage_SalesRule_Model_Rule_Condition_Product $conditionProduct */
$conditionProduct = Mage::getModel('salesrule/rule_condition_product')
->setType('salesrule/rule_condition_product')
->setAttribute('sku')
->setOperator('==')
->setValue($product->getSku());
/** @var Mage_SalesRule_Model_Rule_Condition_Product_Found $conditionProductFound */
$conditionProductFound = Mage::getModel('salesrule/rule_condition_product_found')
->setConditions(array($conditionProduct));
/** @var Mage_SalesRule_Model_Rule_Condition_Combine $condition */
$condition = Mage::getModel('salesrule/rule_condition_combine')
->setConditions(array($conditionProductFound));
/** @var Mage_SalesRule_Model_Coupon $coupon */
$coupon = Mage::getModel('salesrule/coupon');
// try to generate unique coupon code
$attempts = 0;
do {
if ($attempts++ >= 8) {
Mage::throwException(Mage::helper('mymodule')->__('Unable to create requested Coupons. Please try again.'));
}
$code = $generator->generateCode();
} while ($coupon->getResource()->exists($code));
// create rule
/** @var Mage_SalesRule_Model_Rule $rule */
$rule = Mage::getModel('salesrule/rule');
$rule->setName(Mage::helper('mymodule')->__('Name of the coupon'))
->setDescription($rule->getName())
->setFromDate(date('Y-m-d'))
->setCustomerGroupIds($this->_getCustomerGroups())
->setIsActive(1)
->setConditionsSerialized(serialize($condition->asArray()))
//->setActionsSerialized
//->setStopRulesProcessing
//->setIsAdvanced
->setSimpleAction(Mage_SalesRule_Model_Rule::BY_FIXED_ACTION)
->setDiscountAmount($product->getFinalPrice())
->setDiscountQty(1)
//->setDiscountStep
->setStopRulesProcessing(0)
->setIsRss(0)
->setWebsiteIds(array(1))
->setCouponType(Mage_SalesRule_Model_Rule::COUPON_TYPE_SPECIFIC)
->setConditions($condition)
->save();
// create coupon
$coupon->setId(null)
->setRuleId($rule->getRuleId())
->setCode($code)
->setUsageLimit(1)
//->setUsagePerCustomer
//->setTimesUsed
//->setExpirationDate
->setIsPrimary(1)
->setCreatedAt(time())
->setType(Mage_SalesRule_Helper_Coupon::COUPON_TYPE_SPECIFIC_AUTOGENERATED)
->save();
?>
(责任编辑:好模板) |