B-219 Sec-55 Noida, India
+918010221733

Creating a single random Magento coupon

For eg. If you want to automatically generate a single random coupon code in Magento each time someone subscribes to our newsletter. The coupon is 10 dollars off anything and will have an exp. date of two weeks after subscription.

<?php
/**
 * Create coupon for fixed price discount
 *
 * @param int $customer_id
 * @param float $discount
 */
public function createCoupon($customer_id, $discount)
{
    $customer = Mage::getModel(‘customer/customer’)->load($customer_id);

    $customerGroupIds = Mage::getModel(‘customer/group’)->getCollection()->getAllIds();
    $websitesId = Mage::getModel(‘core/website’)->getCollection()->getAllIds();

    $customer_name = $customer->getName();
    $couponCode = Mage::helper(‘core’)->getRandomString(9);

    $model = Mage::getModel(‘salesrule/rule’);
    $model->setName(‘Discount for ‘ . $customer_name);
    $model->setDescription(‘Discount for ‘ . $customer_name);
    $model->setFromDate(date(‘Y-m-d’));
    $model->setToDate(date(‘Y-m-d’, strtotime(‘+2 days’)));
    $model->setCouponType(2);
    $model->setCouponCode($couponCode);
    $model->setUsesPerCoupon(1);
    $model->setUsesPerCustomer(1);
    $model->setCustomerGroupIds($customerGroupIds);
    $model->setIsActive(1);
    $model->setConditionsSerialized(‘a:6:{s:4:”type”;s:32:”salesrule/rule_condition_combine”;s:9:”attribute”;N;s:8:”operator”;N;s:5:”value”;s:1:”1″;s:18:”is_value_processed”;N;s:10:”aggregator”;s:3:”all”;}’);
    $model->setActionsSerialized(‘a:6:{s:4:”type”;s:40:”salesrule/rule_condition_product_combine”;s:9:”attribute”;N;s:8:”operator”;N;s:5:”value”;s:1:”1″;s:18:”is_value_processed”;N;s:10:”aggregator”;s:3:”all”;}’);
    $model->setStopRulesProcessing(0);
    $model->setIsAdvanced(1);
    $model->setProductIds(”);
    $model->setSortOrder(1);
    $model->setSimpleAction(‘by_fixed’);
    $model->setDiscountAmount($discount);
    $model->setDiscountStep(0);
    $model->setSimpleFreeShipping(0);
    $model->setTimesUsed(0);
    $model->setIsRss(0);
    $model->setWebsiteIds($websitesId);

    try {
        $model->save();
    } catch (Exception $e) {
        Mage::log($e->getMessage());
    }
}

(Visited 97 times, 1 visits today)

Leave a reply

You must be logged in to post a comment.