I tried to generate coupon and apply to cart programmatically. With the following script coupon generate successfully but its not applied to cart, Even if tried to apply manually. If I just save this coupon code without any changes in admin panel and then applied to cart its works. I think I am missing something here. (I got this code from here)
$coupon_code = Mage::helper('core')->getRandomString(16);
$frm_date = Mage::getModel('core/date')->date('Y-m-d');
$to_date = date( "Y-m-d", strtotime( "+2 day", strtotime($frm_date) ) );
$data = array(
'product_ids' => null,
'name' => 'AUTO_GENERATION_Coupon',
'description' => null,
'is_active' => 1,
'website_ids' => array(1),
'customer_group_ids' => array(0,1),
'coupon_type' => 2,
'coupon_code' => $coupon_code,
'uses_per_coupon' => 1,
'uses_per_customer' => 1,
'from_date' => $frm_date,
'to_date' => $to_date,
'sort_order' => 100,
'is_advanced' => 1,
'is_rss' => 0,
'conditions' => array(
'1'=> array(
'type' => 'salesrule/rule_condition_combine',
'aggregator' => 'all',
'value' => 1,
'new_child' => null
),
'1--1' => array(
'type' => 'salesrule/rule_condition_address',
'attribute' => 'base_subtotal_with_discount_without_points',
'operator' => '>=',
'value' => 100
)
),
'simple_action' => 'by_percent',
'discount_amount' => $percent_offer,
'discount_qty' => 0,
'discount_step' => 0,
'apply_to_shipping' => 0,
'simple_free_shipping' => 0,
'stop_rules_processing' => 1,
'store_labels' => array('0' => "$percent_offer% Cart below value discount", '1' => "$percent_offer% Cart below value discount")
);
$model = Mage::getModel('salesrule/rule');
$data = $this->_filterDates($data, array('from_date', 'to_date'));
$validateResult = $model->validateData(new Varien_Object($data));
if ($validateResult == true) {
if (isset($data['simple_action']) && $data['simple_action'] == 'by_percent'
&& isset($data['discount_amount'])) {
$data['discount_amount'] = min(100, $data['discount_amount']);
}
if (isset($data['rule']['conditions'])) {
$data['conditions'] = $data['rule']['conditions'];
}
if (isset($data['rule']['actions'])) {
$data['actions'] = $data['rule']['actions'];
}
unset($data['rule']);
$model->loadPost($data);
$model->save();
Mage::getSingleton('checkout/cart')
->getQuote()
->setCouponCode(strlen($coupon_code) ? $coupon_code: '')
->collectTotals()
->save();
}
Please tell me what is missing?
$couponCode
defined in your code?->setCouponCode(strlen($couponCode) ? $couponCode : '')
seem to be alway null