Redsys
Redsys card and Bizum payments (Spain)
@jsm406/medusa-plugin-redsys
Redsys / Sermepa TPV Virtual payment provider plugin for MedusaJS v2.
This plugin enables payment processing through Redsys' hosted payment page (TPV Virtual) via redirect flow. Customers are redirected to the Redsys secure payment page to complete their transaction.
Production-proven: This plugin is derived from a live production Medusa store processing real Redsys payments.
Features
- Redsys hosted payment page / TPV Virtual redirect flow
- Bizum mobile payment support via Redsys TPV
- Sandbox and production environments
- One-step payment (immediate capture) and two-step payment (pre-authorization + capture)
- Full and partial refunds via Redsys API
- Payment cancellation
- Webhook handling with HMAC-SHA256 signature verification
- Secure webhook correlation: a payment is only authorized after a valid, fully matching webhook (order, session, amount, currency, provider, merchant, terminal and transaction type)
- Spanish error messages for Redsys response codes
- Zero PCI scope — card data is handled by Redsys' secure page
Prerequisites
- MedusaJS v2.22.3 or later
- Node.js v22.22.0 or later
- A Redsys merchant account (or sandbox test credentials)
- Copy to clipboard
redsys-easyv5.3.2+ (installed automatically as a dependency)
Installation
12345npm install @jsm406/medusa-plugin-redsys# oryarn add @jsm406/medusa-plugin-redsys# orpnpm add @jsm406/medusa-plugin-redsys
Configuration
Environment Variables
Add the following to your Copy to clipboard.env file:
1234567REDSYS_SECRET_KEY=sq7Hj....REDSYS_MERCHANT_CODE=999008881REDSYS_TERMINAL=001REDSYS_ENVIRONMENT=sandboxREDSYS_NOTIFICATION_URL=https://your-api.com/hooks/payment/redsys_redsysREDSYS_SUCCESS_URL=https://your-store.com/checkout/redsys-callbackREDSYS_ERROR_URL=https://your-store.com/checkout/redsys-callback?error=1
For sandbox testing, use the following test credentials from Redsys:
1234Merchant Code: 999008881Terminal: 001Secret Key: sq7Hj.......Environment: sandbox
Medusa Configuration
In your Copy to clipboardmedusa-config.ts:
1234567891011121314151617181920import { defineConfig } from "@medusajs/framework/config"export default defineConfig({modules: [{resolve: "@medusajs/medusa/payment",options: {providers: [{resolve: "@jsm406/medusa-plugin-redsys/providers/redsys",id: "redsys",options: {secretKey: process.env.REDSYS_SECRET_KEY,merchantCode: process.env.REDSYS_MERCHANT_CODE,terminal: process.env.REDSYS_TERMINAL || "001",environment:process.env.REDSYS_ENVIRONMENT || "sandbox",notificationUrl:process.env.REDSYS_NOTIFICATION_URL,successUrl: process.env.REDSYS_SUCCESS_URL,
Enable in Region
Enable the Redsys provider(s) in your Medusa admin panel under Settings > Regions:
- Credit/Debit Card: Select Redsys as a payment provider
- Provider ID: Copy to clipboard
pp_redsys_redsys
- Provider ID: Copy to clipboard
- Bizum: Select Redsys Bizum as a payment provider
- Provider ID: Copy to clipboard
pp_redsys-bizum_redsys-bizum
- Provider ID: Copy to clipboard
You can enable one or both providers depending on which payment methods you want to offer.
Options
Option Type Required Default Description Copy to clipboardsecretKey string Yes — Redsys HMAC-SHA256 secret key Copy to clipboardmerchantCode string Yes — Redsys merchant code (FUC) Copy to clipboardterminal string No Copy to clipboard"001" Terminal number Copy to clipboardenvironment string No Copy to clipboard"sandbox" Copy to clipboard"sandbox" or Copy to clipboard"production" Copy to clipboardnotificationUrl string No — Webhook URL for Redsys to POST transaction results Copy to clipboardsuccessUrl string No — URL to redirect after successful payment (URLOK) Copy to clipboarderrorUrl string No — URL to redirect after failed payment (URLKO) Copy to clipboardtransactionType string No Copy to clipboard"0" Copy to clipboard"0" = immediate capture, Copy to clipboard"1" = pre-authorization
Payment Flow
- Customer selects Redsys as payment method → Medusa creates a Payment Session (Copy to clipboard
payses_...) - Copy to clipboard
initiatePayment()generates a secure Redsys Copy to clipboardorderId, stores a payment reference (Copy to clipboardorderId↔ payment session, amount, currency, merchant, terminal, transaction type) in the payment session Copy to clipboarddata, and creates a signed redirect form - Customer clicks "Place Order" → the storefront saves Copy to clipboard
{ cartId, countryCode }in Copy to clipboardsessionStorageand auto-submits the redirect form to Redsys TPV. Copy to clipboardcart.complete()is NOT called here — no order is created before the payment exists - Customer completes payment on the Redsys hosted payment page
- Redsys sends a webhook notification to Copy to clipboard
{backendUrl}/hooks/payment/redsys_redsys - Copy to clipboard
getWebhookActionAndData()verifies the HMAC signature and validates the order, session, amount, currency, provider, merchant, terminal and transaction type against the stored reference, then marks it as confirmed - Medusa authorizes/captures the payment and completes the cart server-side, creating the order
- Redsys redirects the customer's browser to Copy to clipboard
successUrlor Copy to clipboarderrorUrlwith the Redsys order ID as a query parameter - Storefront callback page reads the saved Copy to clipboard
cartId, retries Copy to clipboardcart.complete()if needed, and redirects to the order confirmation page
Security: authorizePayment Behavior
A payment session is only authorized after a valid HMAC-confirmed webhook that fully matches the stored payment reference. Copy to clipboardauthorizePayment returns Copy to clipboardPENDING for any session whose reference is missing, not confirmed, or mismatched (amount, currency, session, provider, merchant or transaction type). It never trusts the stored Copy to clipboardstatus field, so a Copy to clipboard"pending" — or even a forged Copy to clipboard"authorized" — status can never authorize a payment on its own.
ID Mapping (Redsys → Medusa)
The plugin generates a 12-character alphanumeric Copy to clipboardorderId (e.g. Copy to clipboard97727XYIWRRF) used as Redsys' merchant order reference. When the cart is completed after payment, Medusa generates its own order ID (e.g. Copy to clipboardorder_01KR3B4X...). These are different IDs.
The callback URL from Redsys only contains the Redsys order ID, not the Medusa order ID. To bridge this gap, the storefront stores the mapping Copy to clipboardredsys_cart_{redsysOrderId} → Copy to clipboard{ cartId, countryCode } in Copy to clipboardsessionStorage before redirecting to the TPV. The callback page uses the Copy to clipboardcartId to retrieve/complete the order and redirect to the correct confirmation page.
Storefront Integration
Redsys is a redirect-based payment method (no card input in your storefront — the customer enters card data on Redsys' secure TPV). You must adapt your Medusa Next.js storefront with the changes below.
Security: starting with v1.1.1 the storefront must not call Copy to clipboardcart.complete() before redirecting to Redsys. Doing so would fail anyway (the payment is not authorized yet) and previously created unpaid orders. The Redsys webhook completes the cart after the payment is confirmed.1. Copy to clipboardsrc/lib/constants.tsx — Register the payment methods
Add Redsys and Bizum to the payment info map and add helper functions:
123456789101112131415161718// Inside paymentInfoMap, add:pp_redsys_redsys: {title: "Credit / Debit Card",icon: <CreditCard />,},"pp_redsys-bizum_redsys-bizum": {title: "Bizum",icon: <Smartphone />,},// Add helper functions:export const isRedsys = (providerId?: string) => {return providerId?.startsWith("pp_redsys_redsys") && !providerId?.includes("bizum")}export const isRedsysBizum = (providerId?: string) => {return providerId?.startsWith("pp_redsys-bizum")}
2. Payment buttons and callback page
The full copyable implementation lives in Copy to clipboardexamples/storefront-redsys.md. The two critical changes vs. older versions:
- The payment buttons no longer call Copy to clipboard
cart.complete()before redirecting to Redsys. They only store Copy to clipboard{ cartId, countryCode }in Copy to clipboardsessionStorageunder Copy to clipboardredsys_cart_{orderId}and submit the redirect form. The HMAC-confirmed webhook completes the cart server-side. - The callback page reads Copy to clipboard
orderIdfrom the URL, recovers the Copy to clipboardcartId, and retries Copy to clipboardcart.complete()with exponential backoff to bridge the race between the browser redirect and the webhook arrival.
3. Copy to clipboardsrc/middleware.ts — Bypass region redirect
If your storefront uses middleware to enforce region/country code prefixes in URLs (as the default Medusa Next.js storefront does), add a bypass so Copy to clipboard/checkout/redsys-callback is not redirected. Add this early in the Copy to clipboardmiddleware function:
1234// Redsys callback URL — bypass region redirectif (request.nextUrl.pathname.startsWith("/checkout/redsys-callback")) {return NextResponse.next()}
4. Copy to clipboardmedusa-config.ts — CORS
Ensure your storefront domain is allowed in CORS:
12345projectConfig: {http: {storeCors: "http://localhost:8000,https://your-store.com",},}
Session Data Reference
The payment session Copy to clipboarddata field returned by Copy to clipboardinitiatePayment:
12345678910111213{orderId: "1234ABCD5678", // Redsys merchant order (12 chars, ^\d{4}[A-Z0-9]{8}$)medusaSessionId: "payses_...", // Real Medusa payment session ID — never the Redsys ordercartId: "cart_...", // Optionalamount: "2550", // Smallest currency unit (cents)currency: "978", // Redsys numeric currency codestatus: "pending",transactionType: "0",merchantParams: "base64...", // Base64-encoded merchant parameterssignature: "hmac...", // HMAC-SHA256 signaturesignatureVersion: "HMAC_SHA256_V1", // Version identifier returned by redsys-easyformUrl: "https://sis-t.redsys.es:25443/sis/realizarPago"}
Note: The Copy to clipboardsignatureVersion: "HMAC_SHA256_V1"identifier in the callback URL is the value returned by the Copy to clipboardredsys-easylibrary and is normal. This does not indicate a problem — the actual signature computation follows the Redsys v4.1 specification.
Webhook
Medusa automatically exposes webhook endpoints for the Redsys providers at:
12/hooks/payment/redsys_redsys (Card payments)/hooks/payment/redsys-bizum_redsys-bizum (Bizum payments)
For local development with sandbox, you must expose your backend to the internet (e.g., via ngrok) so Redsys can reach the webhook. Set Copy to clipboardnotificationUrl to the ngrok URL.
Important: Redsys sends the notification to Copy to clipboardnotificationUrl but the signature verification and payment status update happens through the Medusa webhook handler — make sure Copy to clipboardnotificationUrl points to the same endpoint or forward notifications accordingly.
Persistence: payment session data
Since v1.1.3 the plugin stores everything it needs in the Medusa Payment Session Copy to clipboarddata field, so it needs no direct database access and no extra table or migration:
Field Purpose Copy to clipboardorderId Redsys order ID generated by the plugin Copy to clipboardmedusaSessionId Real Medusa payment session (Copy to clipboardpayses_...) Copy to clipboardcartId Medusa cart, if available Copy to clipboardamount, Copy to clipboardcurrency, Copy to clipboardcurrencyCode Expected amount/currency Copy to clipboardmerchantCode (provider option), Copy to clipboardterminal, Copy to clipboardtransactionType Expected merchant/terminal/type Copy to clipboardwebhookConfirmed Only set to Copy to clipboardtrue by a validated webhook Copy to clipboardresponseCode, Copy to clipboardauthCode Set by the validated webhook
A webhook can only confirm a payment that the plugin itself created in Copy to clipboardinitiatePayment/Copy to clipboardupdatePayment, and only if every field matches.
Test Cards (Sandbox)
Card Payments
Card Number Brand Behavior 4548810000000003 VISA 3DS v2 approved 5576441563045037 Mastercard 3DS v2 approved 4548814479727229 VISA 3DS frictionless 4548817212493017 VISA 3DS challenge Any + CVV 999 Any Payment declined
Bizum (Sandbox)
Important: In sandbox, Bizum transactions cannot exceed 10€. Use a discount coupon or low-price test product.
Field Value Phone number Copy to clipboard700 000 000 PIN Copy to clipboard1234 SMS code Copy to clipboard123456
Test scenarios by amount:
Amount Result < 5€ Payment approved 5€ - 10€ Payment approved 10€ - 15€ Payment declined (exceeds sandbox limit) > 15€ Payment declined (no Bizum user)
Transaction Types
Code Type Description Copy to clipboard"0" Payment Authorization + immediate capture (default) Copy to clipboard"1" Pre-authorization Reserve funds only Copy to clipboard"2" Confirmation Capture pre-authorized funds Copy to clipboard"3" Refund Full or partial refund Copy to clipboard"9" Cancellation Cancel/void a transaction
Security
- Never log PAN, CVV, or the secret key. The provider strips sensitive fields from log output.
- Always validate signatures server-side. Copy to clipboard
getWebhookActionAndData()uses Copy to clipboardredsys-easy's Copy to clipboardprocessRestNotification(), which verifies the HMAC signature before anything else. - The webhook is the only source of truth. A payment is authorized only when a valid webhook confirms a payment the plugin previously recorded, and the amount, currency, provider, merchant, terminal and transaction type all match. Reusing an old Copy to clipboard
orderIdis impossible because each payment session stores its own order data. - Use HTTPS for all communication with Redsys.
- Do not trust client-side payment data. The webhook with signature verification is the source of truth.
- Amounts are normalized. Copy to clipboard
Ds_Amountis received in the smallest unit (e.g. Copy to clipboard"2550") and converted back to the main unit (Copy to clipboard25.5) before being passed to Medusa. - Unsupported currencies fail closed. An unknown currency throws instead of silently charging in EUR.
- The redirect flow keeps you out of PCI scope — card data is handled by Redsys' secure page.
Upgrading from < 1.1.1
Sessions created before v1.1.1 do not carry a Copy to clipboardmedusaSessionId and have no payment reference, so they will not be authorized (fail-closed). Customers in the middle of a checkout will need to refresh / recreate their payment session. This is intentional: it is safer to reject than to authorize an unverified payment.
Currency Support
The plugin includes built-in numeric currency codes for all major currencies (see Copy to clipboardsrc/types.ts for the full list). Unsupported currencies are rejected with an error rather than silently falling back to EUR.
Development
1234567891011# Install dependenciesnpm install# Buildnpm run build# Run testsnpm test# Watch mode (for local plugin development)npm run dev
Local Testing with a Medusa Project
12345# From your plugin directorynpm run dev# In your Medusa project directory:npx medusa plugin:add ../path-to/@jsm406/medusa-plugin-redsys
Acknowledgements
- TomatitoCodes — for discovering and responsibly reporting the vulnerability in the webhook/HMAC authorization flow. His finding drove the security hardening released in v1.1.1–v1.1.4: a payment session is no longer authorized from client-controlled session state and only an HMAC-verified, fully matching Redsys webhook can confirm it.
License
MIT — see LICENSE file for details.
Version History
v1.2.2 (2026-11-04)
- Updated: MedusaJS dependencies to v2.22.3 (Copy to clipboard
@medusajs/framework, Copy to clipboard@medusajs/cli, Copy to clipboard@medusajs/medusa, Copy to clipboard@medusajs/types) - Verified: No source changes required — the plugin builds, typechecks and passes its test suite against Medusa v2.22.3
v1.2.1 (2026-11-02)
- Updated: MedusaJS dependencies to v2.22.2 (Copy to clipboard
@medusajs/framework, Copy to clipboard@medusajs/cli, Copy to clipboard@medusajs/medusa, Copy to clipboard@medusajs/types) - Verified: No source changes required — the plugin builds, typechecks and passes its test suite against Medusa v2.22.2
v1.2.0 (2026-10-25)
- Updated: MedusaJS dependencies to v2.22.1 (Copy to clipboard
@medusajs/framework, Copy to clipboard@medusajs/cli, Copy to clipboard@medusajs/medusa, Copy to clipboard@medusajs/types) - Updated: Node.js engine requirement to Copy to clipboard
>=22.22.0(required by Medusa v2.22) - Updated: Copy to clipboard
redsys-easyto v5.3.2 and dev tooling (Copy to clipboardtypescript, Copy to clipboardvitest, Copy to clipboard@swc/core, Copy to clipboard@types/node) - Docs: Added acknowledgement for TomatitoCodes and documented the current Payment Session persistence model
v1.1.2 (2026-08-31)
- Fixed: Install-time Copy to clipboard
ERESOLVEpeer dependency conflict — removed Copy to clipboard@medusajs/medusafrom Copy to clipboardpeerDependencies(aligned with the official Copy to clipboard@medusajs/payment-stripeconvention; only Copy to clipboard@medusajs/frameworkis required).
v1.1.1 (2026-08-31) — Security release
- SECURITY: Never authorize a Copy to clipboard
pendingRedsys payment before an HMAC-confirmed webhook - SECURITY: Correlate webhooks with the real Medusa payment session ID (Copy to clipboard
payses_...) instead of an artificial Copy to clipboardredsys_*ID - SECURITY: Validate order, amount, currency, provider, merchant, terminal and transaction type before confirming a webhook
- SECURITY: Persist a payment reference (Copy to clipboard
redsys_payment_reference) for every initiated payment, preventing reuse of previously confirmed Copy to clipboardorderIds - SECURITY: Generate Redsys order IDs using cryptographic randomness instead of Copy to clipboard
Math.random() - SECURITY: Reject unsupported currencies instead of silently falling back to EUR
- FIX: Normalize webhook amounts (Copy to clipboard
Ds_Amountin cents → main unit) before passing them to Medusa - FIX: Return Copy to clipboard
AUTHORIZEDfor preauthorizations and Copy to clipboardSUCCESSFULfor immediate captures in webhook actions - FIX: Tighten Redsys response-code validation (4-digit payment codes 0000-0099, confirmation/refund 900, cancellation 400)
- FIX: Make Copy to clipboard
updatePayment()generate a fresh Copy to clipboardorderIdand keep MerchantData at fixed 3-position layout - FIX: Storefront flow no longer creates the order before the payment (see Copy to clipboard
examples/storefront-redsys.md)
v1.1.0 (2026-06-16)
- Added: Bizum payment method support via Redsys TPV
- New Copy to clipboard
redsys-bizumprovider with Copy to clipboardDS_MERCHANT_PAYMETHODS: "z"parameter - Full lifecycle support: initiate, authorize, capture, cancel, refund, webhook
- Same configuration as card provider (can share credentials)
- Separate webhook endpoint at Copy to clipboard
/hooks/payment/redsys-bizum_redsys-bizum
v1.0.12 (2026-05-13)
- Fixed: Response code validation for payment authorization (codes 0-99), refunds/confirmations (code 900), cancellations (code 400)
- Note: The Copy to clipboard
signatureVersion: "HMAC_SHA256_V1"in the callback URL is normal - it's the identifier returned by the redsys-es library. The actual HMAC computation follows Redsys v4.1 specification.
v1.0.0 (2025-05-05)
- Initial release
Support
For issues and questions, please open an issue on GitHub.
