Poseidonas

payload coupons

by Poseidonas
Stores & catalogs
v3
>=3.88 <4
MIT

Overview

Summary generated from the README

Adds a coupons collection and a redemptions collection to a Payload shop, with percentage and fixed discounts, scope and exclusions, usage limits and validity windows. It works with the official ecommerce plugin or any carts and orders collections, and adds validate, apply-coupon and remove-coupon endpoints. Discounts are split across cart lines in exact integer arithmetic. Requires Payload 3.88 or newer.

Features

  • Percentage and fixed coupons with per-currency amounts in minor units
  • Scope by cart, products or categories, with product and category exclusions
  • Minimum and maximum cart amounts, validity window and usage limits
  • Concurrency-safe redemption claims via unique indexed slots, with per-customer limits
  • Validate, apply and remove coupon endpoints returning stable refusal reason codes
  • Exact line-by-line discount allocation, exported as helper functions for front ends

Use cases

  • Offer promo codes in a Payload shop without rounding errors between line amounts and totals
  • Limit a campaign code to a number of total uses or uses per customer
  • Restrict a discount to certain products or categories while excluding others

From the author

Coupon codes and discounts for Payload ecommerce, in integer minor units with exact rounding.

Installation

npm i payload-coupons

2

Stars

0

Forks

0

Open Issues

2 weeks ago

Last Updated

149

Weekly Downloads

v1.0.2

npm Version

64.9 KB

Unpacked Size

0

Dependencies

GitHub stars

2+1 since Sep 6

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 20262
Dec 4, 20262
Dec 3, 20262
Dec 2, 20262
Dec 1, 20262
Nov 30, 20262
Nov 29, 20262
Nov 28, 20262
Nov 27, 20262
Nov 26, 20262
Nov 25, 20262
Nov 24, 20262
Nov 23, 20262
Nov 22, 20262
Nov 21, 20262
Nov 20, 20262
Nov 19, 20262
Nov 18, 20262
Nov 17, 20262
Nov 16, 20262
Nov 15, 20262
Nov 14, 20262
Nov 13, 20262
Nov 12, 20262
Nov 11, 20262
Nov 10, 20262
Nov 9, 20262
Nov 8, 20262
Nov 7, 20262
Nov 6, 20262
Nov 5, 20262
Nov 4, 20262
Nov 3, 20262
Nov 2, 20262
Nov 1, 20262
Oct 31, 20262
Oct 30, 20262
Oct 29, 20262
Oct 28, 20262
Oct 27, 20262
Oct 26, 20262
Oct 25, 20262
Oct 24, 20262
Oct 23, 20262
Oct 22, 20262
Oct 21, 20262
Oct 20, 20262
Oct 19, 20262
Oct 18, 20261
Oct 17, 20261
Oct 16, 20261
Oct 15, 20261
Oct 14, 20261
Oct 13, 20261
Oct 12, 20261
Oct 11, 20261
Oct 10, 20261
Oct 9, 20261
Oct 8, 20261
Oct 7, 20261
Oct 6, 20261
Oct 5, 20261
Oct 4, 20261
Oct 3, 20261
Oct 2, 20261
Oct 1, 20261
Sep 30, 20261
Sep 29, 20261
Sep 28, 20261
Sep 27, 20261
Sep 26, 20261
Sep 25, 20261
Sep 24, 20261
Sep 23, 20261
Sep 22, 20261
Sep 21, 20261
Sep 20, 20261
Sep 19, 20261
Sep 18, 20261
Sep 17, 20261
Sep 16, 20261
Sep 15, 20261
Sep 14, 20261
Sep 13, 20261
Sep 12, 20261
Sep 11, 20261
Sep 10, 20261
Sep 9, 20261
Sep 8, 20261
Sep 7, 20261
Sep 6, 20261
npm weekly downloads

79+61 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 202679
Dec 4, 202651
Dec 3, 202637
Dec 2, 202645
Dec 1, 202646
Nov 30, 202649
Nov 29, 202655
Nov 28, 202662
Nov 27, 202671
Nov 26, 2026248
Nov 25, 2026246
Nov 24, 2026266
Nov 23, 2026266
Nov 22, 2026254
Nov 21, 2026241
Nov 20, 2026228
Nov 19, 202645
Nov 18, 202640
Nov 17, 202616
Nov 16, 202612
Nov 15, 202613
Nov 14, 202613
Nov 13, 202615
Nov 12, 202615
Nov 11, 202612
Nov 10, 202612
Nov 9, 202610
Nov 8, 202612
Nov 7, 202614
Nov 6, 202613
Nov 5, 202613
Nov 4, 202613
Nov 3, 202612
Nov 2, 202615
Nov 1, 202610
Oct 31, 202610
Oct 30, 20268
Oct 29, 20265
Oct 28, 20265
Oct 27, 20267
Oct 26, 20266
Oct 25, 20267
Oct 24, 20266
Oct 23, 20266
Oct 22, 202610
Oct 21, 202610
Oct 20, 202610
Oct 19, 20269
Oct 18, 20268
Oct 17, 20268
Oct 16, 20268
Oct 15, 20268
Oct 14, 20268
Oct 13, 20266
Oct 12, 20265
Oct 11, 20266
Oct 10, 20266
Oct 9, 20266
Oct 8, 20263
Oct 7, 20265
Oct 6, 202610
Oct 5, 202610
Oct 4, 202612
Oct 3, 202614
Oct 2, 202617
Oct 1, 202616
Sep 30, 202614
Sep 29, 202614
Sep 28, 202615
Sep 27, 202615
Sep 26, 202615
Sep 25, 202614
Sep 24, 202614
Sep 23, 202616
Sep 22, 202616
Sep 21, 202617
Sep 20, 202615
Sep 19, 202612
Sep 18, 202611
Sep 17, 202615
Sep 16, 202615
Sep 15, 202610
Sep 14, 20269
Sep 13, 20269
Sep 12, 20269
Sep 11, 202610
Sep 10, 20266
Sep 9, 20265
Sep 8, 20266
Sep 7, 202612
Sep 6, 202618

Each point is npm's rolling 7-day download count.

Health Score

76/100Excellent

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1340409834-root.svg)](https://payloaddirectory.dev/plugins/1340409834-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1340409834-root"><img src="https://payloaddirectory.dev/badge/1340409834-root.svg" alt="Payload Directory"></a>
Updated Nov 17, 2026Created Aug 20, 2026Published Nov 17, 2026

README

payload-coupons

npm node license payload

Gives a Payload shop coupon codes with percentage and fixed discounts, scope and exclusions, usage limits and a validity window, calculated in whole minor units so that the line amounts always add up to the total.

  • Works with @payloadcms/plugin-ecommerce and with any collection that holds carts and orders
  • Every amount is an integer number of minor units, never a float
  • A code that cannot be used is refused with a stable reason code, never converted or silently adjusted
  • No runtime dependencies
  • No admin components, so it survives minor releases

Install

Requires Payload 3.88 or newer and @payloadcms/plugin-ecommerce 3.88 or newer. Verified against Payload 3.88.0 with the official plugin installed.

pnpm add payload-coupons
import { couponsPlugin } from 'payload-coupons'

export default buildConfig({
  plugins: [
    couponsPlugin({
      currencies: ['EUR', 'USD'],
    }),
  ],
})

Create a coupon in the admin, then ask whether it may be used:

curl -X POST /api/coupons/validate \
  -H 'Content-Type: application/json' \
  -d '{"code":"SAVE10","cartID":"6a85cce9ce631c0034f52d84"}'
{
  "valid": true,
  "discount": {
    "amount": 300,
    "code": "SAVE10",
    "coupon": "1",
    "currency": "EUR",
    "freeShipping": false,
    "lines": [{ "amount": 100, "index": 0 }, { "amount": 200, "index": 1 }],
    "type": "percentage",
    "value": 1000
  }
}

Apply it to the cart, and the cart keeps a total next to its untouched subtotal:

curl -X POST /api/carts/6a85cce9ce631c0034f52d84/apply-coupon \
  -H 'Content-Type: application/json' \
  -d '{"code":"SAVE10"}'

What was measured

@payloadcms/plugin-ecommerce 3.88.0 has no discount of any kind. Its published dist contains zero occurrences of coupon, discount or promo. One third-party package exists, @wtree/payload-ecommerce-coupon, last published in March 2026; no code from it is used here.

Read from the plugin source, and the reason this package works the way it does:

WhatWhere it was readConsequence
Amounts are minor units, Math.round(value * 10 ** currency.decimals)ui/utilities.tsevery calculation here is integer only
EUR, USD and GBP all have decimals: 2currencies/index.tsone cent is the smallest unit that can be moved
A cart stores items and one subtotal, no price per linecollections/carts/beforeChange.tsline amounts are recalculated from product and variant prices
An order is created with amount, currency and items, with no link back to the cartpayments/adapters/stripe/confirmOrder.tsthe discount is recorded on the order, the charged amount is never rewritten

How a percentage is split across lines

The total is worked out once, on the sum of the eligible lines, and then divided. Both steps are exact integer arithmetic.

  1. The rate is held in basis points, so 12.5 percent is 1250 and nothing is ever a float.
  2. The total is eligible x rate / 10000, rounded half up, once.
  3. Each line takes the floor of its exact share of that total.
  4. The units left over are handed out one at a time, largest fractional remainder first. A tie goes to the larger line, and a tie between equal lines goes to the earlier position.
  5. No line is ever given more than the line is worth, and the parts always add up to the total.

A cart of 3.33, 3.33 and 3.34 with 10 percent off gives a total of 100 cents split as 33, 33 and 34. A cart of three items of one cent each with 50 percent off gives 2 cents split as 1, 1 and 0: the third item is not rounded up to keep the split even, because that would take more than the total.

The multiplication is done in BigInt, so the split stays exact for carts far beyond the range where total x line overflows the safe integer range of a float.

The calculation is exported as computeDiscount, allocate, percentageOf and toBasisPoints, so a front end can show the same split before the cart is saved. normalizeCode uppercases and trims a code the way the plugin does.

The test suite checks this exhaustively: every total from 0 to 1000 against a three line cart, every combination of three lines drawn from a fixed set of amounts against several totals, 500 pseudo random carts of up to eight lines, and every rate from 1 to 10000 basis points against five cart shapes. In each case the parts add up to the total and no part exceeds its own line.

How the usage limit holds under concurrency

The same problem as sequential order numbers, and the same answer. These facts were measured on a live Payload 3.88 install while building payload-order-numbers:

ApproachResult
Read a counter and increment it in a hook5 of 25 concurrent operations succeeded
$inc on the PostgreSQL adapteratomic, but 40 concurrent calls all returned the same number, so it cannot back a counter you have to read
Insert into a unique index from a separate transaction25 of 25 succeeded, no duplicates

So a use is not counted, it is claimed. Each redemption inserts a document whose slot is couponID#useIndex and, when a per customer limit applies, whose customerSlot is couponID#customerID#useIndex. Both are unique indexes. The insert commits on its own, outside the order's transaction, so a second order arriving at the same instant sees the claim and takes the next index. When the next index would pass the limit the code is refused. Two customers cannot both take the last use, because the database refuses the second insert.

A coupon with no limits inserts a redemption with no slot at all, so unlimited codes never contend.

Options

OptionDefaultMeaning
attempts25How many times to look for a free redemption slot before refusing. Each attempt is one insert
cartsSlug'carts'Slug of the carts collection
categoriesSlug'categories'Slug of the categories collection
categoryField'categories'Field on a product holding its categories
couponsSlug'coupons'Slug of the coupons collection this plugin creates
currencies[]Currency codes offered as a select in the admin. Empty means a free text field, uppercased on save
customersSlug'users'Slug of the customers collection
disabledfalseStops evaluating and claiming, keeps every field and collection so the database keeps its shape
fieldName'discount'Group field holding the applied discount on carts and orders
ordersSlug'orders'Slug of the orders collection
priceField(currency) => `priceIn${currency}`Name of the price field to read for a currency
productsSlug'products'Slug of the products collection
redemptionsSlug'coupon-redemptions'Collection holding one document per claimed use
refuseOrderOnInvalidCouponfalseThrows instead of saving the order without the discount
resolveLineAmountnoneReplaces the built in line amount lookup. Return the amount of the whole line in minor units, or null to fall back
totalFieldName'total'Number field on the cart holding the total after the discount
variantsSlug'variants'Slug of the variants collection

A value that cannot be used is replaced by its default rather than being applied. An attempts of 0 or -5 becomes 25, and 9.9 becomes 9.

Relationship fields are only added for collections that exist in your config. A shop with no categories collection gets a coupons collection with no category scope, rather than a config that refuses to boot.

What it adds to your database

CollectionFieldTypeNotes
couponscodetextunique, indexed, uppercased on save
couponsenabledcheckboxdefaults to true
couponstypeselectpercentage or fixed
couponspercentagenumber0 to 100, kept to two decimal places
couponsamountsarraycurrency and amount in minor units, one entry per currency
couponsfreeShippingcheckboxrecorded on the cart and the order, nothing more
couponsappliesToselectcart, products or categories
couponsproducts, categoriesrelationshipthe scope, when the scope is not the whole cart
couponsexcludedProducts, excludedCategoriesrelationshipremoved from the scope, whatever the scope is
couponsminimumAmounts, maximumAmountsarraycart conditions per currency, in minor units
couponsmaxUses, maxUsesPerCustomernumberempty or 0 means unlimited
couponsvalidFrom, validUntildatethe validity window
your carts collectiondiscountgroupcode, coupon, type, value, amount, currency, freeShipping, lines
your carts collectiontotalnumbersubtotal less the discount, never below zero
your orders collectiondiscountgroupthe same group, written once when the order is created
coupon-redemptionsslottextunique, indexed. couponID#useIndex
coupon-redemptionscustomerSlottextunique, indexed. couponID#customerID#useIndex
coupon-redemptionsuseIndex, customerUseIndexnumberindexed. The position inside each limit
coupon-redemptionscoupon, code, customer, order, amount, currencymixedwhat was claimed, and by whom

value is the basis points of a percentage coupon or the fixed amount of a fixed coupon. amount is what was actually deducted. lines records how that amount was split: index, the position of the item in items, and amount.

The redemptions collection is closed to create, read, update and delete through the API and hidden in the admin. It is written only by the plugin. The coupons collection is left on Payload's own access control, which requires a logged in user for every operation, so codes cannot be listed by the public.

Endpoints

Method and pathBodyAnswer
POST /api/coupons/validatecode, and either cartID or currency with items200 with valid: true and the discount, or 200 with valid: false and a reason. 400 when the code is missing, 404 when the cart cannot be read
POST /api/carts/:id/apply-couponcode, optional secret for a guest cart200 and the updated cart, 422 with a reason when the code is refused, 404 when the cart cannot be read
POST /api/carts/:id/remove-couponoptional secret200 and the updated cart

Validating claims nothing. A use is claimed only when an order is created.

Every refusal carries a stable machine readable reason next to its English message. Switch on the reason, not on the text.

ReasonWhen
CART_NOT_FOUNDthe cart does not exist or the request may not read it
CURRENCY_NOT_SUPPORTEDa fixed coupon has no amount in the cart's currency
CUSTOMER_LIMIT_REACHEDthis customer has used the code as often as allowed
CUSTOMER_REQUIREDthe code is limited per customer and the request is a guest
DISABLEDthe coupon is switched off
EMPTY_CARTthe cart has no items
EXPIREDnow is past validUntil
MAXIMUM_EXCEEDEDthe cart is above maximumAmounts for its currency
MINIMUM_NOT_METthe cart is below minimumAmounts for its currency
MISSING_CODEno code was sent
MISSING_PRICEan item has no price in the cart's currency
NOT_FOUNDno coupon has that code
NOT_STARTEDnow is before validFrom
NO_ELIGIBLE_ITEMSnothing in the cart is in scope after exclusions
REDEMPTION_CONFLICTthe slot could not be claimed within attempts
USAGE_LIMIT_REACHEDthe coupon has been used as often as allowed

The full set of codes and their English messages is exported as refusalReasons, and refusalMessage returns the message for one code.

The checks run in a fixed order and the first failure is the one reported: enabled, then the validity window, then the currency, then the cart contents, then the scope, then the minimum and maximum, then the per customer limit, then the total limit.

Honest limits

PostgreSQL needs a large enough connection pool. Claiming a use opens a second connection while the order's own transaction holds the first. With the pg default of 10, ten simultaneous orders exhaust the pool and the eleventh waits forever. This was measured while building payload-order-numbers, which claims its numbers the same way:

Simultaneous ordersResult with the default pool of 10
2, 4, 6, 8, 10all succeed
153 succeed, the rest time out
postgresAdapter({
  pool: { connectionString: process.env.DATABASE_URI, max: 60 },
})

MongoDB is not affected and needs no change.

The plugin never changes an amount you already have. The cart keeps its subtotal untouched and gains a total. The order keeps the amount it was created with, because that is what the payment provider charged; only the discount group is written. Charge the cart's total at checkout, and the order will record what the code took off. Nothing is silently rewritten, and no total ever goes below zero.

A coupon carries no uses counter. A number kept on the coupon and incremented in a hook is wrong under load, which is what the 5 of 25 above measures, so there is no such field. Uses are counted from the redemptions collection instead, with countCouponUses.

A claimed use can be lost. The claim commits before the order does. If the order then fails to save, the use is gone. Call releaseCouponRedemption to give it back:

import { releaseCouponRedemption } from 'payload-coupons'

await releaseCouponRedemption({ id: redemptionID, payload })

One coupon per cart. There is no stacking, no automatic best code, and no priority between codes. Applying a second code replaces the first.

The cart is re-checked on every save. A code that has become invalid, because the cart changed or the coupon expired, is removed from the cart and the discount goes to zero. The cart does not keep a note of why. Ask the validate endpoint for the reason.

Free shipping is data, not a shipping calculation. discount.freeShipping is exposed on the cart and the order. Nothing else is done with it, and no shipping package is touched.

Fixed amounts are never converted. A coupon with an amount in EUR is refused on a USD cart. Add an amount for each currency you sell in.

Line prices are read from the products. A cart line has no stored price, so the plugin reads priceIn{CURRENCY} from the variant, or from the product when there is no variant. A category scope reads the product as well. That is one or two reads per line; use resolveLineAmount if your prices live elsewhere.

All coupon fields are always visible in the admin. The plugin adds no admin components and no client side conditions, so the fixed amounts are shown even on a percentage coupon.

License

MIT. Copyright George Vasiliades, https://github.com/Poseidonas

Similar plugins