Magento 1 – How to Generate and Get the Coupon Code

collection;couponmagento-1shopping-cart-price-rules

    $generator = Mage::getModel('salesrule/coupon_massgenerator');
    $data = array(
        'uses_per_customer' => 1,
        'uses_per_coupon'   => 1,
        'qty'               => 1,  //number of coupons to generate
        'length'            => 16, //length of coupon string
        'to_date'           => date('Y-m-d', strtotime("+1 month",  time())), //ending date of generated promo
        'prefix'            => 'rev',
        'suffix'            => 'tf',
        'dash'              => 5,
        /**
         * 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'         => 1 //the id of the rule you will use as a template
    );
    $generator->validateData($data);
    $generator->setData($data);
    $generator->generatePool();

    $salesRule = Mage::getModel('salesrule/rule')->load($data['rule_id']);
    $collection = Mage::getResourceModel('salesrule/coupon_collection')
                ->addRuleToFilter($salesRule)
                ->addGeneratedCouponsFilter();

I have this method to generate coupon code but how can I get a coupon code.

Best Answer

To get the last generated coupon code you will have to modify your collection like this:

$couponCode = Mage::getResourceModel('salesrule/coupon_collection')
                ->addRuleToFilter($salesRule)
                ->addGeneratedCouponsFilter()
                ->getLastItem()
                ->getData('code');

The two lines I've added get the last item and retrieve the corresponding code.

Related Topic