Poseidonas

payload refunds

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

Overview

Summary generated from the README

Adds a refunds collection that records full and partial refunds against orders created by the official ecommerce plugin or any orders collection. It validates amounts in integer minor units, recomputes refunded and refundable totals from the records, and can return units to stock. It does not move money; an onRefund hook connects a payment provider. Requires Payload 3.88 or newer and the ecommerce plugin.

Features

  • Refund records with per-line quantities, amounts, reason and note
  • Running refundedAmount and refundableAmount recomputed from records on every write
  • Refusal of zero, fractional or over-refund amounts with typed RefundError codes
  • Optional restock of refunded units using a retried compare-and-set stock write
  • Append-only refunds collection closed to update and delete, stamped with issuer
  • onRefund hook for calling a payment provider before the record is written

Use cases

  • Issue partial refunds on specific order lines in a Payload shop
  • Return refunded items to inventory automatically after a return
  • Keep an immutable refund history for accounting and audits

From the author

Full and partial refunds for Payload ecommerce, per line item, with optional restock and an append only audit trail.

Installation

npm i payload-refunds

1

Stars

0

Forks

0

Open Issues

2 weeks ago

Last Updated

20

Weekly Downloads

v1.0.2

npm Version

53.6 KB

Unpacked Size

0

Dependencies

GitHub stars

10 since Sep 6

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 20261
Dec 4, 20261
Dec 3, 20261
Dec 2, 20261
Dec 1, 20261
Nov 30, 20261
Nov 29, 20261
Nov 28, 20261
Nov 27, 20261
Nov 26, 20261
Nov 25, 20261
Nov 24, 20261
Nov 23, 20261
Nov 22, 20261
Nov 21, 20261
Nov 20, 20261
Nov 19, 20261
Nov 18, 20261
Nov 17, 20261
Nov 16, 20261
Nov 15, 20261
Nov 14, 20261
Nov 13, 20261
Nov 12, 20261
Nov 11, 20261
Nov 10, 20261
Nov 9, 20261
Nov 8, 20261
Nov 7, 20261
Nov 6, 20261
Nov 5, 20261
Nov 4, 20261
Nov 3, 20261
Nov 2, 20261
Nov 1, 20261
Oct 31, 20261
Oct 30, 20261
Oct 29, 20261
Oct 28, 20261
Oct 27, 20261
Oct 26, 20261
Oct 25, 20261
Oct 24, 20261
Oct 23, 20261
Oct 22, 20261
Oct 21, 20261
Oct 20, 20261
Oct 19, 20261
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

13−7 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 202613
Dec 4, 202615
Dec 3, 202616
Dec 2, 202624
Dec 1, 202622
Nov 30, 202624
Nov 29, 202622
Nov 28, 202634
Nov 27, 202642
Nov 26, 2026179
Nov 25, 2026170
Nov 24, 2026167
Nov 23, 2026165
Nov 22, 2026164
Nov 21, 2026152
Nov 20, 2026142
Nov 19, 20265
Nov 18, 20267
Nov 17, 20268
Nov 16, 20268
Nov 15, 20265
Nov 14, 20267
Nov 13, 20268
Nov 12, 202611
Nov 11, 20269
Nov 10, 20268
Nov 9, 20269
Nov 8, 202613
Nov 7, 202614
Nov 6, 202613
Nov 5, 202612
Nov 4, 202612
Nov 3, 202612
Nov 2, 202615
Nov 1, 202611
Oct 31, 20268
Oct 30, 20267
Oct 29, 20264
Oct 28, 20264
Oct 27, 20265
Oct 26, 20264
Oct 25, 20264
Oct 24, 20265
Oct 23, 20265
Oct 22, 20268
Oct 21, 20268
Oct 20, 20267
Oct 19, 20265
Oct 18, 20266
Oct 17, 20266
Oct 16, 20266
Oct 15, 20266
Oct 14, 20266
Oct 13, 20266
Oct 12, 20265
Oct 11, 20265
Oct 10, 20265
Oct 9, 20265
Oct 8, 20263
Oct 7, 20264
Oct 6, 20269
Oct 5, 20269
Oct 4, 202611
Oct 3, 202612
Oct 2, 202617
Oct 1, 202616
Sep 30, 202615
Sep 29, 202615
Sep 28, 202615
Sep 27, 202613
Sep 26, 202615
Sep 25, 202611
Sep 24, 202612
Sep 23, 202612
Sep 22, 202610
Sep 21, 202610
Sep 20, 202612
Sep 19, 20268
Sep 18, 20269
Sep 17, 202610
Sep 16, 202612
Sep 15, 20269
Sep 14, 202610
Sep 13, 20268
Sep 12, 202611
Sep 11, 202611
Sep 10, 202610
Sep 9, 20269
Sep 8, 202610
Sep 7, 202613
Sep 6, 202620

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

Health Score

70/100Good

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/1340410250-root.svg)](https://payloaddirectory.dev/plugins/1340410250-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1340410250-root"><img src="https://payloaddirectory.dev/badge/1340410250-root.svg" alt="Payload Directory"></a>
Updated Nov 17, 2026Created Aug 20, 2026Published Nov 17, 2026

README

payload-refunds

npm node license payload

Records full and partial refunds against a Payload order and the payment behind it, per line item, with an optional restock, running totals that can never drift from the records, and an audit trail that is never edited.

  • Extends @payloadcms/plugin-ecommerce and works on any collection that holds orders
  • Every amount is a whole number of minor units, added with integers from beginning to end
  • No runtime dependencies, and no runtime import of payload either
  • 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-refunds
import { ecommercePlugin } from '@payloadcms/plugin-ecommerce'
import { refundsPlugin } from 'payload-refunds'

export default buildConfig({
  plugins: [
    ecommercePlugin({ /* ... */ }),
    refundsPlugin({
      restock: true,
      updateTransactionStatus: true,
    }),
  ],
})

refundsPlugin must come after the plugin that defines the orders collection. It extends what it finds; if the orders collection is not there yet, it returns the config untouched.

A refund is an ordinary document, so it is created the ordinary way:

await payload.create({
  collection: 'refunds',
  data: {
    order: orderID,
    amount: 2500,
    reason: 'damaged',
    lines: [{ item: 'a1b2c3', quantity: 1, amount: 2500 }],
  },
  req,
})

What was measured

Read in the published @payloadcms/[email protected], in the original TypeScript carried by its source maps.

The whole refund surface is two words

refunded appears twice in the plugin's own code, and both are select options:

FileFieldWhere the word sits
collections/orders/createOrdersCollection.tsstatus on orderslast of processing, completed, cancelled, refunded
fields/statusField.tsstatus on transactionslast of pending, succeeded, failed, cancelled, expired, refunded

There is no amount, no partial refund, no line, no reason, no record of who did it and no restock. Marking an order refunded is the entire feature.

An order carries no per line price

fields/cartItemsField.ts builds the items array, and collections/orders/createOrdersCollection.ts calls it without a currency configuration. An order line therefore holds exactly this:

FieldTypePresent on an order line
productrelationshipyes
variantrelationshiponly when variants are enabled
quantitynumberyes
amountnumberno, it needs individualPrices, which orders do not pass
currencyselectno, it needs a currency configuration, which orders do not pass

The only money on an order is amount and currency at the top, written by the payment adapter from the payment intent. That decides the arithmetic below: this package can cap a line by quantity, because the quantity is on the line, and it can cap money at the order level, because that is the only place money exists. It never invents a line price.

Amounts are integers of minor units

ui/utilities.ts converts a typed price with Math.round(value * 10 ** currency.decimals), and currencies/index.ts gives EUR, USD and GBP decimals: 2. The order's amount is the payment intent's amount, which is minor units as well. This package adds, compares and stores integers only, and refuses a fractional amount rather than rounding it.

How the official plugin moves stock

endpoints/confirmOrder.ts decrements after payment, taking item.variant when there is one and item.product otherwise:

187   await payload.db.updateOne({
191     inventory: {
192       $inc: item.quantity * -1,

The restock in this package targets the same document for the same line, so a refunded unit goes back where the sale took it from. It does not use $inc; see Honest limits.

Tests

182 unit tests, pnpm test. The refund arithmetic is tested against every boundary: one minor unit under and over the remainder, the last unit of a line, the same line twice, lines that add up to more than the refund, and a whole history of partial refunds checked after every step.

The arithmetic, stated as rules

These hold for every order, whatever order the refunds arrive in.

  1. Every amount is a whole number of minor units. A fraction is refused, never rounded.
  2. refundedAmount is the sum of the amount of every refund record on the order. It is recomputed from the records on every write, never incremented, so it cannot drift from them.
  3. refundableAmount is order.amount - refundedAmount, and never below zero.
  4. refundedAmount + refundableAmount = order.amount.
  5. A refund is refused when its amount is zero, negative, fractional, or above refundableAmount.
  6. For each order line, the units refunded across all records never exceed the units ordered.
  7. Within one refund, the line amounts add up to no more than the refund amount. Less is allowed, and is how shipping or tax is returned without a line.
  8. The same order line may not appear twice in one refund.
  9. The order status becomes refunded exactly when refundedAmount reaches order.amount.

A refusal is a RefundError carrying HTTP 400, isPublic, and a code from refusalCodes:

import { RefundError, refusalCodes } from 'payload-refunds'

try {
  await payload.create({ collection: 'refunds', data, req })
} catch (error) {
  if (error instanceof RefundError && error.code === refusalCodes.OverRefund) {
    console.log(error.detail.refundableAmount)
  }
}

The codes are InvalidAmount, InvalidLine, LineOverRefund, LinesExceedAmount, OrderNotFound, OverRefund, RefundImmutable and WrongCurrency.

Why a partial refund leaves the order status alone

The official vocabulary has four values and none of them means partially refunded. Writing refunded after a refund of one cent would tell the shop, its exports and its own admin filters that the order is finished when it is not, and adding a fifth option would change the shape of the collection for everyone who installs this package. So a partial refund changes the totals and nothing else. If you want a state for it, payload-fulfillment is where extra states belong, and refundedStatus: '' here turns off the full refund write as well.

Options

OptionDefaultMeaning
createAccessany signed in userWho may create a refund record
disabledfalseStops validating, restocking and updating the order, but keeps every field and collection
inventoryFieldName'inventory'Numeric field holding stock on products and variants
onRefundnoneCalled after validation and before the record is written, for the payment provider
orderItemsFieldName'items'Array field holding the order lines
orderRefundableFieldName'refundableAmount'Order field holding the money still refundable
orderRefundedFieldName'refundedAmount'Order field holding the money already refunded
ordersSlug'orders'Slug of the orders collection
productsSlug'products'Slug of the products collection
readAccessany signed in userWho may read refund records
reasonssix values, belowOptions of the reason field
refundedStatus'refunded'Status written on a full refund. An empty string leaves the status alone
refundsSlug'refunds'Slug of the refunds collection
restockfalsePuts refunded units back into stock. A record may override it either way
restockAttempts10How many times a stock write is retried when another writer got there first
statusFieldName'status'Name of the status field on the order
transactionsSlug'transactions'Slug of the transactions collection
updateTransactionStatusfalseSets the transaction status to refunded on a full refund
usersSlug'users'Collection the issuedBy relationship points at
variantsSlug'variants'Slug of the variants collection

A value that cannot be used is replaced by its default rather than being applied. A slug given as an empty string becomes its default, a restockAttempts of 0 or -5 becomes 10, and 4.9 becomes 4. Nothing is silently reinterpreted: -5 never becomes 5.

The default reasons

requested-by-customer, damaged, not-received, returned, duplicate, other. A reason may be a string or { label, value }; a bare string becomes its own label, so 'gift-return' is shown as Gift return. Passing reasons replaces the list, and reasons: [] offers none. They are exported as defaultReasons.

The payment provider hook

This package records refunds. It does not move money, and it contacts no provider. onRefund is where you do that:

refundsPlugin({
  onRefund: async ({ input, order, req }) => {
    const refund = await stripe.refunds.create({
      payment_intent: paymentIntentOf(order),
      amount: input.amount,
    })

    return { reference: refund.id }
  },
})

It runs after the refund has been checked against the order and before the record is written, so a provider that refuses leaves nothing behind: no record, no totals, no restock. The reference it returns is stored on the record. It is given the validated input, the order document, the totals before this refund, and req, so any call it makes can stay inside the same transaction.

What it adds to your database

CollectionFieldTypeNotes
your orders collectionrefundedAmountnumberindexed, sidebar, read only, closed to the API
your orders collectionrefundableAmountnumbersidebar, read only, closed to the API
your order linesrefundedQuantitynumberread only, closed to the API
your order linesrefundedAmountnumberread only, closed to the API
refundsorderrelationshiprequired, indexed
refundsamountnumberrequired, minimum 1, minor units
refundscurrencytexttaken from the order when absent
refundsreasonselectindexed
refundsnotetextareafree text
refundslinesarrayitem, product, variant, quantity, amount
refundstransactionrelationshipoptional
refundsreferencetextthe provider's own identifier
refundsrestockcheckboxdefaults to the restock option
refundsrestockednumberread only, how many lines went back into stock
refundsissuedAtdateindexed, stamped by the hook
refundsissuedByrelationshipthe user, when they belong to usersSlug
refundsissuedByEmailtexttheir email, kept as a copy that survives a deleted user

The refunds collection is closed to update and delete through the API, and every field is closed to update as well. The stamped fields are closed to create too, so a request cannot forge who issued a refund or how much went back into stock. Update is refused a second time inside the collection's own beforeChange hook, which catches a Local API call that overrides access, because a record that can be edited is not an audit trail.

What it adds to your code

import { refundableFor } from 'payload-refunds'

const totals = await refundableFor(payload, { order: orderID, req })

It returns { amount, currency, refundedAmount, refundableAmount, lines }, with each line carrying quantity, refundedQuantity and refundedAmount, or null when the order does not exist. The pure functions behind it are exported as well, so you can check a refund before you send it: refundTotals, validateRefund, matchLine, readOrderLines and isFullyRefunded.

Honest limits

This package records refunds. It does not move money. Nothing here talks to Stripe or any other provider. Creating a refund record changes your database and your stock; it does not put anything back on a card. Wire onRefund to your provider, or your books will disagree with your bank.

A line has no price, so a line cannot be capped in money. The order does not store what a line cost, as measured above. This package refuses more units than were ordered, and more money than the order is worth, but it cannot tell you that 25.00 is the wrong amount for one unit of a 10.00 product. The line amounts you pass are recorded as given and checked only against the refund total. If you need money capped per line, you have to supply the line price yourself, from the product, the cart, or your own snapshot.

Two refunds on the same order in the same instant can both pass. Each request reads the totals inside its own transaction, so two refunds of 60 against an order of 100 can both see 100 refundable. The records stay correct and the running totals stay equal to their sum, so the order will show 120 refunded and 0 refundable, but the over-refund is not refused. If simultaneous refunds on one order are a real risk for you, serialise them in your own code. A single admin clicking twice is not this case: the second write reads the first inside the same connection.

Restock is a read, then a compare and set, not $inc. The official plugin decrements with payload.db.updateOne and a $inc operator, which is outside the stable surface this package is limited to. Instead, the stock is read and then written with a where that requires it to still hold the value that was read; if another writer moved it, the write matches nothing and it is tried again, up to restockAttempts times. That is correct under concurrency and costs one extra read per line. After restockAttempts failures the line is left alone and restocked counts it as not returned; nothing is overwritten.

Restock does not need payload-stock-reservation, and does not know about it. It adds to the same inventory field the official plugin decrements. If you run that package as well, its holds are computed from recorded stock, so a restock raises availability the same way a manual correction would.

An item with no stock value is left alone. A product or variant whose inventory field is absent is treated as not tracking stock, exactly as the official plugin does, and the line counts as not restocked.

The refunded status is set, but no transition is checked. If you use payload-fulfillment with guardTransitions on, a full refund writes refunded through payload.update, which passes through that guard like any other write. A map that refuses the transition will refuse the refund. Set refundedStatus: '' if you would rather move the status yourself.

Order lines must sit at the document root. The plugin finds the items array inside rows, collapsibles and unnamed tabs, which is where the official plugin puts it, and reads it from the top level of the document. Inside a named tab or a group the data path changes, so the fields are not added there.

Existing orders show nothing until they are refunded. refundedAmount defaults to zero, but refundableAmount is written for the first time when the first refund lands. Orders already in the database keep an empty refundableAmount until then.

Deleting an order does not delete its refunds. The records keep pointing at an identifier that is gone. That is deliberate for an audit trail, and it means the refunds collection is the thing to export before you delete anything.

Nothing is refunded automatically. No webhook, no schedule, no cancellation hook. A refund happens when something in your application creates the record.

License

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

Similar plugins