I recently needed to add promotional discounts for one of my web sites. I was unable to find an off the shelf function to generate unique (user specific) codes. So, I created the code myself.
The PHP code presented here allows you to encode any string of your choice into a familiar looking serial number/promotional code. The produced codes are restricted to a limited subset of characters minimising the risk of human typing mistakes. Basic encryption is also supported.
Typical Scenario 1
An online store wants to provide a registered customer the opportunity to purchase with a 10% discount. The discount code should be valid for that customer only, and should be valid until a certain date. The store generates a code that consists of the users ID, the offer and an expiry date:
- 123,10off,091212
This code is easily decipherable and open to abuse by other store customers. By using the functions presented here, the following code can be generated:
- WGK4P-H7JV9-S6XXW-PWQYL-TJPDU-2
The generated promotional code is far more difficult to decipher. When the customer enters this code, the online store can decode it, check it is valid (customer and date) and apply the discount.
Typical Scenario 2
A software developer has released an application that has multiple levels of functionality, depending on the license purchased by the user. The application detects supported functionality, based on the serial number provided by the user:
- pro,noexpire
- lite,101112
Allowing a user to enter such codes is again open to rampant abuse. The software developer provides the following serial numbers:
- 6DK8F-H9F55-M732G-L6ZNA
- 5VFQR-YFDWC-TKMJN-UWW
Each serial number is valid, but allows the application to offer different levels of functionality.
Usage Example
The code below demonstrates how to use the functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <?php // GENERATE A CODE // Include the functions include_once('promo_gen.php'); // The key used for encryption $key = "password"; // The plaintext promotional code $promo = "123,10off,091212"; // Encrypt the plaintext $promo = promo_encrypt($promo, $key); // Encode the encrypted plaintext $promo = promo_encode($promo); // $promo is now: // WGK4P-H7JV9-S6XXW-PWQYL-TJPDU-2 // DECODE A SERIAL NUMBER // The serial number $serial = "6DK8F-H9F55-M732E-P7RAQ-PWJ"; // Decode the number $serial = prom_decode($serial); // Decrypt the serial number $serial = promo_decrypt($serial, $key); // $serial is now: // pro,noexp,xMob ?> |
Download
Current release: php_promo_gen.current.tgz
If you use this code generator, I would love to hear about it.
