We built DEV3 AI Smart Coupons & Dynamic Discounts as a WooCommerce plugin in PHP with a small React admin and a dependency-free storefront script. The AI is one step in a longer pipeline, and every step after it is deterministic.
Key design decisions
- Explainable risk, not AI risk. The abandonment score (0–100) is a weighted additive model of exit intent, idle time, cart value against the store's average order, visitor type, order history and repeat cart views. Every point has a named factor, shown in the admin simulator.
- The model only suggests. The Google Gemini API receives anonymous cart context (subtotal, item count, categories, risk reasons, the allowed ranges) and returns a typed JSON proposal.
Rules::clamp() treats every field as untrusted: type, amount, time limit and copy.
- Margin floor per cart line. Room on each line is its total minus cost × quantity × (1 + minimum margin). The tightest line sets the maximum percentage, lines with no room are left out of the coupon, and the coupon is restricted to the products that passed the check.
- Copy that cannot promise a different deal. The model writes
{discount} and {minutes} placeholders. Any copy that still contains digits, currency symbols, links or markup is replaced by the merchant's template, so the banner always states the clamped offer.
- Real WooCommerce coupons, locked down. Unique code, usage limit 1 and 1 per user, expiry equal to the countdown, email restriction when known, individual use, and a
woocommerce_coupon_is_valid filter that binds the code to the shopping session it was issued to.
- Budget and rate gates. One offer per session, email and (optionally) IP per day, stored only as HMAC hashes; a global daily discount budget; a 15-minute evaluation cooldown per session; a deterministic rules-based fallback when the AI is off or fails.
Architecture
The storefront script watches for exit intent, idle time, tab switches and fast scroll-up, then calls a same-origin, rate-limited REST endpoint. The server builds a cart snapshot (line totals, unit cost from a configurable meta key), runs the gates, asks the AI, clamps, creates the coupon and logs the offer in its own table. Banners work on block and classic cart and checkout pages and stay compatible with full-page caching, because offers are fetched per shopper and printed inline only on cart and checkout. Action Scheduler removes expired unused coupons and resets the budget at midnight. The API client, licensing and settings screens come from a shared core used across DEV3's plugins.