order-management
v0.0.130
Published
A starter for Medusa plugins.
Maintainers
Readme
order-management
Order lifecycle management plugin for Medusa v2 with customer/guest cancel + reorder, returns, exchanges, payment detail capture, and refund mapping workflows.
Plugin Overview
order-management extends Medusa order operations with:
- customer and guest order actions (
cancel,reorder, returns, swaps), - OTP-based guest portal JWT flow,
- payment detail storage (
upi,bank,card) and default payment rules, - refund payment mapping and admin refund context tooling,
- order status email/notification subscribers,
- admin UI routes/widgets for returns, swaps, payments, refunds,
- store pickup / pay-at-store helpers (
GET /store/pickup-locations,POST /store/carts/:id/pickup) and required return-storelocation_idvalidation.
It solves common gaps where storefronts need secure post-purchase self-service (especially for guest orders), richer refund operations, and operational admin screens without implementing all workflows manually.
Built for Medusa v2 (@medusajs/framework/@medusajs/medusa 2.11.2 in package.json).
Installation & Setup
npm install order-management
# or
yarn add order-managementRegister plugin in medusa-config.ts:
import { defineConfig } from "@medusajs/framework/utils"
import orderManagement from "order-management"
export default defineConfig({
plugins: [
{
resolve: "order-management",
options: {
storefrontUrl: "https://store.example.com",
jwtSecret: "replace-with-strong-secret",
email: {
otpTemplate: "src/templates/emails/otp.html",
orderConfirmTemplate: "src/templates/emails/order-confirmation.html",
},
allowPayAtStore: true,
requireReturnStoreLocation: true,
capture_payment_on_pickup: true,
},
},
],
modules: [
orderManagement.modules["payment-detail"],
orderManagement.modules["refund-payment-mapping"],
orderManagement.modules["cancel-order-reason"],
orderManagement.modules["deleted-records-audit"],
],
})Run migrations:
npx medusa db:migrate⚠️ Note: the plugin contains module migrations under
src/modules/*/migrations; ensure those modules are registered inmodulesbefore runtime.
Configuration
Source: src/types/order-management-options.ts, normalized by src/config.ts.
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
| storefrontUrl | string | Yes | - | Base storefront URL (used in email claim links). |
| jwtSecret | string | Yes | - | Secret used to sign/verify guest OTP JWTs. |
| email.orderConfirmTemplate | string \| null | No | null | Template path for order confirmation subscriber emails. |
| email.otpTemplate | string \| null | No* | null | Template used by /store/otp/request; required for OTP flow. |
| smtp.enabled | boolean | No | false | Optional SMTP toggle for notification sending path. |
| smtp.host | string | No | undefined | SMTP host. |
| smtp.port | number | No | undefined | SMTP port. |
| smtp.secure | boolean | No | true | SMTP secure mode. |
| smtp.auth.user | string | No | undefined | SMTP username. |
| smtp.auth.pass | string | No | undefined | SMTP password. |
| smtp.from | string | No | undefined | Sender override. |
| notifications.enabled | boolean | No | false | Enables status-based notification subscriber handling. |
| notifications.statusConfig | Record<string, NotificationConfig[]> | No | {} | Map of order status to rules. Email/push: template = file path. SMS Twilio: template = inline body string. SMS MSG91: template_obj: { templateId, varMap? }. Optional getRecipient. |
| capture_payment_on_delivered | boolean | No | true | Auto-capture remaining authorized amount on delivery events. |
| capture_payment_on_pickup | boolean | No | true | Capture pay-at-store / authorized amount when store pickup is collected. |
| allowPayAtStore | boolean | No | true | Allow offline payment for web store-pickup carts. |
| requireReturnStoreLocation | boolean | No | true | Require a valid stock location on return/exchange create. |
| returnValidInDays | number | No | 7 | Return request window in days from delivered_at. |
| exchangeValidInDays | number | No | 7 | Exchange request window in days from delivered_at. |
Pickup / pay-at-store notification keys (under notifications.statusConfig): pickup_pay_at_store_placed, pickup_ready, pickup_collected, pay_at_store_captured.
Example:
{
resolve: "order-management",
options: {
storefrontUrl: "https://store.example.com",
jwtSecret: "super-secret",
email: {
otpTemplate: "src/templates/emails/otp.html",
orderConfirmTemplate: "src/templates/emails/order-confirmation.html",
},
notifications: {
enabled: true,
statusConfig: {
shipped: [{ template: "src/templates/emails/shipped.html", channel: "email" }],
},
},
returnValidInDays: 7,
exchangeValidInDays: 7,
capture_payment_on_delivered: true,
},
}Environment Variables
Direct process.env.* usage in plugin source:
| Variable | Required | Used In | Purpose |
|---|---|---|---|
| NODE_ENV | No | API handlers | Includes stack trace in development error responses. |
Most production values are expected to be supplied via plugin options in medusa-config.ts (for example jwtSecret, storefrontUrl, SMTP settings).
REST APIs / Routes
Store Routes
| Method | Endpoint | Auth | Description |
|---|---|---|---|
| GET | /store/plugin | Public | Health endpoint. |
| POST | /store/otp/request | Public | Sends OTP to email/phone using configured OTP template. |
| POST | /store/otp/verify | Public | Verifies OTP and returns guest JWT. |
| POST | /store/orders/cancel/:order_id | Customer JWT | Cancel customer order; requires reason_id. |
| POST | /store/orders/reorder/:order_id | Customer JWT | Reorder into new cart (force_reorder query optional). |
| GET | /store/orders/:order_id/cancel-reason-mapping | Customer JWT | Get cancel reason label mapping for order. |
| GET | /store/orders/:order_id/refund-payment-mappings | Customer JWT | Get all refund mappings for order returns. |
| POST | /store/returns | Customer JWT | Create return (StoreCreateReturnSchema). |
| GET | /store/returns | Customer JWT | List customer returns (order_id, limit, offset). |
| GET | /store/returns/:id | Customer JWT | Get return details. |
| POST | /store/returns/:id/cancel | Customer JWT | Cancel return. |
| POST | /store/swaps | Customer JWT | Create exchange request. |
| GET | /store/swaps | Customer JWT | List exchange requests. |
| GET | /store/swaps/:id | Customer JWT | Get exchange request. |
| POST | /store/swaps/:id/cancel | Customer JWT | Cancel exchange request. |
| GET | /store/payment-details | Customer JWT | List payment details. |
| POST | /store/payment-details | Customer JWT | Create payment detail (type, detail_json). |
| GET | /store/payment-details/:id | Customer JWT | Retrieve payment detail. |
| PUT | /store/payment-details/:id | Customer JWT | Update payment detail. |
| DELETE | /store/payment-details/:id | Customer JWT | Delete payment detail. |
| POST | /store/payment-details/:id/make-default | Customer JWT | Set default payment detail. |
| GET | /store/refund-payment-mapping/:return_id | Customer JWT | Get refund mapping for owned return. |
| PUT | /store/refund-payment-mapping/:return_id | Customer JWT | Update payment_id only (customer-safe fields). |
| GET | /store/guest-orders | Guest JWT | List guest orders. |
| GET | /store/guest-orders/:id | Guest JWT | Get guest order. |
| POST | /store/guest-orders/:id/cancel | Guest JWT | Cancel guest order. |
| POST | /store/guest-orders/:id/reorder | Guest JWT | Reorder guest order. |
| POST | /store/guest-orders/:id/returns | Guest JWT | Create guest return (optional refund_payment / refund_payment_id). |
| GET/POST | /store/guest-orders/:id/payment-details | Guest JWT | List / create guest refund destinations. |
| PUT | /store/guest-orders/:id/returns/:return_id/refund-payment | Guest JWT | Link payment_detail to return mapping. |
| GET | /store/guest-orders/:id/swaps | Guest JWT | List guest exchange requests. |
| POST | /store/guest-orders/:id/swaps | Guest JWT | Create guest exchange request. |
| GET | /store/guest-orders/:id/swaps/:swap_id | Guest JWT | Get guest exchange request. |
| POST | /store/guest-orders/:id/swaps/:swap_id/cancel | Guest JWT | Cancel guest exchange request. |
| GET | /store/guest-orders/:id/cancel-reason-mapping | Guest JWT | Get cancel reason mapping for guest order. |
Admin Routes
| Method | Endpoint | Auth | Description |
|---|---|---|---|
| GET | /admin/plugin | Admin JWT | Health endpoint. |
| GET | /admin/return | Admin JWT | List returns (filters/paging). |
| GET | /admin/return/:id | Admin JWT | Return details. |
| POST | /admin/return/:id/reject | Admin JWT | Reject/cancel return. |
| GET | /admin/swaps | Admin JWT | List exchanges (filters/paging). |
| GET | /admin/swaps/:id | Admin JWT | Exchange details. |
| POST | /admin/swaps/:id/reject | Admin JWT | Reject exchange. |
| POST | /admin/swaps/:id/cancel | Admin JWT | Cancel exchange. |
| GET | /admin/payment-transactions | Admin JWT | List payment sessions/transactions. |
| GET | /admin/payment-transactions/:id | Admin JWT | Payment session details. |
| GET | /admin/refunds | Admin JWT | List refunds. |
| GET | /admin/refunds/:id | Admin JWT | Refund detail + computed summary. |
| GET | /admin/orders/:order_id/refund-context | Admin JWT | Aggregated order refund context (return_status, can_process_refund). |
| GET | /admin/orders/:order_id/cancel-reason-mapping | Admin JWT | Cancel reason mapping for order. |
| PUT | /admin/refund-payment-mapping/:return_id | Admin JWT | Update refund_mode, images, details. |
| POST | /admin/refund-payment-mapping/:return_id/mark-refunded | Admin JWT | Set is_refunded=true (requires return received; 400 NOT_ALLOWED otherwise). |
| GET | /admin/deleted-records-audit | Admin JWT | Paginated hard-delete audit entries (no old_data). See Deleted Records audit. |
| GET | /admin/deleted-records-audit/stats | Admin JWT | All-time counts for summary cards plus known source / deleted_by values. |
| GET | /admin/deleted-records-audit/:id | Admin JWT | One audit entry including the full old_data snapshot. |
Important endpoint examples:
curl -X POST "http://localhost:9000/store/otp/request" \
-H "content-type: application/json" \
-d '{"email":"[email protected]"}'curl -X POST "http://localhost:9000/store/orders/cancel/order_123" \
-H "authorization: Bearer <customer_token>" \
-H "content-type: application/json" \
-d '{"reason_id":"rr_123"}'curl "http://localhost:9000/admin/orders/order_123/refund-context" \
-H "authorization: Bearer <admin_token>"Services
| Service | Responsibility | Key Methods |
|---|---|---|
| OtpService | OTP generation/verification and guest JWT minting | generate, verify, generateToken |
| PaymentDetailModuleService | Payment detail CRUD and default constraints | createPaymentDetail, updatePaymentDetail, deletePaymentDetail, makeDefault, hasDefaultPayment, listPaymentDetailsByCustomer |
| RefundPaymentMappingModuleService | Return-to-payment mapping management | createMapping, getByReturnId, updatePaymentId, markRefunded, updateAdminFields |
| CancelOrderReasonModuleService | Stores cancel reason used for an order | assertReasonExists, recordOrderCancelReason, getMappingWithReasonLabel |
| DeletedRecordsAuditModuleService | Reads the hard-delete audit trail | listAudits, retrieveAudit, getStats |
Workflows & Steps (Medusa v2)
Workflows
| Workflow | Input | Output | Description |
|---|---|---|---|
| reorder | { order_id, customer_id, force_reorder? } | { cart_id } | Rebuilds cart from prior order with inventory checks. |
| order-management-cancel-order | { order_id, customer_id } | { order_id, status, message } | Validates ownership and cancels order through Medusa flow. |
Steps
| Step | Description |
|---|---|
| retrieve-order | Retrieves order and validates customer ownership. |
| transform-order-to-cart | Converts order lines to cart lines, validates inventory and force behavior. |
| create-cart-from-order | Creates cart via Medusa createCartWorkflow. |
| cancel-order-step | Checks fulfillment state and runs Medusa cancel order workflow. |
| validate-no-active-order-change | Blocks duplicate active order changes. |
| send-notification-step | Notification helper used by OTP/subscribers. |
Subscribers / Event Hooks
| Subscriber | Event(s) | Action |
|---|---|---|
| send-order-email | order.placed | Loads order data, renders configured template, sends order confirmation email. |
| order-status-change | order.updated, order.placed, order.shipment_created, order.fulfillment_created, order.completed, order.canceled, delivery.created | Triggers status-based notifications from plugin config. |
| order-fulfilled | delivery.created, shipment.delivered, shipment.deliver, order.shipment_delivered, fulfillment.shipment_delivered | Completes delivered order; optionally captures remaining authorized payment. |
Admin UI / Widgets
| Extension | Placement | UI | Interactions/Data |
|---|---|---|---|
| Returns routes | /returns, /returns/:id | Return listing/detail pages | Search, filters, reject return; uses /admin/return*. |
| Swaps routes | /swaps, /swaps/:id | Exchange listing/detail pages | Search, filters, reject/cancel exchange; uses /admin/swaps*. |
| Payments routes | /payments, /payments/:id | Transaction list + detail pages | Filter transactions and inspect gateway payload. |
| Refunds routes | /refunds, /refunds/:id | Refund list + detail pages | Filter by status/provider/date/amount; view computed refund context. |
| Deleted Records routes | /deleted-records-audit, /deleted-records-audit/:id | Audit list + investigation detail | Summary cards, record ID search, entity/date/source/deleted-by filters in the URL; detail shows record summary, masked raw data and next steps. |
| order-gift-items-widget | order.details.side.after | Gift item widget | Reads gift metadata and downloads generated gift card image. |
Models & Entities
| Entity | Fields | Relationship Notes |
|---|---|---|
| payment_detail | id, customer_id, type, detail_json, is_default | Linked logically to Medusa customer via customer_id. |
| refund_payment_mapping | id, return_id (unique), payment_id?, is_refunded, refund_mode?, images, details? | Links a return to refund destination and admin reconciliation metadata. |
| cancel_order_reason_mapping | id, order_id, reason_id | Migration defines FK to return_reason(id). |
| deleted_records_audit | id, table_name, record_id?, operation, old_data (jsonb), occurred_at, deleted_by?, source? | Append-only; written by Postgres BEFORE DELETE triggers, never by application code. |
Use Cases & Examples
- Guest self-service after checkout without account: OTP authenticate and allow secure cancel/reorder/return/exchange flows.
- Customer reorder with inventory-safe behavior: create cart from previous order, optionally partial with
force_reorder. - COD return refund handling: enforce default payment details and track refund destination via mapping module.
- Operations refund control: admin edits refund mode/details/images and marks refunded with visibility in order detail widget.
- Automated post-delivery capture and communications: delivery events drive capture flow and status notifications.
Troubleshooting
| Issue | Likely Cause | Resolution |
|---|---|---|
| OTP request fails with template/config message | Missing email.otpTemplate or unresolved plugin options | Configure plugin options in medusa-config.ts; verify template path exists. |
| Guest JWT endpoints return unauthorized | Invalid/expired token or jwtSecret mismatch | Re-run OTP verify and ensure same jwtSecret is used in runtime config. |
| Store cancel returns generic An error occurred | Workflow failure was wrapped and not unwrapped by the cancel route | Upgrade this plugin. Nested Medusa/workflow errors are now unwrapped into a real message. Check payment refund/void logs if cancel still fails. |
| Backend fails to start: Package subpath './zod' is not defined in @medusajs/framework | Validators imported @medusajs/framework/zod, which older framework builds do not export | Upgrade to order-management ≥ 0.0.95 (validators import zod directly). |
| Cancel blocked by open fulfillments on a “not fulfilled” order | Core cancel requires all fulfillments to have canceled_at | Upgrade this plugin. Unshipped open fulfillments are canceled automatically before core cancel. |
| Return/exchange blocked with RETURN_WINDOW_EXPIRED | Delivery date outside configured window | Increase returnValidInDays/exchangeValidInDays or update storefront UX for expiry handling. |
| Refund mapping routes fail | refund-payment-mapping module not registered/migrated | Register module and run migrations. |
| Guest return shows no payment method in Admin | Guest COD returns previously stored payment_id=null and guests could not create/link payment details | Upgrade this plugin. Pass refund_payment / refund_payment_id on guest return create, or use POST /store/guest-orders/:id/payment-details + PUT .../returns/:return_id/refund-payment. |
| Cannot set default payment via create/update | API intentionally blocks is_default in request body | Use POST /store/payment-details/:id/make-default. |
| No development stack traces in API errors | NODE_ENV not development | Set NODE_ENV=development locally when debugging. |
| Deleted Records page is empty after deletes | deleted-records-audit module not registered/migrated, or rows were soft-deleted (deleted_at set) rather than hard-deleted | Register the module and run npx medusa db:migrate. Only real SQL DELETEs are captured. |
| Deleted Records shows "Unknown" for Deleted by / Source | The app didn't set app.audit_actor_id / app.audit_source in the deleting transaction | Expected by default. See Recording who deleted a record. |
Compatibility
This plugin is compatible with Medusa v2 (e.g. @medusajs/framework and @medusajs/medusa 2.11.x). Check package.json peer dependencies for the exact version range.
Features
- Order Management: Cancel and reorder for both authenticated customers and guest orders
- Cancel error surfacing: Customer/guest cancel routes unwrap nested Medusa workflow errors so the storefront shows the real failure (not a bare
An error occurred) - Cancel pre-clears unshipped fulfillments: Before calling Medusa core cancel, open unshipped fulfillments are canceled so pending orders are not blocked by fulfillment rows
- Authenticated Customer APIs: Store endpoints for logged-in customers to cancel orders (
/store/orders/cancel/:order_id), reorder (/store/orders/reorder/:order_id), manage returns (/store/returns), and manage exchanges (/store/swaps) - Guest Order Portal: OTP-based look-up for guest users with full order management (view orders, initiate returns, cancel, reorder)
- Guest Order Actions: Secure JWT-protected endpoints for guest users to view orders, initiate returns (via Medusa workflow), cancel orders, reorder (all under
/store/guest-orders/:id/...) - Order Confirmation Emails: Optional email notifications when orders are placed (with "Claim Order" support for registered users)
- Status-Based Notifications: Configurable email, SMS, and push notifications for order status changes (pending, shipped, delivered, canceled, etc.)
- Return / Exchange Delivery Window: Configurable per-type windows (
returnValidInDays,exchangeValidInDays) that block return or exchange requests submitted after N days from the fulfillment'sdelivered_attimestamp. Defaults to 7 days each if not configured. The window is checked only when the order has been marked as delivered; undelivered orders are unaffected. - Return / Exchange mutual exclusion: Order-level lock via
order_rma_gate— an active return blocks creating an exchange (and a second return), and vice versa. Same helper on store and guest create routes. Gate uses a partial unique index onorder_idand atomic stale reclaim (SELECT … FOR UPDATE). Unlock on cancel/reject or when return status is actuallyreceived. - Return Orders Admin Panel: Admin UI and API for return orders (list, filter, search, detail, reject); returns are stored in the Medusa ORDER module and created via
createAndCompleteReturnOrderWorkflow - Exchanges Admin Panel: Admin UI and API for exchanges (list, detail, reject, cancel); exchanges are ORDER module order changes (type
exchange) created by customers via Medusa core workflows (beginExchangeOrderWorkflow, etc.) - Medusa workflows: Customer returns use
createAndCompleteReturnOrderWorkflow; customer exchanges usebeginExchangeOrderWorkflow,orderExchangeRequestItemReturnWorkflow,orderExchangeAddNewItemWorkflow,confirmExchangeRequestWorkflow, andcancelBeginOrderExchangeWorkflow. Admin actions useconfirmReturnReceiveWorkflow,cancelReturnWorkflow, andcancelBeginOrderExchangeWorkflow. - Payment details: Custom module
payment_detailfor customer payment methods (UPI, bank, card). Store CRUD at/store/payment-details. Type-driven validation — UPI requiresupi_id; bank requiresaccount_holder_name,bank_name,account_number,ifsc(optionalbranch_name); card requirescard_holder_name,card_number,expiry_date,cvv. One default per customer; return creation requires at least one default payment method. - Refund payment mapping: Table
refund_payment_mapping(one row per return:return_id,payment_id,is_refunded,refund_mode,images,details). A mapping is created automatically when a return is created. Customer can GET mapping (read-only for all fields) and PUTpayment_idonly whileis_refunded = false; customer can also GET all mappings for an order to see if all refunds are successful. Only admin can setis_refunded,refund_mode(offline/online),images, anddetails. - Deleted Records audit: Postgres
BEFORE DELETEtriggers on 190 commerce/plugin tables copy every hard-deleted row intodeleted_records_audit. An Admin page (Deleted Records) lets admins search by record ID, filter by entity/date/source, read a human-readable summary of what was deleted, inspect the full (secret-masked) snapshot, and see what to do next. See Deleted Records audit. - Receive-before-refund: Admin payment refunds (
POST /admin/payments/:id/refund) andPOST /admin/refund-payment-mapping/:return_id/mark-refundedare rejected with400 NOT_ALLOWEDwhile any return on the order isopen,requested, orpartially_received(including exchange-linked returns). Receive items first. Refunds with no unreceived return (order cancel / goodwill) still work. Receive-and-refund inside Medusa’s receive workflow is not blocked.
Plugin structure (high level)
| Area | What the plugin provides |
|------|---------------------------|
| Store (authenticated) | /store/orders/cancel|reorder/:id, /store/returns, /store/swaps, /store/payment-details, /store/refund-payment-mapping/:return_id, /store/orders/:order_id/refund-payment-mappings |
| Store (guest) | /store/otp/request|verify, /store/guest-orders, /store/guest-orders/:id/returns|cancel|reorder|swaps |
| Admin | /admin/returns, /admin/swaps, /admin/refund-payment-mapping/:return_id, /admin/refund-payment-mapping/:return_id/mark-refunded, /admin/orders/:order_id/refund-context |
| Modules | payment_detail, refund_payment_mapping, order_rma_gate; returns/exchanges use Medusa ORDER module |
| Subscribers | Order confirmation email, status notifications, return/swap event sync, order.return_received RMA gate release |
Important APIs (quick reference)
| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| Store (customer) | | | |
| POST | /store/orders/cancel/:order_id | Customer | Cancel order |
| POST | /store/orders/reorder/:order_id | Customer | Reorder (new cart) |
| GET | /store/returns | Customer | List returns (optional ?order_id=) |
| POST | /store/returns | Customer | Create return |
| GET | /store/returns/:id | Customer | Get return |
| POST | /store/returns/:id/cancel | Customer | Cancel return |
| GET | /store/swaps | Customer | List swaps (optional ?order_id=) |
| POST | /store/swaps | Customer | Create swap |
| GET | /store/swaps/:id | Customer | Get swap |
| POST | /store/swaps/:id/cancel | Customer | Cancel swap |
| GET | /store/payment-details | Customer | List payment details |
| POST | /store/payment-details | Customer | Create payment detail |
| GET | /store/payment-details/:id | Customer | Get payment detail |
| PUT | /store/payment-details/:id | Customer | Update payment detail |
| POST | /store/payment-details/:id/make-default | Customer | Set default payment |
| GET | /store/refund-payment-mapping/:return_id | Customer | Get mapping (own return) |
| PUT | /store/refund-payment-mapping/:return_id | Customer | Update payment_id only |
| GET | /store/orders/:order_id/refund-payment-mappings | Customer | List mappings for order |
| Store (guest) | | | |
| POST | /store/otp/request | — | Request OTP |
| POST | /store/otp/verify | — | Verify OTP, get JWT |
| GET | /store/guest-orders | Guest JWT | List guest orders |
| GET | /store/guest-orders/:id | Guest JWT | Get guest order |
| POST | /store/guest-orders/:id/returns | Guest JWT | Create return |
| POST | /store/guest-orders/:id/cancel | Guest JWT | Cancel order |
| POST | /store/guest-orders/:id/reorder | Guest JWT | Reorder |
| GET/POST | /store/guest-orders/:id/swaps | Guest JWT | List / create swaps |
| Admin | | | |
| GET | /admin/returns | Admin | List returns |
| GET | /admin/returns/:id | Admin | Get return |
| POST | /admin/returns/:id/reject | Admin | Reject return |
| GET | /admin/swaps | Admin | List swaps |
| GET | /admin/swaps/:id | Admin | Get swap |
| POST | /admin/swaps/:id/reject | Admin | Reject swap |
| POST | /admin/swaps/:id/cancel | Admin | Cancel exchange |
| GET | /admin/orders/:order_id/refund-context | Admin | Refund context (return + return_status + can_process_refund + mapping + payment_detail + order checkout payment) |
| PUT | /admin/refund-payment-mapping/:return_id | Admin | Update refund_mode, images, details |
| POST | /admin/refund-payment-mapping/:return_id/mark-refunded | Admin | Mark mapping as refunded (requires return received) |
| POST | /admin/uploads | Admin | Upload file (Medusa core; used by widget for refund images) |
Configuration
The plugin can be configured in your medusa-config.js file:
import { defineConfig } from "@medusajs/framework/utils"
module.exports = defineConfig({
// ...
plugins: [
{
resolve: "order-management",
options: {
// Required options
storefrontUrl: process.env.STOREFRONT_URL || "http://localhost:8000",
jwtSecret: process.env.JWT_SECRET || "medusa-secret-guest-access",
// Email template options
email: {
orderConfirmTemplate: "src/templates/emails/order-confirmation.html", // Path to HTML template file
otpTemplate: "src/templates/emails/otp-verification.html", // Path to HTML template file (required)
},
// Optional SMTP configuration (for email delivery)
smtp: {
enabled: process.env.FORCE_SMTP_REDELIVER === "true",
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT ? Number(process.env.SMTP_PORT) : undefined,
secure: process.env.SMTP_SECURE === "true",
auth: {
user: process.env.SMTP_AUTH_USER,
pass: process.env.SMTP_AUTH_PASS,
},
from: process.env.SMTP_FROM || process.env.SMTP_AUTH_USER,
},
// Optional: number of days after delivery within which returns are allowed (default: 7)
returnValidInDays: 7,
// Optional: number of days after delivery within which exchanges are allowed (default: 7)
exchangeValidInDays: 7,
// Optional status-based notification configuration
notifications: {
enabled: true,
statusConfig: {
"pending": [
{
template: "src/templates/emails/order-placed.html",
channel: "email"
},
{
template: "src/templates/sms/order-placed.txt",
channel: "sms",
getRecipient: (order, _templateData) =>
order.shipping_address?.phone || order.billing_address?.phone
},
{
template: "src/templates/push/order-placed.txt",
channel: "push"
}
],
"shipped": [
{
template: "src/templates/emails/order-shipped.html",
channel: "email"
}
],
"delivered": [
{
template: "src/templates/emails/order-delivered.html",
channel: "email"
}
],
"canceled": [
{
template: "src/templates/emails/order-canceled.html",
channel: "email"
}
]
}
},
// Optional: auto-capture payment on delivered events (default: true)
capture_payment_on_delivered: true,
},
},
],
})Configuration Options
Required Options:
storefrontUrl- Your storefront URL (required)jwtSecret- JWT secret for guest order tokens (required)
Email Template Options:
email.orderConfirmTemplate- Path to HTML template file for order confirmation emails (optional)email.otpTemplate- Path to HTML template file for OTP verification emails (required for guest OTP functionality)
Optional SMTP Options:
smtp.enabled- Enable SMTP email delivery (default:false)smtp.host- SMTP server host (required if enabled)smtp.port- SMTP server port (required if enabled)smtp.secure- Use secure connection (default:true)smtp.auth.user- SMTP username (required if enabled)smtp.auth.pass- SMTP password (required if enabled)smtp.from- From email address (optional, defaults tosmtp.auth.user)
Optional Return / Exchange Window Options:
returnValidInDays— Number of days afterfulfillment.delivered_atwithin which a customer may request a return. Defaults to7. Set to a higher value to allow a longer window; the check is skipped entirely if the fulfillment has nodelivered_attimestamp.exchangeValidInDays— Number of days afterfulfillment.delivered_atwithin which a customer may request an exchange. Defaults to7. Independent fromreturnValidInDaysso you can allow different windows for each action type.
When the window has expired the API returns:
{
"type": "RETURN_WINDOW_EXPIRED",
"message": "Returns and exchanges are only allowed within 7 days of delivery. The 7 days window for this order has expired.",
"delivered_at": "2026-03-07T10:46:59.153Z",
"window_days": 7
}Optional Status-Based Notification Options:
notifications.enabled- Enable status-based notifications (default:false)notifications.statusConfig- Map of order status to notification configurations- Each status can have multiple notification configurations
- Each configuration requires:
template- Path to template file (HTML for email, text for SMS/push)channel- Notification channel (supports any string:"email","sms","push", or any custom channel)
- Optional per-config:
getRecipient(order, templateData)- Function that receives the order and template data and returns the recipient for this notification (e.g. mobile number for SMS, customer_id for push). If omitted, the default resolver for the channel is used (e.g.order.emailfor email,shipping_address.phonefor SMS,order.customer_idfor push).
- Push channel: For
channel: "push", the recipient is treated as a customer_id. The code loads all active device tokens for that customer from thenotification_tokensmodule (e.g. when using themedusa-notification-token-managementplugin) and sends one push notification to each token. If the token module is not installed or the customer has no tokens, no push is sent. - SMS channel: The plugin sends the SMS body in a form compatible with medusa-twilio-sms (
content.text) and astext/body/data.textfor other adapters. If you use medusa-twilio-sms and patch it to also accept stringcontentordata.text, usenpx patch-package medusa-twilio-smsafter editing so the fix persists across installs.
Optional Delivery Payment Capture Option:
capture_payment_on_delivered- Automatically captures the remaining authorized payment amount when delivery events are received (default:true). Set tofalseto disable auto-capture.
Notes:
storefrontUrlandjwtSecretare required. All other options are optional.- Order confirmation emails are only sent if a template path is provided. If no template is configured, emails will not be sent.
- OTP template is mandatory for guest OTP functionality. The guest OTP request API will return an error if
email.otpTemplateis not configured. - OTP templates should include
{{otp}}placeholder for the verification code. - SMTP configuration is optional. If not enabled, emails will use Medusa's default email provider.
- Status-based notifications are optional. If enabled, notifications will be sent whenever an order reaches a configured status.
- Payment auto-capture on delivery is enabled by default and captures only the remaining uncaptured amount, skipping already captured payments.
Payment detail module
The plugin includes a payment_detail module for storing customer payment methods (e.g. UPI, bank, card). To use it:
- Register the module in
medusa-config.js:
import orderManagement from "order-management"
module.exports = defineConfig({
modules: [
// ... other modules
orderManagement.modules["payment-detail"],
],
plugins: [
{ resolve: "order-management", options: { storefrontUrl: "...", jwtSecret: "..." } },
],
})Run migrations from your Medusa project (or from the plugin directory):
npx medusa plugin:db:generate(if using the plugin's migrations from the app).Store API (authenticated customers only):
GET /store/payment-details– list (scoped tocustomer_id)GET /store/payment-details/:id– get onePOST /store/payment-details– create (type,detail_jsononly;is_defaultis rejected)PUT /store/payment-details/:id– update (nois_default; use make-default endpoint)DELETE /store/payment-details/:id– deletePOST /store/payment-details/:id/make-default– only way to set a payment as default (idempotent, atomic)
Validation:
typemust be one ofupi,bank,card.detail_jsonis type-driven:type: "upi"→detail_json.upi_idrequiredtype: "bank"→account_holder_name,bank_name,account_number,ifscrequired;branch_nameoptionaltype: "card"→card_holder_name,card_number,expiry_date(MM/YY),cvvrequired
Default payment: At least one record per customer must have
is_default: true. Only one default per customer (enforced by DB unique partial index and service logic). The only way to change which record is default isPOST /store/payment-details/:id/make-default; create/update APIs rejectis_defaultin the body. Creating a return (POST /store/returns) is blocked if the customer has no default payment method.
Refund payment mapping module
The plugin includes a refund_payment_mapping module: one row per return linking a return to a payment (e.g. for refund destination), with is_refunded, refund_mode, images, and details.
- Table:
refund_payment_mapping—id,return_id(unique),payment_id,is_refunded(defaultfalse),refund_mode(text, nullable; admin-only: use"offline"or"online"),images(JSON array of URLs),details(text, nullable; admin-only notes), timestamps. - Auto-create: When a return is created (store or guest), a mapping row is created; optional
refund_payment_idcan be sent in the create-return body. - Store API:
GET /store/refund-payment-mapping/:return_id— get mapping for one return (customer must own the return). Returns all fields read-only; customer can seeis_refunded,refund_mode,images,details.PUT /store/refund-payment-mapping/:return_id— body{ payment_id }only; allowed only whileis_refunded = false. Request body must not includerefund_mode,images, ordetails(admin-only).GET /store/orders/:order_id/refund-payment-mappings— list all refund payment mappings for the order’s returns (customer must own the order). Use to show “all refunds successful” vs “some pending” (checkis_refundedon each).
- Admin API:
PUT /admin/refund-payment-mapping/:return_id— update admin-only fields. Body:{ refund_mode?: "offline" | "online" | null, images?: string[], details?: string | null }(partial; only provided keys are updated).POST /admin/refund-payment-mapping/:return_id/mark-refunded— setis_refunded = true(idempotent). Requires Medusa return statusreceived; otherwise400 NOT_ALLOWED. Already-refunded mappings still succeed without re-checking receive status.
- Receive-before-refund guard: Middleware on Medusa core
POST /admin/payments/:id/refundrejects the request with400 NOT_ALLOWEDwhen the order has any return inopen,requested, orpartially_received(including exchange-linked returns). Message:Cannot process a refund while the return is {status}. Receive the returned items first.Orders with no return, or onlyreceived/canceledreturns, are not blocked. - Order detail integration:
GET /admin/orders/:order_id/refund-context— aggregated read returningreturn_id,return_status,can_process_refund(trueonly when status isreceivedand the mapping exists and is not already refunded),order_payment(checkoutprovider_id, human-readablelabel,is_cod— used for guest orders that have no savedpayment_detail),refund_mapping(id, payment_id, is_refunded, refund_mode, images, details),payment_detail(id, type, detail_json, is_default) resolved from the customer's specified or default payment detail, andrefund(product_amount, return_charge, expected_net_amount, final_refund_amount, currency_code, is_processed, breakdown_matches, destination_label).final_refund_amountis the processed payment refund (or COD/offlinereturn.refund_amountafter mark-refunded), notproduct_amount - return_charge. Returns null blocks when no return or mapping exists. Used by admin refund/return detail pages; refund_mode, images, and details are admin-only via the mapping APIs above. - Store return payload:
GET /store/returnsandGET /store/returns/:idattach the samerefundobject so the storefront can render the breakdown.GET /store/orders/:order_id/refund-payment-mappingsincludesrefundper mapping. - Registration: Add the module in
medusa-config.js(e.g.orderManagement.modules["refund-payment-mapping"]) and run migrations.
Deleted Records audit
A hard DELETE normally leaves no trace. The deleted_records_audit module installs a Postgres trigger on each monitored table that copies the full row into deleted_records_audit inside the same transaction as the delete, so rolled-back deletes leave no audit row and nothing can be deleted without being recorded.
Setup
- Register
orderManagement.modules["deleted-records-audit"]inmodules(see Installation & Setup). - Run
npx medusa db:migrate.
The migration (Migration20261008120000) creates the table, the om_audit_row_delete() function, and one om_ad_<table> trigger per table in src/modules/deleted-records-audit/audited-tables.ts (190 tables covering orders, carts, customers, catalog, pricing, payments, fulfillment, inventory, wallet, auth, store settings, engagement, notifications and system tables). Tables that don't exist in your database are skipped, so the migration is safe on smaller installs. Re-running it is idempotent; rolling it back removes every trigger, the function and the table.
What is captured
| Column | Meaning |
|---|---|
| table_name | Table the row was deleted from. Shown in the UI as a human entity name (e.g. order_line_item → "Order Item"). |
| record_id | The deleted row's id. null for link tables without an id column. |
| old_data | Full row as JSON, exactly as it was immediately before deletion. |
| occurred_at | When the delete ran. (Not deleted_at: that column is Medusa's soft-delete marker.) |
| deleted_by, source | Optional attribution—see below. |
Soft deletes (UPDATE … SET deleted_at = now()) are not captured; only real SQL DELETEs are.
Recording who deleted a record
The trigger reads two Postgres settings from the deleting transaction. If your code sets them, the UI shows who deleted the record and where the deletion came from; otherwise both show "Unknown".
BEGIN;
SET LOCAL app.audit_actor_id = 'user_01H...'; -- shown as "Deleted by"
SET LOCAL app.audit_source = 'admin'; -- admin | api | system | job | workflow | any label
DELETE FROM product WHERE id = 'prod_123';
COMMIT;SET LOCAL only lasts until the end of the transaction, so the values cannot leak into other requests on a pooled connection.
Admin UI
Deleted Records (/app/deleted-records-audit) is an investigation tool rather than a raw table viewer:
- Summary cards: total deleted, today, last 7 days, and the number of entity types affected (all-time, computed from real data).
- Search by record ID (substring, case-insensitive).
- Filters: a searchable, grouped Entity picker (pick a whole area such as "All Orders" or a single entity), a Date preset (any time, today, yesterday, last 7/30 days, custom range), plus Source and Deleted by filters, which appear once attribution data exists. Filters live in the URL, so investigations can be bookmarked or shared, and going back from a detail page restores the same filters, loaded rows and position.
- Detail page (
/app/deleted-records-audit/:id): entity and record ID, a clear historical snapshot notice, deletion time/actor/source, a Record summary of the important fields for common entities (orders, items, customers, products, payments, refunds, returns, carts, users, API keys, promotions, inventory, reviews…), the full snapshot in a collapsible JSON viewer with Copy JSON, and What you can do now guidance tailored to the kind of record.
There is deliberately no restore button: recreating records automatically is unsafe for linked commerce data. The guidance explains how to recreate a record when that's appropriate (and when not to, e.g. payments or wallet balances).
Sensitive data: passwords, hashes, tokens, secrets, API keys, card/account numbers, CVVs, OTP and recovery codes are masked (••••••••••••) in the summary, the JSON viewer and Copy JSON. The raw data in the database is unmasked, and the API routes are admin-only.
List API query parameters (GET /admin/deleted-records-audit)
| Param | Description |
|---|---|
| limit (≤ 100, default 50), offset | Pagination. Response: { audits, count, limit, offset }. |
| q | Record ID substring (% / _ are matched literally). |
| table_name / table_names | One table, or a comma-separated list (used for category filters). |
| date_from, date_to | ISO timestamps bounding occurred_at. |
| source | Exact source value; unknown matches rows with no source. |
| deleted_by | Substring match on deleted_by. |
GET /admin/deleted-records-audit/stats?today_start=<ISO> returns { stats: { total, today, last_7_days, tables_affected, sources, deleted_by } }. Pass the viewer's local midnight as today_start so "Today" matches their timezone.
Operational notes
- Every hard delete on a monitored table writes one extra row. High-churn tables (
cart_*,workflow_execution,notification, search index tables) can grow the audit table quickly, so plan retention or archiving for large stores. - To monitor another table, add it to
AUDITED_TABLE_NAMESand ship a new migration that callsbuildCreateAuditTriggerSql(table). Never adddeleted_records_audititself.
Return Orders Admin Panel
The plugin includes a dedicated section in the Medusa Admin Panel for managing customer return orders. This feature provides administrators with comprehensive tools to view, search, filter, and manage all return orders.
Features
- List View: View all return orders in a table format with key information
- Search: Search returns by return ID, order ID, or customer email
- Filtering: Filter returns by status (requested, received, requires_action, completed, canceled)
- Detail Pages: View detailed information for each return order including:
- Return information (ID, status, refund amount, reason, note)
- Related order information (order ID, customer, payment method used at checkout, totals)
- Return items with quantities
- Status history timeline
- Metadata
- Status Management: Update return status with validation and status history tracking
- Pagination: Load more returns with pagination support
Accessing Return Orders
Once the plugin is installed and configured, you can access the Return Orders section from the Admin Panel sidebar. The section appears as "Return Orders" with a return icon.
API Endpoints
The plugin provides admin API endpoints for return orders:
GET /admin/returns- List all return orders (filtering, search, pagination)GET /admin/returns/:id- Get detailed information for a specific returnPOST /admin/returns/:id/reject- Reject the return
Full request/response details are in the Standalone Return Flow section below.
Return Statuses
The plugin supports the following return statuses:
requested- Return has been requested by the customerreceived- Return items have been receivedrequires_action- Return requires manual interventioncompleted- Return has been completedcanceled- Return has been canceled
Status updates are tracked in the return's metadata with timestamps and admin user IDs.
One active return or exchange per item (Medusa v2)
Active standalone return = status ∈ {open, requested, partially_received} and no exchange_id.
Medusa v2 does not allow multiple active return/exchange requests for the same order item at the same time. Once an item is part of a return or a swap (exchange), that quantity is reserved until the request is completed or canceled. This plugin also enforces order-level mutual exclusion via order_rma_gate (see Eligibility and Validation).
To allow a new request, the first one must be closed or canceled:
| State | Action | Effect |
|-------|--------|--------|
| Swap (exchange) pending / not confirmed | POST /admin/swaps/{swap_id}/reject or POST /admin/swaps/{swap_id}/cancel | Releases reserved quantities; item becomes eligible again. |
| Return created but not received yet | POST /admin/returns/{return_id}/reject | Closes return flow; quantities unlocked. |
| Exchange already created in Medusa | POST /admin/swaps/{swap_id}/cancel | Cancels the exchange; same unlock behavior. |
Storefront gating: Before showing "Request Return" or "Request Exchange", check the order (e.g. GET /admin/orders/{id} or your store API) and block if the item has an active return, active swap (exchange), or claim in progress. Show status instead (e.g. "Return in review", "Exchange pending", "Request rejected — retry available").
Operational pattern: When a customer creates a swap, the exchange is created directly (no approval step). Use statuses such as rejected, cancelled, completed and only allow a new request when status is rejected or cancelled.
Guest Order Portal
The Guest Order Portal allows users who placed orders without an account to view their order status, cancel orders, reorder, initiate returns, and download invoices securely via an OTP (One-Time Password) system.
Security Features
- Strict Separation: Guest orders are strictly filtered by unique guest customer IDs. Registered account orders will never be exposed in the guest portal.
- Access Control: The portal uses short-lived JWT tokens issued upon successful OTP verification.
- Account Protection: Emails belonging to registered accounts are blocked from the guest OTP flow to prevent unauthorized access and encourage secure logins.
Complete API Documentation
For detailed API documentation, usage examples, error handling, and security best practices, see the Guest Order API Guide.
Store API Endpoints
The plugin provides the following store API endpoints for the Guest Order Portal:
Authentication
POST /store/otp/request- Request an OTP for an email or phone number.POST /store/otp/verify- Verify the OTP and receive a guest JWT token.
Guest Order Management
GET /store/guest-orders- List summary of orders for the verified guest identifier.GET /store/guest-orders/:id- Get full details for a specific guest order (includes items, shipping status, etc.).
Guest Order Actions
GET /store/guest-orders/:id- Get full details for a specific guest order (requires guest JWT).POST /store/guest-orders/:id/returns- Initiate a return request for a guest order. Optional body fields:refund_payment_id, or inlinerefund_payment: { type, detail_json }(e.g. UPI). COD guest returns require a refund destination.GET/POST /store/guest-orders/:id/payment-details- List / create refund destinations (UPI/bank/card) for the guest order's customer.PUT /store/guest-orders/:id/returns/:return_id/refund-payment- Link apayment_idto the return's refund mapping.
Guest prepaid refunds still default to the original checkout method when no destination is specified. Guest COD refunds store the provided UPI/bank/card on refund_payment_mapping so Admin Refund Payment can display it.
POST /store/guest-orders/:id/cancel- Cancel a guest order.POST /store/guest-orders/:id/reorder- Reorder a guest order (creates a new cart with the same items).GET /store/guest-orders/:id/swaps- List exchange requests for the guest order.POST /store/guest-orders/:id/swaps- Create an exchange request (return items + new items).GET /store/guest-orders/:id/swaps/:swap_id- Get one exchange request.POST /store/guest-orders/:id/swaps/:swap_id/cancel- Cancel an exchange request.
Note: All guest order endpoints require the guest JWT in the Authorization: Bearer <token> header or cookie.
Authenticated Customer Order APIs
Logged-in customers (storefront with customer auth) can use these endpoints without the guest portal:
POST /store/orders/cancel/:order_id- Cancel an order (customer must own the order).POST /store/orders/reorder/:order_id- Reorder (creates a new cart with the same items).GET /store/returns,POST /store/returns,GET /store/returns/:id,POST /store/returns/:id/cancel- List and create returns (filtered by customer).GET /store/swaps,POST /store/swaps,GET /store/swaps/:id,POST /store/swaps/:id/cancel- List and create exchanges (filtered by customer).
All require Authorization: Bearer <customer_token>.
Email Templates
The plugin supports custom HTML templates for order confirmation emails. Templates use variable replacement with {{variable_name}} syntax.
Creating Templates
Create HTML template files for email notifications. Place them in your project, for example:
your-project/
src/
templates/
emails/
order-confirmation.htmlExample Email Template (src/templates/emails/order-confirmation.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background-color: #4CAF50; color: white; padding: 20px; text-align: center; }
.content { padding: 20px; background-color: #ffffff; }
.order-info { background-color: #f5f5f5; padding: 15px; margin: 15px 0; border-radius: 5px; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Order Confirmation</h1>
</div>
<div class="content">
<div class="order-info">
<p><strong>Order ID:</strong> {{order_id}}</p>
<p><strong>Status:</strong> {{order_status}}</p>
<p><strong>Total:</strong> {{order_total}}</p>
<p><strong>Email:</strong> {{order_email}}</p>
<p><strong>Date:</strong> {{order_date}}</p>
</div>
<p>Thank you for your order!</p>
</div>
</div>
</body>
</html>Template Variables
The following variables are available in order confirmation email templates:
| Variable | Description | Example |
|----------|-------------|---------|
| {{order_id}} | Order ID | order_123 |
| {{order_status}} | Order status | pending |
| {{order_total}} | Order total amount | 99.99 |
| {{currency_code}} | Order currency (ISO 4217, lowercase, e.g. usd, inr) | inr |
| {{order_email}} | Customer email address | [email protected] |
| {{order_date}} | Order date/time (localized, long date + short time) | January 15, 2024 at 10:30 AM |
| {{order_items}} | Order items array (JSON stringified) | [{"title":"Product","quantity":1}] |
| {{shipping_address}} | Shipping address object (JSON stringified) | {"first_name":"John",...} |
| {{billing_address}} | Billing address object (JSON stringified) | {"first_name":"John",...} |
| {{is_registered}} | Whether the customer email has a registered account | true |
| {{claim_link}} | Link for registered users to claim their guest order | http://.../claim?order_id=... |
Status-Based Notifications
The plugin supports automatic notifications (email and SMS) based on order status changes. When an order reaches a configured status, the plugin will automatically send all configured notifications for that status.
📖 For detailed documentation, see the Notifications Guide
Features
- Multi-Channel Support: Send notifications via email and/or SMS
- Status-Based Configuration: Configure different notifications for different order statuses
- Multiple Notifications Per Status: Send multiple notifications for a single status change
- Template-Based: Use custom templates for each notification
- Automatic Triggering: Notifications are automatically triggered when order status changes
Configuration
Configure status-based notifications in your medusa-config.js:
{
resolve: "order-management",
options: {
// ... other options ...
notifications: {
enabled: true,
statusConfig: {
// Status name as key
"pending": [
{
template: "src/templates/emails/order-placed.html",
channel: "email"
},
{
template: "src/templates/sms/order-placed.txt",
channel: "sms"
}
],
"shipped": [
{
template: "src/templates/emails/order-shipped.html",
channel: "email"
}
],
"delivered": [
{
template: "src/templates/emails/order-delivered.html",
channel: "email"
},
{
template: "src/templates/sms/order-delivered.txt",
channel: "sms"
}
],
"canceled": [
{
template: "src/templates/emails/order-canceled.html",
channel: "email"
}
]
}
}
}
}Supported Channels
The notification system supports dynamic channel types, allowing you to configure any channel supported by your notification service:
- email: Sends email notifications to the customer's email address
- sms: Sends SMS notifications to the customer's phone number (from shipping address)
- push: Sends push notifications (browser/mobile notifications) to the customer's device
- Any custom channel: Configure any channel name supported by your notification service (e.g.,
whatsapp,slack,webhook, etc.)
The system automatically resolves recipients and sends notifications through the appropriate channel handler.
Triggered Events
The notification system listens to the following Medusa events:
order.updated- General order status changesorder.placed- When an order is first placedorder.shipment_created- When a shipment is createdorder.fulfillment_created- When fulfillment startsorder.completed- When an order is completedorder.canceled- When an order is canceleddelivery.created- When an order is delivered
Using Push Notifications
The plugin now supports push notifications (browser/mobile push) alongside email and SMS. Here's how to configure them:
{
resolve: "order-management",
options: {
// ... other options ...
notifications: {
enabled: true,
statusConfig: {
"shipped": [
{
template: "src/templates/emails/order-shipped.html",
channel: "email"
},
{
template: "src/templates/push/order-shipped.txt",
channel: "push" // Browser/mobile push notification
}
],
"delivered": [
{
template: "src/templates/emails/order-delivered.html",
channel: "email"
},
{
template: "src/templates/sms/order-delivered.txt",
channel: "sms"
},
{
template: "src/templates/push/order-delivered.txt",
channel: "push" // Browser/mobile push notification
}
]
}
}
}
}Push Notification Template Example (src/templates/push/order-shipped.txt):
📦 Your order {{order_id}} has been shipped! Track your package to stay updated.Important Notes:
- Push notifications require a configured notification service provider (e.g., FCM, OneSignal, Web Push API)
- The recipient resolver for push notifications uses the customer's email to identify the device token
- You may need to implement custom device token registration in your storefront
- Push notification templates should be concise (similar to SMS)
Creating Notification Templates
Note: The plugin includes example templates in src/templates/emails/ and src/templates/sms/ that you can use as a starting point.
Email Templates
Create HTML templates for email notifications. Templates use the same variable replacement syntax as order confirmation emails:
Example: Order Shipped Email (src/templates/emails/order-shipped.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background-color: #2196F3; color: white; padding: 20px; text-align: center; }
.content { padding: 20px; background-color: #ffffff; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Your Order Has Shipped!</h1>
</div>
<div class="content">
<p>Hi there,</p>
<p>Great news! Your order <strong>{{order_id}}</strong> has been shipped and is on its way to you.</p>
<p><strong>Order Total:</strong> {{order_total}}</p>
<p><strong>Shipped on:</strong> {{order_date}}</p>
<p>Thank you for your purchase!</p>
</div>
</div>
</body>
</html>SMS Templates
Create plain text templates for SMS notifications:
Example: Order Shipped SMS (src/templates/sms/order-shipped.txt)
Your order {{order_id}} has been shipped! Total: {{order_total}}. Thank you for your purchase.Available Template Variables
All notification templates have access to the same variables as order confirmation emails:
{{order_id}}- Order ID{{order_status}}- Current order status{{order_total}}- Order total amount{{order_email}}- Customer email address{{order_date}}- Order creation/update date{{order_items}}- Order items array (JSON stringified){{shipping_address}}- Shipping address object (JSON stringified){{billing_address}}- Billing address object (JSON stringified){{is_registered}}- Whether the customer has a registered account{{claim_link}}- Link for registered users to claim their order
Common Status Names
Common Medusa order statuses you can configure notifications for:
pending- Order placed, payment pendingawaiting- Awaiting fulfillmentfulfilled- Order fulfilledshipped- Order shippeddelivered- Order deliveredcompleted- Order completedcanceled- Order canceledrequires_action- Order requires action
Note: You can configure notifications for
