Overview
Icon for Redsys

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 clipboardredsys-easy v5.3.2+ (installed automatically as a dependency)

Installation

npm install @jsm406/medusa-plugin-redsys
# or
yarn add @jsm406/medusa-plugin-redsys
# or
pnpm add @jsm406/medusa-plugin-redsys

Configuration

Environment Variables

Add the following to your Copy to clipboard.env file:

REDSYS_SECRET_KEY=sq7Hj....
REDSYS_MERCHANT_CODE=999008881
REDSYS_TERMINAL=001
REDSYS_ENVIRONMENT=sandbox
REDSYS_NOTIFICATION_URL=https://your-api.com/hooks/payment/redsys_redsys
REDSYS_SUCCESS_URL=https://your-store.com/checkout/redsys-callback
REDSYS_ERROR_URL=https://your-store.com/checkout/redsys-callback?error=1

For sandbox testing, use the following test credentials from Redsys:

Merchant Code: 999008881
Terminal: 001
Secret Key: sq7Hj.......
Environment: sandbox

Medusa Configuration

In your Copy to clipboardmedusa-config.ts:

import { 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 clipboardpp_redsys_redsys
  • Bizum: Select Redsys Bizum as a payment provider
    • Provider ID: Copy to clipboardpp_redsys-bizum_redsys-bizum

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

  1. Customer selects Redsys as payment method → Medusa creates a Payment Session (Copy to clipboardpayses_...)
  2. Copy to clipboardinitiatePayment() 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
  3. Customer clicks "Place Order" → the storefront saves Copy to clipboard{ cartId, countryCode } in Copy to clipboardsessionStorage and auto-submits the redirect form to Redsys TPV. Copy to clipboardcart.complete() is NOT called here — no order is created before the payment exists
  4. Customer completes payment on the Redsys hosted payment page
  5. Redsys sends a webhook notification to Copy to clipboard{backendUrl}/hooks/payment/redsys_redsys
  6. Copy to clipboardgetWebhookActionAndData() 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
  7. Medusa authorizes/captures the payment and completes the cart server-side, creating the order
  8. Redsys redirects the customer's browser to Copy to clipboardsuccessUrl or Copy to clipboarderrorUrl with the Redsys order ID as a query parameter
  9. Storefront callback page reads the saved Copy to clipboardcartId, 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:

// 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 clipboardcart.complete() before redirecting to Redsys. They only store Copy to clipboard{ cartId, countryCode } in Copy to clipboardsessionStorage under 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 clipboardorderId from 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:

// Redsys callback URL — bypass region redirect
if (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:

projectConfig: {
http: {
storeCors: "http://localhost:8000,https://your-store.com",
},
}

Session Data Reference

The payment session Copy to clipboarddata field returned by Copy to clipboardinitiatePayment:

{
orderId: "1234ABCD5678", // Redsys merchant order (12 chars, ^\d{4}[A-Z0-9]{8}$)
medusaSessionId: "payses_...", // Real Medusa payment session ID — never the Redsys order
cartId: "cart_...", // Optional
amount: "2550", // Smallest currency unit (cents)
currency: "978", // Redsys numeric currency code
status: "pending",
transactionType: "0",
merchantParams: "base64...", // Base64-encoded merchant parameters
signature: "hmac...", // HMAC-SHA256 signature
signatureVersion: "HMAC_SHA256_V1", // Version identifier returned by redsys-easy
formUrl: "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-easy library 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:

/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 clipboardgetWebhookActionAndData() 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 clipboardorderId is 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 clipboardDs_Amount is 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

# Install dependencies
npm install
# Build
npm run build
# Run tests
npm test
# Watch mode (for local plugin development)
npm run dev

Local Testing with a Medusa Project

# From your plugin directory
npm 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 clipboardredsys-easy to 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 clipboardERESOLVE peer dependency conflict — removed Copy to clipboard@medusajs/medusa from Copy to clipboardpeerDependencies (aligned with the official Copy to clipboard@medusajs/payment-stripe convention; only Copy to clipboard@medusajs/framework is required).

v1.1.1 (2026-08-31) — Security release

  • SECURITY: Never authorize a Copy to clipboardpending Redsys payment before an HMAC-confirmed webhook
  • SECURITY: Correlate webhooks with the real Medusa payment session ID (Copy to clipboardpayses_...) 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 clipboardredsys_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 clipboardMath.random()
  • SECURITY: Reject unsupported currencies instead of silently falling back to EUR
  • FIX: Normalize webhook amounts (Copy to clipboardDs_Amount in cents → main unit) before passing them to Medusa
  • FIX: Return Copy to clipboardAUTHORIZED for preauthorizations and Copy to clipboardSUCCESSFUL for 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 clipboardupdatePayment() generate a fresh Copy to clipboardorderId and keep MerchantData at fixed 3-position layout
  • FIX: Storefront flow no longer creates the order before the payment (see Copy to clipboardexamples/storefront-redsys.md)

v1.1.0 (2026-06-16)

  • Added: Bizum payment method support via Redsys TPV
  • New Copy to clipboardredsys-bizum provider 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 clipboardsignatureVersion: "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.

You may also like

Browse all integrations

Build your own

Develop your own custom integration

Build your own integration with our API to speed up your processes. Make your integration available via npm for it to be shared in our Library with the broader Medusa community.

gift card interface

Ready to build your custom commerce setup?