Sub topic 11
Building Coupon Rules on Your Own Site
Assume you already have a course, a checkout page, and basic server-side code. You also need to be comfortable with percentages, dates, and simple database concepts. A coupon is a rule that changes the price only when a buyer meets defined conditions.
Start with explicit coupon rules
Define each coupon before you publish it. Record:
- The code buyers enter, such as
SPRING30. - The discount type, such as a percentage or a fixed amount.
- The expiration time and time zone.
- The products or course editions it applies to.
- Whether it applies to new customers, existing customers, or a specific group.
- The maximum number of total redemptions.
- The maximum number of redemptions per customer.
- Whether it can be combined with another discount.
A percentage discount scales with the price. A fixed discount gives the same amount off, but it must never reduce the price below zero. Store money as decimal values or integer cents. Do not rely on binary floating-point arithmetic for currency.
| Rule | Example | Why it matters |
|---|---|---|
| Discount | 30% off | Defines the price change |
| Expiry | 2030-04-01 UTC | Prevents an old offer remaining active |
| Total limit | 100 uses | Controls campaign cost |
| Customer limit | One use per customer | Reduces repeated use |
| Eligibility | Course A only | Protects other products |
Validate on the server
The browser can display a coupon result, but it cannot be trusted. A buyer can change browser requests. Validate the code again on your server when the order is created.
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
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 when the coupon is valid."""
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:
if coupon.redeemed >= coupon.max_redemptions:
return "Coupon fully redeemed"
if coupon.percent_off < 0 or coupon.percent_off > 100:
return "Invalid discount"
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),
)) # NoneThe final redemption must be atomic. This means checking the limit and recording the redemption as one database operation. Otherwise, two simultaneous checkouts might both see one remaining use and exceed the limit. Record the customer, order, coupon, discount, and timestamp so that refunds and reports can be traced later.
Handle taxes, refunds, and abuse
Decide whether your discount reduces the taxable amount in each region. Your payment provider or tax service may calculate this differently, so test representative orders.
For refunds, store the original order totals. Do not recalculate a historical discount using the current coupon rules. Decide whether a refunded redemption becomes available again. A one-time campaign often should not restore it automatically.
Protect codes that are intended for a limited audience. Use random codes for private offers, avoid predictable sequences, and require a customer account when one-use-per-customer rules matter. Monitor unusual redemption patterns rather than silently changing terms after buyers have paid.
Coupon checkout flow
Exercise
A coupon allows 50 total uses. Two customers submit checkout at the same time when 49 uses have already been recorded. What must the server do?
Show answer
It must check the remaining limit and record the successful redemption in one atomic database transaction, allowing only one of the two requests to claim the final use.