Magento Forum

   
Generate unique coupon code via API? 
 
Andre N
Sr. Member
 
Avatar
Total Posts:  186
Joined:  2009-12-09
CA
 

What I would like to do is be able to generate a unique coupon code for 15% off that will expire in 2 days, using api (soap v2).
On my website (xtremelean.us) there are quizzes the user can take. You can find them if you look in the left blocks on any page. When the user scores 100% on a quiz I would like to generate this unique coupon code just for them.
The way it is set up now, the code is static so anyone can post it on the internet or give it to others or whatever.
Is this something that can be done?
Thanks in advance smile

 
Magento Community Magento Community
Magento Community
Magento Community
 
Jakub@WebCatch
Sr. Member
 
Avatar
Total Posts:  215
Joined:  2009-11-06
Nottingham, UK
 

You would need to create the coupon in your own code. You might also get a module developed which will tie this coupon to the account of the user who did the quiz…

 
Magento Community Magento Community
Magento Community
Magento Community
 
Andre N
Sr. Member
 
Avatar
Total Posts:  186
Joined:  2009-12-09
CA
 

Hi, thanks for replying!

Generating the coupon code is the easy part :D

How could I activate it using the api? It wouldn’t need to be customer specific because lots of people aren’t logged in, as long as it expires fairly quickly I won’t have to worry about the code leaking out.

Thanks!

 
Magento Community Magento Community
Magento Community
Magento Community
 
Andre N
Sr. Member
 
Avatar
Total Posts:  186
Joined:  2009-12-09
CA
 

What if I were to generate this coupon code and just write it and its params directly into the Magento db… would that work?
I don’t have the db in front of me so I don’t know how it’s set up but I’d assume the coupon code isn’t hashed or anything… I’ll post back any results I get when I’ve had a chance to try this out, unless someone has a better idea or any insight into this…
Thanks!
smile

 
Magento Community Magento Community
Magento Community
Magento Community
 
Jakub@WebCatch
Sr. Member
 
Avatar
Total Posts:  215
Joined:  2009-11-06
Nottingham, UK
 

Writing it directly to db should work as expected, as long as you have all the coupons’ db structure covered…

 
Magento Community Magento Community
Magento Community
Magento Community
 
Andre N
Sr. Member
 
Avatar
Total Posts:  186
Joined:  2009-12-09
CA
 

I got it working with Magento version 1.3.2.4

Here is the code I used if anyone else wants to do this. You will need to define a couple variables like $quiz_fullname which are in this that I defined elsewhere. Should be pretty easy to figure out

//function to create 8 digit alphanumeric coupon code
    function createCouponCode() {
    $chars 
"ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
    
srand((double)microtime()*1000000);
    
$i 0;
    
$code '' ;
    while (
$i <= 7)
    
{
        $num 
rand() % 33;
        
$tmp substr($chars$num1);
        
$code $code $tmp;
        
$i++;
    
}
    
return $code;}
    
    
//generate the code, set it in session var so it is not generated again
    
$_SESSION[$quiz_name]['coupon'createCouponCode();
    (string)
$coupon_code $_SESSION[$quiz_name]['coupon'];
    (string)
$coupon_name $quiz_fullname.' coupon';
    (string)
$coupon_description 'For scoring 100% on our '.$quiz_fullname;
    (string)
$conditions_serialized 'a:7:{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\";s:10:\"conditions\";a:1:{i:0;a:5:{s:4:\"type\";s:32:\"salesrule/rule_condition_address\";s:9:\"attribute\";s:13:\"base_subtotal\";s:8:\"operator\";s:2:\">=\";s:5:\"value\";s:5:\"50.00\";s:18:\"is_value_processed\";b:0;}}}';
    (string)
$actions_serialized '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\";}';
    (string)
$coupon_from_date date('Y-m-d');
    
//the coupon will be good for 2 days and expire on the third I guess?
    
(int)$coupon_expiration_date time() + (24 60 60);
    (string)
$coupon_to_date date('Y-m-d'$coupon_expiration_date);

    
//set up the coupon data
    
$coupon_vars = array(
        
'name' => "'$coupon_name'",
        
'description' => "'$coupon_description'",
        
'from_date' => "'$coupon_from_date'",
        
'to_date' => "'$coupon_to_date'",
        
'coupon_code' => "'$coupon_code'",
        
'uses_per_coupon' => '1',
        
'uses_per_customer' => '1',
        
'customer_group_ids' => "'0,1,2,3'",
        
'is_active' => 1,
        
'conditions_serialized' => "'$conditions_serialized'",
        
'actions_serialized' => "'$actions_serialized'",
        
'stop_rules_processing' => 1,
        
'is_advanced' => 1,
        
'product_ids' => "''",
        
'sort_order' => "'0'",
        
'simple_action' => "'by_percent'",
        
'discount_amount' => "'15.0000'",
        
'discount_qty' => "'999.0000'",
        
'discount_step' => "'0'",
        
'simple_free_shipping' => 0,
        
'times_used' => "'0'",
        
'is_rss' => 0,
        
'website_ids' => "'1'",
    );

    
$magento_db 'localhost';
    
$mdb_user 'db user';
    
$mdb_passwd 'db password';
    
$mdb_name 'db name';
    
$magento_connection = @mysql_connect($magento_db$mdb_user$mdb_passwd);
    if (!
$magento_connection)
    
{
        
die('Unable to connect to the Magento database');
    
}
    
@mysql_select_db($mdb_name$magento_connection) or die ("Magento Database not found.");

    
$query "
          INSERT INTO salesrule
          (" 
implode(', 'array_keys($coupon_vars)) . ")
          VALUES (" 
implode(', '$coupon_vars) . ')';
    
    @
mysql_db_query($mdb_name$query) or die("Failed Query of ".$query);
    
$coupon_rule_id = @mysql_insert_id($magento_connection);

So with this code generated they get 15% off any order over $50. It expires in 2 (3?) days and can be used only once. I’ve tested it and it works. If you want a different coupon just change the coupon variables. If you’re not sure what they should be create a coupon in Magento admin and then get the variables out of the db (salesrule).

smile

 
Magento Community Magento Community
Magento Community
Magento Community
 
jward1983
Jr. Member
 
Total Posts:  17
Joined:  2009-06-15
 

Stumbled across this thread while looking for the best way to do exactly what this thread is going for - create a coupon code programatically instead of in the Admin control panel.

I am building a Refer-a-Friend module for a client right now - they have some specific reqs that don’t make it feasible to use one of the community-built modules for this. Anyway when a registered user refers someone it needs to create a coupon code on the fly for the referral for use by the person who gets referred to the website.

My own implementation is somewhat different but I figured I would post it here in case anyone else searches for this sort of thing and finds it.

Here is how I did it:

public function createCouponForReferral($couponCode)
    
{
        $model 
Mage::getModel('salesrule/rule');

        
$model->setName($couponCode);
        
$model->setDescription('Discount coupon for Refer-a-Friend program.');
        
$model->setFromDate(date('Y-m-d'));
        
$model->setCouponCode($couponCode);
        
$model->setUsesPerCoupon(1);
        
$model->setUsesPerCustomer(1);
        
$model->setCustomerGroupIds('0,1');
        
$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(5);
        
$model->setDiscountStep(0);
        
$model->setSimpleFreeShipping(0);
        
$model->setTimesUsed(0);
        
$model->setIsRss(0);
        
$model->setWebsiteIds('1');

        
$model->save();
    
}

You shouldn’t need to write direct SQL to insert the record nor expose your database connection login properties. I’m obviously generating the coupon using a custom function outside of this call so I’m injecting it into the signature of the function, but you get the idea and can write it any way you want.

The best way to create the action rules and condition rules is to go into the Admin control panel and create a dummy coupon with the generic rules for your coupon and save the rule - go to phpMyAdmin and view the contents in the salesrule table in the database and copy/paste the values for the actions and conditions rules. Obviously you need to escape the double quotes when you inject the string into the setter function. Delete the dummy coupon when you’re done, of course.

Hope this helps someone.

 
Magento Community Magento Community
Magento Community
Magento Community
 
LeeSaferite
Guru
 
Avatar
Total Posts:  322
Joined:  2007-08-31
Lake City, FL
 

This was for a specific requirement, but it should give some more ideas.  Including the serialized coupon data as something hard-coded is always a bad idea.  Using this code as a reference you could easily re-write your code to use a master coupon as a template for the unique coupons.

<?php

class LKC_Goodies_Block_Email_TemplatedCouponLink extends Mage_Core_Block_Abstract
{

    
protected function _toHtml()
    
{
        $html 
'';

        
$masterCouponCode trim($this->getMasterCouponCode());
        if (empty(
$masterCouponCode))
        
{
            
return '';
        
}

        $masterCoupon 
Mage::getModel('salesrule/rule')->load($masterCouponCode'coupon_code');
        if (!
$masterCoupon || ! $masterCoupon->getId())
        
{
            
return '';
        
}

        $couponCodePrefix 
trim($this->getCouponCodePrefix());
        
$couponCodeSuffix trim($this->getCouponCodeSuffix());
        
$couponCode strtoupper($couponCodePrefix $couponCodeSuffix);
        if (empty(
$couponCode))
        
{
            
return '';
        
}

        
try
        
{
            $coupon 
Mage::getModel('salesrule/rule')->load($couponCode'coupon_code');
            if (!
$coupon || ! $coupon->getId())
            
{
                $coupon 
$masterCoupon;

                
$coupon->setId(null);
                
$coupon->setCouponCode($couponCodePrefix $couponCodeSuffix);
                
$couponNameTemplate trim($this->getCouponNameTemplate());
                if (empty(
$couponNameTemplate))
                
{
                    $coupon
->setName($coupon->getCouponCode());
                
}
                
else
                
{
                    $coupon
->setName(sprintf($couponNameTemplate$coupon->getCouponCode()));
                
}
                $coupon
->save();
            
}

            $linkTemplate 
$this->getLinkTemplate();
            
$linkTemplate = (empty($linkTemplate) ? '<a href="%1$s">%2$s</a>' $linkTemplate);

            
$url Mage::getUrl('checkout/cart/couponPost', array('coupon_code' => $coupon->getCouponCode()));

            
$text htmlspecialchars($this->__($this->getText()), ENT_QUOTES'UTF-8'false);

            
$html .= sprintf($linkTemplate$url$text);
        
}
        
catch (Exception $e)
        
{
            $html 
'';

            
$message $this->__('Error creating Templated Coupon (%1$s) using Master Coupon (%2$s).'$couponCode$masterCouponCode);

            
Mage::log($messageZend_Log::ERR);
            
Mage::logException($e);
        
}

        
return $html;
    
}

}

 
Magento Community Magento Community
Magento Community
Magento Community
 
afmaury
Sr. Member
 
Total Posts:  100
Joined:  2008-01-05
 

Would it be possible to use a version of these scripts to import a group of coupon codes at once? It would be nice to be able to create a csv file with multiple coupon codes and import them. Has anyone done this?

 
Magento Community Magento Community
Magento Community
Magento Community
 
sn1pereagle
Jr. Member
 
Total Posts:  27
Joined:  2008-12-19
 

Hello,

In the example of jward1983

How do i return the value of the generated couponcode..

I can;t get it to work.

 
Magento Community Magento Community
Magento Community
Magento Community
 
Andre N
Sr. Member
 
Avatar
Total Posts:  186
Joined:  2009-12-09
CA
 

jaward’s example doesn’t generate a coupon code. You need to generate it first and send it into the function to create the coupon. I’m trying to use that code for 1.4.1.1 but it’s not fully working. It generates the coupon, but the actions and conditions aren’t accepted and the coupon code itself isn’t accepted. When I say not accepted, I mean the values aren’t there when I go into the admin side and look at the coupon I’ve created…

 
Magento Community Magento Community
Magento Community
Magento Community
 
videohead
Jr. Member
 
Total Posts:  22
Joined:  2010-10-14
 

I am working on this today and will post my success.
“Do, or do not . . . there is no try.” - Yoda

 
Magento Community Magento Community
Magento Community
Magento Community
 
key
Member
 
Avatar
Total Posts:  59
Joined:  2008-07-16
beijing.china
 
Lee Saferite - 07 June 2010 08:38 AM

This was for a specific requirement, but it should give some more ideas.  Including the serialized coupon data as something hard-coded is always a bad idea.  Using this code as a reference you could easily re-write your code to use a master coupon as a template for the unique coupons.

<?php

class LKC_Goodies_Block_Email_TemplatedCouponLink extends Mage_Core_Block_Abstract
{

    
protected function _toHtml()
    
{
        $html 
'';

        
$masterCouponCode trim($this->getMasterCouponCode());
        if (empty(
$masterCouponCode))
        
{
            
return '';
        
}

        $masterCoupon 
Mage::getModel('salesrule/rule')->load($masterCouponCode'coupon_code');
        if (!
$masterCoupon || ! $masterCoupon->getId())
        
{
            
return '';
        
}

        $couponCodePrefix 
trim($this->getCouponCodePrefix());
        
$couponCodeSuffix trim($this->getCouponCodeSuffix());
        
$couponCode strtoupper($couponCodePrefix $couponCodeSuffix);
        if (empty(
$couponCode))
        
{
            
return '';
        
}

        
try
        
{
            $coupon 
Mage::getModel('salesrule/rule')->load($couponCode'coupon_code');
            if (!
$coupon || ! $coupon->getId())
            
{
                $coupon 
$masterCoupon;

                
$coupon->setId(null);
                
$coupon->setCouponCode($couponCodePrefix $couponCodeSuffix);
                
$couponNameTemplate trim($this->getCouponNameTemplate());
                if (empty(
$couponNameTemplate))
                
{
                    $coupon
->setName($coupon->getCouponCode());
                
}
                
else
                
{
                    $coupon
->setName(sprintf($couponNameTemplate$coupon->getCouponCode()));
                
}
                $coupon
->save();
            
}

            $linkTemplate 
$this->getLinkTemplate();
            
$linkTemplate = (empty($linkTemplate) ? '<a href="%1$s">%2$s</a>' $linkTemplate);

            
$url Mage::getUrl('checkout/cart/couponPost', array('coupon_code' => $coupon->getCouponCode()));

            
$text htmlspecialchars($this->__($this->getText()), ENT_QUOTES'UTF-8'false);

            
$html .= sprintf($linkTemplate$url$text);
        
}
        
catch (Exception $e)
        
{
            $html 
'';

            
$message $this->__('Error creating Templated Coupon (%1$s) using Master Coupon (%2$s).'$couponCode$masterCouponCode);

            
Mage::log($messageZend_Log::ERR);
            
Mage::logException($e);
        
}

        
return $html;
    
}

}

Good idea!!!

 
Magento Community Magento Community
Magento Community
Magento Community
 
johnrau
Member
 
Total Posts:  36
Joined:  2011-06-12
 

Hey guys, really nice code here.

Just as a note for the first example by iturner - you could perform a check in the database by doing a SELECT on the coupon_code field to make sure you\’re not adding a code that already exists.

Again thanks for saving me a lot of time

-John

 
Magento Community Magento Community
Magento Community
Magento Community
 
MagePsycho
Moderator
 
Avatar
Total Posts:  1702
Joined:  2009-06-23
 

Recently i used this article:
http://marius-strajeru.blogspot.com/2010/04/create-bulk-discount-rules.html
and it worked like a charm.

Thanks

 
Magento Community Magento Community
Magento Community
Magento Community
Magento Community
Magento Community
    Back to top