Sub topic 11
Building coupon rules on your own site
On Udemy, the platform decides which coupon types exist and what limits apply. On your own site, you decide all of it. That freedom also makes you responsible for the checks that stop a coupon from costing you money you did not plan to give away.
This chapter assumes you have read the earlier chapters on coupon types and on payment fees and taxes. You should be comfortable with percentages and have read simple Python. The examples use Python, but the rules apply to any checkout system. Most course platforms and payment processors give you the same building blocks under different names.
What a coupon rule is made of
A coupon is a record plus a set of checks. The record says what discount to give. The checks say when it may be given. Keep these two parts separate in your design, because you will change the checks far more often than the discount math.
| Field | What it controls | Common mistake |
|---|---|---|
| Code | The text the buyer types | Allowing look-alike characters such as `O` and `0` |
| Discount type | Percent off or fixed amount off | Using a fixed amount on a product whose price may change |
| Value | How much is taken off | Letting a percent exceed 100 |
| Expiry | The moment the coupon stops working | Using a local time zone with no offset |
| Redemption cap | Total uses across all buyers | Counting at cart time instead of at payment time |
| Per-buyer limit | Uses per customer | Tracking by email only, so one buyer uses many addresses |
| Eligibility | Which products or buyers qualify | Applying the discount to bundles meant to be excluded |
| Stacking | Whether it combines with other offers | Leaving this undefined |
Choose a discount type deliberately
Percent-off coupons scale with the price. A 30% coupon on a 99.00 course gives 69.30. The same coupon on a 299.00 bundle gives 209.30, which is a larger give-away. If you sell products at several prices, a percent coupon applied everywhere may discount your high-priced offer more than you intended.
Fixed-amount coupons take off the same sum every time. A 20.00 coupon is a strong offer on a 49.00 course and a weak one on a 299.00 program. A fixed coupon also needs a floor so that it cannot push the total below zero or below your cost.
Whichever type you choose, calculate with Decimal, not floating-point numbers. Floats can produce totals such as 69.29999 that then fail to match what the payment processor charges. The next example computes a sale price and the amount you keep after fees. The 2.9% + 0.30 fee is an assumed rate for illustration. Use your processor's actual rate.
from decimal import Decimal, ROUND_HALF_UP
CENT = Decimal("0.01")
def money(x: Decimal) -> Decimal:
return x.quantize(CENT, rounding=ROUND_HALF_UP)
def discounted_price(list_price: Decimal, percent_off: Decimal) -> Decimal:
return money(list_price * (Decimal(100) - percent_off) / Decimal(100))
def net_per_sale(price: Decimal, platform_share: Decimal, fee_rate: Decimal, fee_fixed: Decimal) -> Decimal:
"""Amount you keep. platform_share and fee_rate are fractions, e.g. Decimal('0.03')."""
after_platform = price * (Decimal(1) - platform_share)
after_fees = after_platform - price * fee_rate - fee_fixed
return money(after_fees)
list_price = Decimal("99.00")
sale_price = discounted_price(list_price, Decimal("30"))
print(sale_price) # 69.30
# Own site: no platform share, assumed 2.9% + 0.30 payment fee
print(net_per_sale(sale_price, Decimal("0"), Decimal("0.029"), Decimal("0.30"))) # 67.00The fixed part of the fee matters more as the price falls. At 69.30, the fee is about 2.31, or 3.3% of the price. At 10.00 it would be 0.59, or 5.9%. Deep discounts raise your effective fee rate, so check the net amount before you approve a coupon, not only the sale price.
Validate in a fixed order
Every redemption should pass the same checks in the same order. A fixed order gives buyers a consistent error message and makes your behavior easy to test. The checks in the next example cover the three that every coupon needs: the code exists, it has not expired, and its cap has not been reached.
from dataclasses import dataclass
from datetime import datetime, timezone
from decimal import Decimal
from typing import Optional
@dataclass
class Coupon:
code: str
percent_off: Decimal
expires_at: datetime # timezone-aware
max_redemptions: Optional[int]
redeemed: int = 0
def validate_coupon(coupon: Optional[Coupon], now: Optional[datetime] = None) -> Optional[str]:
"""Return an error message, or None if the coupon can be used."""
now = now or datetime.now(timezone.utc)
if coupon is None:
return "Unknown code"
if now >= coupon.expires_at:
return "Coupon expired"
if coupon.max_redemptions is not None and coupon.redeemed >= coupon.max_redemptions:
return "Coupon fully redeemed"
return None
spring = Coupon("SPRING30", Decimal("30"), datetime(2030, 4, 1, tzinfo=timezone.utc), 100)
print(validate_coupon(spring, datetime(2030, 3, 1, tzinfo=timezone.utc))) # None
print(validate_coupon(spring, datetime(2030, 4, 2, tzinfo=timezone.utc))) # Coupon expiredThree details in this code are worth noting.
- The function takes
nowas a parameter. This lets you test the expiry boundary without waiting for a real date. expires_atis timezone-aware. Comparing a naive datetime with an aware one raises an error in Python, and storing local times with no offset causes coupons to end hours early or late for some buyers.- The comparison uses
>=. A coupon that expires at midnight is dead at midnight, not one second later.
You would add further checks after these three: per-buyer limits and eligibility. Put cheap checks first and checks that need a database lookup last.
Count redemptions at payment, not at cart
The redeemed field in the example is a plain counter. In a live system, two buyers can both pass validation when one use remains, and both then pay. This is a race condition.
Two practices reduce the problem:
- Increment the counter when payment succeeds, not when the buyer applies the code. If you count at cart time, abandoned carts use up your cap.
- Make the increment atomic in your database, for example with a single
UPDATE ... SET redeemed = redeemed + 1 WHERE redeemed < max_redemptionsstatement that you check for one affected row. If no row changed, the cap was reached and you should reject the order.
If your processor offers its own coupon objects, it may already enforce caps this way. Using them saves you from writing this logic, at the cost of tying your rules to that vendor's limits.
Define eligibility and stacking
Eligibility answers two questions. Which products does the coupon cover? Which buyers may use it?
- Product scope. List the product IDs explicitly. A coupon marked "all products" will eventually apply to a bundle or membership that you added later.
- Buyer scope. Options include new customers only, past buyers only, or buyers on a specific email list. "New customers only" is easy to state and hard to enforce, because a buyer can register a second address. Match on payment details or an account history check if the discount is large.
- Stacking. Decide whether a coupon can combine with a sale price or with another coupon. The safest default is one coupon per order and no stacking with an automatic sale. If you allow stacking, apply the rules in a fixed order and set a floor so that the combined discount cannot pass a maximum.
A discount floor is a simple guard. Compute your minimum acceptable price from the earlier chapter on costs, and reject any order that would fall below it.
from decimal import Decimal
def apply_floor(price: Decimal, floor: Decimal) -> Decimal:
"""Never charge less than the floor, whatever discounts were applied."""
return max(price, floor)
print(apply_floor(Decimal("12.00"), Decimal("19.00"))) # 19.00
print(apply_floor(Decimal("69.30"), Decimal("19.00"))) # 69.30Taxes and the discounted price
Sales tax and VAT are normally calculated on the price the buyer actually pays, after the discount. A coupon therefore lowers the tax line as well as the price line. Check the rules for your own jurisdictions, since treatment varies and some situations need advice from an accountant. Whatever the rule, record the list price, the discount, the tax and the total as separate fields on each order. You will need them for refunds and for reports.
The flow of a redemption
The following diagram shows the order of operations at checkout.
Common errors
- Showing the error "invalid code" for every failure. Buyers with an expired code then assume they mistyped it, and they email you. Specific messages cut support load.
- Letting the code field accept unlimited attempts. Add a rate limit so that nobody can guess codes by trial.
- Using short, predictable codes such as
SAVE10. Use these only for public offers. For private offers, generate random codes, one per recipient. - Forgetting to restore a redemption when an order is refunded or fails after the count. Decide whether refunded orders free up a use, and write that rule down.
- Not logging which code produced each order. Without that field you cannot measure a promotion later.
Exercises
Exercise
A coupon expires at 2030-04-01 00:00 UTC and is capped at 100 redemptions. Your system increments redeemed when the buyer applies the code. Name two problems this causes and one fix for each.
Show answer
First, abandoned carts use up the cap, so real buyers are turned away. Fix: increment only after payment succeeds. Second, two buyers can both pass validation when one use remains. Fix: make the increment atomic in the database and reject the order if no row was updated.
Exercise
Using the fee in this chapter (2.9% + 0.30, an assumed rate), what do you keep on a sale at 40.00 with no platform share? Round to the cent.
Show answer
The fee is 40.00 × 0.029 = 1.16, plus 0.30, so 1.46. You keep 40.00 − 1.46 = 38.54.
Exercise
You sell a 49.00 course and a 299.00 program. You want a coupon to take roughly the same dollar amount off each. Should you use a percent or a fixed-amount coupon, and what extra rule do you need?
Show answer
A fixed-amount coupon, because it removes the same sum from both. Add a price floor so the discount can never push an order below your minimum acceptable price.