Automatic Coupon Code for Existing Buyers (via admin/invoice.php)

By | March 5, 2009

Chris writes;

Love the GV DC contribution. Except that my boss wants a 15% coupon that will expire in 30 days attached to each invoice that goes out of here. Any ideas/help on adding:
Random code generator for the codes.
Adding a date field to the coupon.
Checking the date before the coupon is processed.
Automatically generating the code upon Invoice printing

This is quite a departure from how the Coupon System works, but is doable. Here’s how;

Step 1: Upgrade to Version 5 of the Coupon System.

Doing this means that these items are taken care of;

Adding a date field to the coupon.
Checking the date before the coupon is processed.

Step 2: Add Coupon Creation code to admin/invoice.php

This file needs to create a randomly named coupon, good for the next 30 days (from date of purchase). A little lateral thinking enabled me to make an “insert into” line that;

1. Creates a coupon using a random name (invoice_id-5_random_characters), eg; 10-rteop
This meant utilising the tep_create_random_value function, easy enough.
2. Makes the coupon a “single use” coupon good for 1 order only.
This is a standard setting in Version 5 of coupons
3. Makes the expiry date 30 days from the date of purchase.
Expiry dates are standard in V5 – I had to use the mysql interval to add 30 days onto it, fairly straightforward.
4. Make the Coupon 15%
Percentage Coupons are standard in all versions of the Coupon Mod

Step 3: Attach the Coupon Code to the Order / Invoice

The previous step (#2) was fairly straightforwad, but I then had to somehow attach the Coupon Code to the order. The easiest way to do this was simnply to add a new column to the DB order table to hold the Random Coupon Code. I just made a has_voucher varchar 32 to hold the details. Then I enclosed the code in the previous step inside a tep_not_null(has_voucher) to determine whether a coupon should be made or not.

Step 4: Add the Coupon Details to the Invoice

Easy. A simple echo with the relevant details, looks like this;

This means that the Invoice they receive in the post (or by email) from you, has the Coupon Code on it, and that Coupon Code is ready for use straightaway.

And here is the Coupon ready to be used;

All of the above works, both in theory and in practice. However, the code base is ugly! For production release it needs refining and that takes money and time.


A great way to get repeat business is to offer existing buyers a discount on their next order. By setting a 30 day expire on the coupon it entices buyers to buy as quicly as possible. Each and every time they order, their Invoice will create a new coupon code for them to use next time.

Leave a Reply

Your email address will not be published.