Skip to content

Gift cards and store credit

Install gift-card tender, protect bearer codes, and operate checkout holds, refunds, and balance ledgers.

@adocommercekit/store-credit is an optional tender package introduced in the 1.3.0 prerelease. It reduces the amount owed to a payment provider without treating store credit as a product discount.

Install and configure

Configure core first, using the same exact lockstep version for every commerce package:

pnpm add @adocommercekit/store-credit
node ace configure @adocommercekit/store-credit
node ace migration:run

The configurator registers @adocommercekit/store-credit/gift_cards_provider, publishes config/commerce_gift_cards.ts and validators, and creates the host-owned gift-card and transaction-ledger migration using core’s table prefix. Do not use the service until migrations run. The provider registers GiftCardService and its cart processor and subscribes to checkout, payment, cancellation, and refund events.

HTTP publication is conditional: storefront controllers/routes require app/services/commerce_api.ts; admin controllers/routes require app/services/commerce_admin.ts. A core-only host needs neither API package. Configure the optional API first and reconfigure gift cards to add that surface later; existing files are not overwritten.

Published application files:

Surface Files
Always config/commerce_gift_cards.ts, app/validators/commerce_gift_cards.ts, timestamped database/migrations/*_gift_cards.ts
Storefront API present app/controllers/commerce/gift_cards_controller.ts, start/routes/commerce_gift_cards.ts
Admin API present app/controllers/commerce_admin/gift_cards_controller.ts, start/routes/commerce_admin_gift_cards.ts

The package name is @adocommercekit/store-credit; GiftCardService, the gift_cards_provider entrypoint, config filename, HTTP paths, and abilities retain their gift-card identifiers.

defineGiftCardsConfig({ clock: () => DateTime.utc() }) supports an injected Luxon clock; the default is UTC now. Configure it in config/commerce_gift_cards.ts for deterministic expiry behavior, or construct GiftCardService(db, resolvedConfig) directly.

Public entrypoints

Import Contents
@adocommercekit/store-credit Config helper, errors, gift-card service/cart processor, models and types
@adocommercekit/store-credit/models Gift-card and transaction models
@adocommercekit/store-credit/services GiftCardService, GiftCardCartProcessor, and service types
@adocommercekit/store-credit/configure Adonis configure hook
@adocommercekit/store-credit/gift_cards_provider Service provider
@adocommercekit/store-credit/upgrade Publication manifest and artifact loader

Bearer-code security and issuance

issue({ amount: Money, customerId?, expiresAt? }, options?) returns { card, code }. Amounts must be positive safe minor-unit integers, at most 9007199254740991; adjustments must also leave balance in 0..9007199254740991. Expiry must be valid and in the future. A supplied customer must exist. Redemption requires matching currency and, for a customer-bound card, matching customer identity; expired, disabled, empty, or mismatched cards are unusable.

Codes are cryptographically random bearer secrets. Only the SHA-256 hash of the trimmed, uppercase code and its last four characters are stored. Protect the plaintext like a payment credential: deliver it once over a secure channel, and never put it in URLs, application logs, audit metadata, analytics, or durable idempotency responses.

Admin issuance returns { data: { card, code } } once. A successful idempotent replay returns that same card with code: null: the original secret is deliberately unrecoverable. Retain the first response securely rather than issuing another card after an ambiguous retry. Card DTOs expose neither plaintext nor hash. Balance lookup returns { available: false, currency: null, balanceAmount: null } for unusable or unknown codes. The storefront endpoint wraps that balance result in { data: ... }.

Storefront routes

Routes use /api/commerce, commerce error middleware, and a gift-card rate limit of 10 requests per 60 seconds:

Method Path Behavior
POST /cart/gift-card Apply a body code to the active cart and recalculate
DELETE /cart/gift-card Remove tender and recalculate
POST /gift-cards/balance Check body code, respecting customer restrictions

Balance lookup is POST specifically to avoid putting the bearer secret in URL/query logs. Applying a card stores its ID in cart metadata, not its plaintext code. Application is a quote, not a balance reservation: a later concurrent redemption can require recalculation.

Admin routes and policy

Routes use /api/commerce/admin with admin authentication, pre-auth limiting, and the read/mutation rate-limit tiers:

Method Path Ability
GET /gift-cards commerce.gift_cards.view
GET /gift-cards/:id/ledger commerce.gift_cards.view
POST /gift-cards commerce.gift_cards.manage
POST /gift-cards/:id/disable commerce.gift_cards.manage
POST /gift-cards/:id/adjust commerce.gift_cards.manage

Map these abilities in the host’s deny-by-default commerce policy. Issuance, disable, and adjustment use admin idempotency and transactional audit; audit records contain safe operation details, never codes or hashes. Lists and ledgers return { items, nextCursor, total: null }. Adjustments require a nonzero signed minor-unit amount, matching currency, and a reference of 1–128 characters. Reusing the same reference/amount is idempotent; changing the amount for that reference fails.

Checkout, cancellation, and refunds

The processor runs at position 1100, after tax, and creates an eligible negative gift_card adjustment capped at the lesser of available balance and the remaining total. It leaves no negative payable total. During checkout completion, holdOrder locks the card and debits its balance transactionally. OrderPlaced/PaymentCaptured settle that hold with captureOrder; OrderCanceled releases it. Ledger references make replay idempotent. A fully covered order follows zero-total checkout without creating a payment intent or calling a payment provider.

refundOrder(orderId, refundId, amount, options?) credits only captured, unreleased tender, capped at the held amount minus prior refunds. Refunds cannot manufacture store credit beyond that order’s gift tender. Release credits only the still-unrefunded portion. For returns, ReturnRefunded.nonPaymentAmount is credited separately from provider-paid paymentAmount; gift-only returns may have refundId: null. Provider refund rows carrying metadata.returnId are ignored by the generic payment-refund listener so the return’s gift credit is not duplicated. Keep these event subscriptions active, including outbox consumers.

The provider subscribes to the named core events OrderPlaced, PaymentCaptured, OrderCanceled, RefundSucceeded, and ReturnRefunded. Checkout holds are created by the cart processor’s checkoutCompleted hook, not by a separate event listener.

Ledger amount semantics

Ledger amount is the balance delta, serialized as a decimal minor-unit string:

Kind Balance effect
issue Positive initial credit
redeem_hold Negative debit
capture Zero: hold already debited the balance
release Positive remaining hold credit (possibly zero)
refund_credit Positive captured-tender refund
adjust Signed operator adjustment

An exhausted card becomes active again when credited, but a disabled card is not re-enabled by refund. Unique ledger references provide replay protection; do not infer captured spend by summing zero-valued capture rows in isolation.

Upgrade published files

@adocommercekit/store-credit/upgrade exports giftCardsUpgradeManifest and loadGiftCardsUpgradeArtifacts(root?). The version follows the package manifest. Configuration records newly published artifact baselines in .commercekit/publications; core’s commerce:upgrade uses them for reviewable no-op/update/conflict plans rather than blind overwrites. The root-aware loader excludes unavailable storefront/admin surfaces; without a root it returns the complete artifact catalog. Review generated changes, reconfigure when adding an optional API, and run any newly published migrations before deployment. See deployment and operations.

Navigation

Type to search…

↑↓ navigate↵ selectEsc close