Holograficzny bon podarunkowy na 200 zł w Medusa v2, połączony neonowymi liniami ze stoiskami trzech sprzedawców.

A gift voucher in a marketplace is customer money recorded against a code, not a price reduction. That is why the promotions module in Medusa cannot be used for it: a promotion cuts the cart price and disappears from the books, while someone paid real money for a voucher up front.

Artovnia is a handmade marketplace built on Medusa.js v2. A single cart collects products from many makers, and the payment is later split between their orders. The voucher balance has to survive multiple purchases, the seller receives the full value of their order even when the customer paid with a code, and everything has to add up in refunds, payouts and the DAC7 report.

The model: a bearer voucher, bought while logged in

We picked the model most large stores use: whoever knows the code pays with it in the cart. Even when Etsy emails a voucher straight to the recipient, the address is there for delivery, not for security.

How the voucher works
RuleHow it works
DenominationsPLN 100, PLN 200, PLN 300 and PLN 400; the server calculates the amount, the customer only picks it
Validity12 calendar months from the moment of the charge in Stripe, until end of day Warsaw time
Who buysonly a logged in customer with a confirmed email
Who paysanyone who knows the code, including people without an account
Balancethe unused remainder stays on the code for later purchases
Cart worth morethe customer covers the difference with a card or BLIK

We rejected guest purchase deliberately. A typo in a manually entered address would send a bearer code to a stranger. An account also gives us a place for everything that happens after the purchase: balance lookup, printing and editing the dedication.

The second reason is more serious. Vouchers are one of the favorite tools of financial fraudsters: a bearer code turns into money immediately, works without personal data and is easy to resell or extract from a victim. Hence the classic stolen card schemes, where a voucher bought anonymously is moved off the platform before the chargeback arrives. An account with a confirmed email, a purchase history and enforced 3D Secure leave a trail that simply does not exist with an anonymous purchase, and every voucher can be tied to a specific buyer and blocked in case of a dispute.

We also skipped emailing the voucher straight to the recipient. The buyer gets a PDF ready to hand over and passes it on themselves, and we do not write to people who are not our customers.

Architecture: a custom Medusa module and a balance ledger

Vouchers live in a custom Medusa v2 module (voucher) with five tables. The module does not import the cart or orders; workflows and API routes make those connections.

Module tables
TableWhat it holds
voucher_purchasea single voucher purchase: buyer, denomination, Stripe session, email delivery status, dedication
voucherthe voucher itself: code hash, encrypted code, balance, reserved amount, expiry date, block
voucher_reservationone checkout attempt using a voucher and its state
voucher_transactionthe ledger: every debit and credit of the balance with an idempotency key
voucher_admin_actionaudit of admin actions: block, resend, refund

The most important rule: the balance only changes inside a PostgreSQL transaction under a row lock on the voucher. Reading the balance, computing a new one in code and writing it back would lose debits when one checkout breaks into several orders at the same time.

A reservation separates "someone wants to pay with a voucher" from "they paid". When payment starts, part of the balance moves into reserved_amount. The reservation is then consumed (the orders were created), released (the customer abandoned payment) or reversed (the orders had to be rolled back). Every transition is idempotent, so a repeated webhook or a worker restart never spends anything twice.

This is what a reservation looks like in the module service. The voucher row is locked from reading the balance until the write, so two parallel carts cannot reserve more than the voucher has left.

typescript
async reserve(input: ReserveVoucherInput) {
  return this.knex_().transaction(async (trx) => {
    const voucher = await trx('voucher')
      .where({ id: input.voucher_id })
      .whereNull('deleted_at')
      .forUpdate()
      .first()

    if (!voucher || voucher.status !== 'active' ||
        new Date(voucher.expires_at) <= new Date()) {
      throw new VoucherError('voucher_unavailable', 'Voucher cannot be used')
    }
    const available = voucher.balance - voucher.reserved_amount
    if (input.amount > available) {
      throw new VoucherError('voucher_unavailable', 'Voucher balance changed')
    }

    const [reservation] = await trx('voucher_reservation')
      .insert({ voucher_id: voucher.id, cart_id: input.cart_id,
                amount: input.amount, status: 'active',
                cart_fingerprint: input.cart_fingerprint })
      .returning('*')
    await trx('voucher')
      .where({ id: voucher.id })
      .update({ reserved_amount: voucher.reserved_amount + input.amount })
    return reservation
  })
}

Buying a voucher: Stripe Checkout and issuing the code

The code is created only once Stripe confirms payment of exactly that amount in that currency. A voucher is a sale by the platform, so it goes through Stripe Checkout on the platform account, not on the seller accounts.

  1. The browser sends the denomination, an optional dedication and request_key, a random key for one purchase attempt.
  2. The backend records the purchase and the request to Stripe together with an idempotency key before it calls Stripe. If the response is lost on the way, the retry hits the same key and does not create a second paid session.
  3. The customer pays by card with enforced 3D Secure or with BLIK. We did not enable Klarna, because deferred payment for a prepaid instrument is asking for trouble.
  4. The webhook does not trust the event payload. It retrieves the session from Stripe and checks payment_status, the amount, the currency and the link to the purchase. A late or repeated event does not undo the purchase.
  5. Issuing the code is idempotent: parallel webhooks issue exactly one voucher. The email with the code and the PDF goes out afterwards.

The event only carries the session identifier, and we read the rest straight from Stripe, under a lock on that purchase. The email with the code goes out only after the lock is released.

typescript
const session = await stripe.checkout.sessions.retrieve(sessionId, {
  expand: ['payment_intent.latest_charge'],
})
const purchaseId = voucherPurchaseIdOf(session) // from session metadata

let deliver = false
const outcome = await withVoucherPurchaseLock(container, purchaseId, async () => {
  const purchase = await vouchers.retrievePurchaseRow(purchaseId)
  if (session.client_reference_id !== purchase.id) {
    throw new Error('Checkout Session does not belong to this purchase')
  }
  if (session.payment_status !== 'paid') return 'waiting'

  if (session.amount_total !== Number(purchase.amount) ||
      session.currency !== purchase.currency_code) {
    // Money arrived but the figures do not match: a human decides.
    return 'ignored'
  }

  // Idempotent: later calls only read the voucher that was already issued.
  const { created, purchase: issued } = await vouchers.issueVoucherForPurchase({
    purchase_id: purchase.id,
    amount: session.amount_total,
    currency_code: session.currency,
    stripe_checkout_session_id: session.id,
    paid_at: paidAtOf(session), // the moment the card was charged, not when the webhook ran
  })
  deliver = issued.delivery_status !== 'sent'
  return created ? 'issued' : 'already_issued'
})

// Delivery takes the same lock, so it only runs once the lock is released.
if (deliver && sendEmail) await sendVoucherIssuedEmail(container, purchaseId)
return outcome

Customers can come back from Stripe faster than the webhook. The confirmation page then polls the backend, which checks the stored session in Stripe, at most once every 10 seconds across all servers and browser tabs. It issues the voucher and shows it right away, while the email with the PDF stays on the webhook side, so the customer does not wait for the email provider.

A job every 5 minutes closes purchases the webhook never reached and retries the emails with the code. It handles payments and reservations first and takes deliveries last, each with a time limit, so a stalled email provider does not hold up refunds. It records the status "sent" only once the notification row confirms delivery.

Paying with a voucher: a cart credit line and many sellers

In the cart a voucher is a Medusa credit line (credit_lines), so cart.total immediately shows the amount left to pay. Nothing is charged yet; we lock the balance when payment starts.

  1. The customer enters the code. The server calculates how much the voucher covers from the cart value after all other discounts.
  2. Every cart change (loyalty points, a newsletter discount, a customer code) recalculates the voucher and corrects the payment amount. The reservation stores a cart fingerprint, so a change during payment closes the old attempt.
  3. If the voucher covers everything, Stripe is not involved at all: checkout creates a technical payment collection for 0 and creates the orders right away. When something is left to pay, Stripe charges at least PLN 2, because that is the minimum for card and BLIK.
  4. The cart breaks into orders for individual makers. We split the voucher share between them proportionally, and assign rounding remainders deterministically so the total always adds up.
  5. We store the split before the orders are created and never recalculate it later. Payouts, refunds and reports all use it.

Splitting the voucher between sellers uses the largest remainder method on minor units, with BigInt so precision is not lost. Ties are resolved by the seller key, so every retry produces an identical result.

typescript
export const allocateVoucher = (
  partitions: { key: string; value: number }[], // order value in minor units
  voucherTotal: number
) => {
  const total = partitions.reduce((sum, p) => sum + p.value, 0)
  const shares = partitions.map((p) => {
    const exact = BigInt(p.value) * BigInt(voucherTotal)
    const floor = exact / BigInt(total)
    return { ...p, voucher: Number(floor), remainder: exact - floor * BigInt(total) }
  })

  // Leftover minor units go to the largest remainders.
  let left = voucherTotal - shares.reduce((sum, s) => sum + s.voucher, 0)
  const order = [...shares].sort((a, b) =>
    a.remainder === b.remainder ? a.key.localeCompare(b.key)
      : a.remainder > b.remainder ? -1 : 1)
  for (const share of order) {
    if (left <= 0) break
    if (share.voucher < share.value) { share.voucher += 1; left -= 1 }
  }
  return shares.map(({ key, value, voucher }) =>
    ({ key, value, voucher, stripe: value - voucher }))
}

The hardest case is a failure halfway through, when the orders already exist but the voucher debit is not recorded yet. A retry of /complete never recreates the orders in that situation: it only closes the voucher part and reports the incomplete state to the admin. We clear a cart lock left by a dead process before the first workflow that needs it starts. A live process renews its lock every 40 seconds with a single query conditioned on the owner, so a late renewal never takes the lock from anyone. If the lock is lost anyway, the voucher is not debited and the payment goes to retry.

Refunds, payouts and DAC7

The seller receives the full order value regardless of how much the customer paid with a voucher. The voucher part counts in the payout as paid, because the platform took money for the voucher earlier. The seller sees the amount funded by a voucher, but never the code.

A refund of an order paid partly with a voucher is split in two: what was paid with the voucher returns to the voucher, and the rest returns to the card. For an order of PLN 300, of which PLN 200 came from a voucher and PLN 100 from a card, a refund of PLN 150 returns PLN 100 to the voucher and PLN 50 to the card. The voucher credit carries an idempotency key, and a voucher with only a few days of validity left gets an extension.

Traps we ran into:

  • Refunding the voucher purchase itself is possible only for an untouched balance. Otherwise you could buy a voucher, spend it, recover the balance through an order refund and then refund the voucher to the card.
  • The standard cancel and refund in the Medusa admin would refund the whole shared cart. For orders with a voucher and split orders we block them in middleware and route them to our own flow.
  • DAC7 initially only saw refunds from Stripe. For a single seller order a refund to the voucher was lost, and the report overstated the earnings. Now the DAC7 snapshot adds the voucher part from the order settlement itself.
  • A refund made in the Stripe dashboard does not carry the identifier of our operation, so at first nobody saw it and the code kept working. Now the webhook recognizes a voucher purchase by its PaymentIntent, blocks the voucher and sends an alert to the admin.
  • Blocking a voucher during payment (a dispute, an admin decision) did not stop a reservation made earlier. Now a debit on a blocked voucher is rejected, and the part paid by card comes back through the webhook and the job, even when the customer has already closed the browser tab.

Security: a bearer code is like cash

The code is 16 characters in the Crockford base32 alphabet, that is 80 random bits, printed as XXXX-XXXX-XXXX-XXXX. People copy them from paper, so letter case, spaces and hyphens do not matter, and O, I and L are read as 0, 1 and 1.

Normalization and lookup take a few lines. Only the digest is stored in the database, so even a full table dump yields no codes.

typescript
export const normalizeVoucherCode = (input: unknown): string | null => {
  if (typeof input !== 'string') return null
  const compact = input
    .toUpperCase()
    .replace(/[\s-]/g, '')
    .replace(/O/g, '0')
    .replace(/[IL]/g, '1')
  if (compact.length !== 16) return null
  for (const char of compact) if (!ALPHABET.includes(char)) return null
  return compact
}

export const hashVoucherCode = (normalized: string) =>
  createHmac('sha256', hashKey).update(normalized).digest('hex')

// in the module service
async findVoucherByCode(code: unknown) {
  const normalized = normalizeVoucherCode(code)
  if (!normalized) return null
  return this.knex_()('voucher')
    .where({ code_hash: hashVoucherCode(normalized) })
    .whereNull('deleted_at')
    .first()
}
  • There is no plaintext code in the database. We look up an entered code by a keyed digest (HMAC-SHA256). For display in the account and in the email we keep it encrypted (AES-256-GCM), with a random IV for every voucher.
  • The code never leaves the buyer. It is not in Stripe metadata, logs, seller facing data or integrations. The Medusa notification row, stored in plaintext, holds only the ciphertext, and the email provider decrypts it in memory just before sending.
  • Voucher search in the admin sends the query in the request body, not in the URL. A full code typed by an operator therefore never reaches proxy logs or telemetry.
  • Attempt limits count wrong codes per cart and per account before the code is checked. Counters per network address and global ones block nobody, they only raise alerts. Storefront traffic arrives from a few shared server addresses, so blocking by address would cut everyone off from their own valid vouchers.
  • A registered customer's cart can only be read, changed, paid and claimed by that customer, and the check covers all /store/carts/:id routes. Claiming a guest cart at login runs under a lock, so two simultaneous logins cannot divide it between accounts. A cart or order assigned to a deleted account is closed.
  • Calls from the browser. The session token sits in the storefront httpOnly cookie, so a request made straight from the browser to the backend arrives unauthenticated. The ownership check broke payment for logged in customers twice: the pay button and an internal cart fetch were going out anonymously. Today both go through the server with the customer token.
  • Coming back from Stripe. The session cookie uses SameSite=Strict, so it is not sent when entering from another site and the confirmation page saw a guest. The page then reloads itself once, and that navigation already happens inside the site.
  • Session recording. On pages that show a voucher code the session recording tool does not run. A guard in the root layout reloads the page when the script is already running, and the script itself checks the route just before it starts.

An independent code review gave us the most. The hook checking cart ownership looked for the customer where Medusa does not store it, and let every request through. A test with real authentication showed it in a minute, and the earlier unit tests never caught it.

A voucher to hand over: A5, a dedication and a PDF in the email

A voucher should be a gift, not a code in an email. Every buyer gets a printable version: A5 landscape (210 × 148 mm) on the top half of an A4 sheet. The sides and top of the voucher are the paper edges, so a single cut through the middle of the sheet is enough. The first version was 180 × 90 mm and turned out to be too small.

To, From and a message. At purchase the customer enters the recipient's name, their own and a few words. The voucher preview updates while they type, and the dedication can be corrected later in the account. Empty fields stay as lines to fill in by hand.

One layout for screen and print. The face of the voucher is described once, in "voucher millimeters". In print a millimeter is a millimeter, and in the preview it is 1/210 of the container width. The whole trick is a single CSS variable: every dimension of the face is a multiple of --mm, and the preview only overrides its value with container units.

CSS
.face {
  --mm: 1mm;                      /* print: real millimeters */
  --pt: calc(0.3528 * var(--mm)); /* typographic points */
  width: calc(210 * var(--mm));
  height: calc(148 * var(--mm));
}
.amount { font-size: calc(58 * var(--pt)); }
.dedication { width: calc(80 * var(--mm)); }
TSX
// Preview: 1 "voucher millimeter" = 1/210 of the container width.
<div className="[container-type:inline-size]">
  <VoucherFace style={{ "--mm": "calc(100cqw / 210)" }} {...props} />
</div>

The PDF generator in the backend draws the same numbers (16 mm from the edges, the amount at 58 pt, an 80 mm dedication column), so the preview shows exactly what comes out of the printer.

Long names. A double barrelled surname must not be cut off or run past the voucher, because the customer will treat that as a bug. Names and messages have a fixed area, and text that is too long shrinks the font. The same rule works in the preview, in print and in the PDF.

The PDF in the email. Medusa does not store attachments with a notification, so a resend would lose the file. The PDF is created in the email provider on every send, from the same data. The generator (pdf-lib) reproduces the page layout in millimeters. We embed fonts as TTF, because a WOFF2 subset crashed the whole Node process. Characters the font cannot draw, emoji for example, are stripped already while typing. If the PDF fails to generate, the email with the code still goes out.

GDPR: the buyer disappears, the voucher keeps working

After the account is deleted the voucher purchase loses its personal data, but the voucher itself stays valid for whoever holds the code.

What remains after the account is deleted
WhatAfter the account is deleted
email and customer ID on the purchasedeleted
stored request to Stripe (contains the email)deleted
names and message from the dedicationdeleted
recipient and dedication in the stored code emaildeleted
amount, dates, status, Stripe identifierskept as proof of sale
voucher, balance and balance historykept, the code works

The timing of anonymization is what matters. If we erased the purchase email during payment, the customer would pay and never receive the code. That is why we anonymize finished purchases immediately, and those in progress only once they finish, at the latest after 30 days. Order matters too: notifications first, then the purchase, so that a failed step leaves a marker for a retry.

Sending the email with the code and anonymization take the same purchase lock. After sending, Medusa saves the notification as the whole object from before the send, so a send that finishes later would restore the address and the dedication after the cleanup. Anonymization does not wait for the lock; a purchase that is being delivered is left for the next run of the job.

typescript
async listPurchasesToAnonymize(limit = 100) {
  const graceCutoff = new Date(Date.now() - 30 * 24 * 3600_000)
  return this.knex_()('voucher_purchase')
    .select('id')
    .whereNull('deleted_at')
    .whereRaw(`"metadata"->>'anonymize_requested_at' IS NOT NULL`)
    .where((settled) =>
      settled
        .whereIn('status', ['expired', 'failed', 'refunded'])
        .orWhere((paid) => paid.where({ status: 'paid', delivery_status: 'sent' }))
        .orWhereRaw(`("metadata"->>'anonymize_requested_at')::timestamptz < ?`,
                    [graceCutoff.toISOString()]))
    .limit(limit)
}

A small catch with knex: the JSONB ? operator collides with its parameter placeholder, which is why instead of "metadata" ? 'key' we use ->> ... IS NOT NULL.

Analytics and takeaways

We measure the voucher funnel in GA4 with four events that answer one question: how many people get lost at login.

  1. voucher_offer_view with a logged_in parameter: the offer loaded, and we know whether a guest is looking at it.
  2. voucher_auth_click: a click on "Log in" or "Create account".
  3. voucher_checkout_start: moving to payment, with information on whether there is a dedication.
  4. voucher_purchase: the voucher paid and issued, counted once, including after a page reload.

Voucher sales are deliberately not a purchase event. A voucher later spent on products would count in revenue twice. For the same reason we calculate the cart value in checkout events before subtracting the voucher, and send the voucher share and the top up separately. We mark an event as sent only once GA4 accepts it, so consent given later on the same page still measures the current view and purchase.

The chosen amount and dedication survive login, registration and email confirmation in a new tab, because otherwise the customer comes back to an empty form. The draft has an owner, so on a shared computer nobody sees someone else's message, and a guest draft moves to the account that logs in.

What we take away from this project:

  • Money belongs in a ledger, not in a field. Only transactions with a row lock and an idempotency key change the balance. Everything else, from webhooks to workers and retries, can then repeat without harm.
  • Every step has to survive a failure halfway through. Writing before the Stripe call, idempotent reservation transitions and a cleanup job every 5 minutes do more than the best happy path.
  • Verify data at the source. E-commerce events were landing in the dataLayer in GTM format even though the site loaded plain gtag.js, and for months they never reached GA4. It only surfaced during an event review inside GA4 itself.
  • The database has to enforce the wait limit. The timeout parameter in Medusa's locking.execute only races a JS timer against the lock query, so the job still waited for someone else's delivery to finish. A custom advisory lock with lock_timeout or pg_try_advisory_xact_lock really does end the wait.
  • A skeleton instead of loading in stages. The purchase block has a fixed shape from the first render, and only the content is swapped in after loading, so the page does not jump. We fetch the logged in customer with one shared query for the whole page; previously four parallel ones made the email appear after 3 seconds.
  • A test ends at clicking "Pay". Unit tests stubbed out login and fetch, so they could not see where the request actually went. The payment regression for logged in customers only showed up in a real purchase.

FAQ

Frequently asked questions

No. A promotion lowers the cart price and leaves no balance and no trace in settlements. A voucher is the customer's money: it has to survive several purchases, fund the vendor payout and go back onto the code on a refund. That takes a separate module with its own balance ledger.

Proportionally to the value of each maker's order, in PLN cents, using the largest remainder method. Ties are broken by the vendor key, so a retry gives an identical result. We store the split before the orders are created, and payouts, refunds and reports all read it.

No. The vendor gets the full order value, and the voucher part counts in the payout as paid, because the platform collected the money for the voucher earlier. The vendor sees the amount funded by the voucher, but never the code itself.

The database holds only a keyed HMAC-SHA256 hash for lookups and an AES-256-GCM encrypted copy for display in the account and in the email. The code never reaches Stripe metadata, logs or vendor data, and we count failed attempts per cart and per account.

The purchase loses its personal data: email, customer ID and the dedication. The amount, dates and Stripe identifiers stay as proof of sale, and the voucher itself, along with its balance, keeps working for whoever knows the code.