Programmatically Create Auto-Generated Coupon Codes in Magento 1

In Magento, you can generate batches of discount coupon codes based on a shopping cart rule from the backend.

But you may ask how I can generate coupon codes programmatically on request. For example,  you may want to automatically generate a random 10% OFF coupon codes whenever you have a new subscriber and send it to them.

This post will walk you through the essential steps to create an auto-generate coupon code in Magento.

Step 1. Create a Shopping Cart Price Rule in Magento

Before we jump onto coding,  first we will need to create a shopping cart price rule. All codes generated programmatically later will be under this rule.

If you’ve already known how to create a promo rule that uses auto-generated codes, you can skip reading this step.

Go to your Magento backend, and then find Promotions –> Shopping Cart Price Rule from the top menu.

Set up a desired rule for your promotion.  Go through the basic info of your rule, and the condition,  the discount amount. You should be familiar with these. If not, you can find some instruction here >>

A couple things we should be careful when we create the rule: see the screenshot below:

Magento auto generated coupon

1. Select Coupon drop-down to be ‘Specific Coupon‘, which means this rule will be triggered by applying a coupon in cart.

2. Check the Use Auto Generation Coupon checkbox, which means this rule uses auto-generated unique code(a random string), instead of a general coupon code.

3. We should also give Uses per Coupon 1 because each code is meant to be unique and it should be single-use only. Otherwise, the person receive this coupon can use it multiple times or even pass it to other people.

Step 2. Load the Promo Rule You Just Created

Now, it is time to write some code. First, let’s load the rule we just created:

You can find the Id of your rule in the rule list (Promotions –> Shopping Cart Price Rule), Ids are in the first column.

Step 2. Format Coupon Code

Using an array to format the code we are going to create. Basically, there are 5 arguments we can change to get a specific format:

format:  alphanumeric | alphabetical | numeric

length: the length of the code, how many characters

prefix: prefix of the code (optional)

suffix: suffix of the code (optional)

dash every x characters: insert a dash every x characters  (optional)

Let’s also specific how many codes we will generate by adding count to the array.

See the example above, below are some possible codes generated:

PRE0IY3-V2C1-L9SUF

PRE9AHH-28PC-QTSUF

PRE8JGH-ZRVW-EBSUF

Step 3. Generate Coupon Codes

Last, we need to create a generator object and then load our format setting array.

Now, we have our generator object, formatting array, and the promo rule ready. Let’s get some promo codes!

You will not need to worry about if the coupon code generated has existed before. The code generated will be unique.