Redsys / Sermepa TPV Virtual payment provider plugin for MedusaJS v2
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.
npm install medusa-payment-redsys# oryarn add medusa-payment-redsys# orpnpm add medusa-payment-redsys
Add the following to your file:
REDSYS_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:
In your :
import { defineConfig } from "@medusajs/framework/config"export default defineConfig({modules: [{resolve: "@medusajs/medusa/payment",options: {providers: [{resolve: "medusa-payment-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,errorUrl: process.env.REDSYS_ERROR_URL,transactionType: "0", // "0" = immediate capture, "1" = pre-authorization},},],},},],})
Enable the Redsys provider in your Medusa admin panel under Settings > Regions and select Redsys as a payment provider.
The provider ID will be:
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
| string | Yes | — | Redsys HMAC-SHA256 secret key | |
| string | Yes | — | Redsys merchant code (FUC) | |
| string | No | Terminal number | ||
| string | No | or | ||
| string | No | — | Webhook URL for Redsys to POST transaction results | |
| string | No | — | URL to redirect after successful payment (URLOK) | |
| string | No | — | URL to redirect after failed payment (URLKO) | |
| string | No | = immediate capture, = pre-authorization |
This plugin's returns for sessions with status and . This is intentional for the redirect flow: the real authorization happens on Redsys TPV and is confirmed via webhook. Without this, would fail with a 400 error because Medusa requires the payment session to be authorized before completing the cart.
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.
Add Redsys to the payment info map and add a helper function:
// Inside paymentInfoMap, add:pp_redsys_redsys: {title: "Credit / Debit Card",icon: <CreditCard />,},// Add helper function:export const isRedsys = (providerId?: string) => {return providerId?.startsWith("pp_redsys_")}
Add a function. The standard does a (server-side), but Redsys needs to redirect the browser to the TPV instead. This function completes the cart, creates the order, but returns the result so the client can handle the TPV redirect:
export async function completeCartWithoutRedirect(cartId?: string) {const id = cartId || (await getCartId())if (!id) {throw new Error("No existing cart found when completing cart")}const headers = {...(await getAuthHeaders()),}const cartRes = await sdk.store.cart.complete(id, {}, headers).then(async (cartRes) => {const cartCacheTag = await getCacheTag("carts")revalidateTag(cartCacheTag)return cartRes}).catch(medusaError)if (cartRes?.type === "order") {const orderCacheTag = await getCacheTag("orders")revalidateTag(orderCacheTag)removeCartId()}return cartRes}
Add a component that:
// Add import:import { isManual, isRedsys, isStripeLike } from "@lib/constants"import { completeCartWithoutRedirect, placeOrder } from "@lib/data/cart"// Add case in PaymentButton's switch:case isRedsys(paymentSession?.provider_id):return (<RedsysPaymentButtonnotReady={notReady}cart={cart}data-testid={dataTestId}/>)// Add the component:const RedsysPaymentButton = ({cart,notReady,"data-testid": dataTestId,}: {cart: HttpTypes.StoreCartnotReady: boolean"data-testid"?: string}) => {const [submitting, setSubmitting] = useState(false)const [errorMessage, setErrorMessage] = useState<string | null>(null)const handlePayment = async () => {setSubmitting(true)const paymentSession = cart.payment_collection?.payment_sessions?.find((s) => s.status === "pending" && isRedsys(s.provider_id))const redsysData = paymentSession?.data as Record<string, string> | undefinedif (!redsysData?.formUrl || !redsysData?.merchantParams || !redsysData?.signature) {setErrorMessage("No se pudieron obtener los datos de pago de Redsys")setSubmitting(false)return}const cartRes = await completeCartWithoutRedirect().catch((err) => {setErrorMessage(err.message)setSubmitting(false)return null})if (!cartRes || cartRes.type !== "order") {setErrorMessage(cartRes ? "Error al crear el pedido" : "")setSubmitting(false)return}const form = document.createElement("form")form.method = "POST"form.action = redsysData.formUrlconst fields: Record<string, string> = {Ds_SignatureVersion: redsysData.signatureVersion,Ds_MerchantParameters: redsysData.merchantParams,Ds_Signature: redsysData.signature,}Object.entries(fields).forEach(([name, value]) => {const input = document.createElement("input")input.type = "hidden"input.name = nameinput.value = valueform.appendChild(input)})document.body.appendChild(form)form.submit()}return (<><Buttondisabled={notReady || submitting}isLoading={submitting}onClick={handlePayment}size="large"data-testid={dataTestId}>Place order</Button><ErrorMessageerror={errorMessage}data-testid="redsys-payment-error-message"/></>)}
Create the page Redsys redirects to after payment. It reads the query param and redirects to the order confirmation page:
import { retrieveOrder } from "@lib/data/orders"import { Metadata } from "next"import { redirect } from "next/navigation"export const metadata: Metadata = {title: "Resultado del pago",description: "Resultado de la operación con Redsys",}type Props = {searchParams: Promise<{ [key: string]: string | undefined }>}export default async function RedsysCallbackPage(props: Props) {const searchParams = await props.searchParamsconst isError = searchParams.error === "1"const orderId = searchParams.orderIdif (isError) {return (<div className="flex flex-col items-center justify-center min-h-[50vh] gap-4 p-8"><h1 className="text-2xl font-bold text-red-600">Pago no completado</h1><p className="text-gray-600">La operación no se ha completado correctamente.</p><a href="/" className="mt-4 px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">Volver a la tienda</a></div>)}if (orderId) {try {const order = await retrieveOrder(orderId)if (order) {const countryCode = order.shipping_address?.country_code?.toLowerCase() || "dk"return redirect(`/${countryCode}/order/${orderId}/confirmed`)}} catch {// Order not found, show success anyway}}return (<div className="flex flex-col items-center justify-center min-h-[50vh] gap-4 p-8"><h1 className="text-2xl font-bold text-green-600">Pago procesado</h1><p className="text-gray-600">Tu pago ha sido procesado correctamente.</p><a href="/" className="mt-4 px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">Volver a la tienda</a></div>)}
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 is not redirected. Add this early in the function:
// Redsys callback URL — bypass region redirectif (request.nextUrl.pathname.startsWith("/checkout/redsys-callback")) {return NextResponse.next()}
Ensure your storefront domain is allowed in CORS:
projectConfig: {http: {storeCors: "http://localhost:8000,https://your-store.com",},}
The payment session field returned by :
{orderId: "1234ABCD5678",amount: "2550",currency: "978",status: "pending",transactionType: "0",merchantParams: "base64...", // Base64-encoded merchant parameterssignature: "hmac...", // HMAC-SHA256 signaturesignatureVersion: "HMAC_SHA256_V1",formUrl: "https://sis-t.redsys.es:25443/sis/realizarPago"}
These fields are used in step 3 to build the auto-submitting redirect form.
Medusa automatically exposes a webhook endpoint for the Redsys provider at:
For local development with sandbox, you must expose your backend to the internet (e.g., via ngrok) so Redsys can reach the webhook. Set to the ngrok URL.
Important: Redsys sends the notification to but the signature verification and payment status update happens through the Medusa webhook handler — make sure points to the same endpoint or forward notifications accordingly.
| 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 |
| Code | Type | Description |
|---|---|---|
| Payment | Authorization + immediate capture (default) | |
| Pre-authorization | Reserve funds only | |
| Confirmation | Capture pre-authorized funds | |
| Refund | Full or partial refund | |
| Cancellation | Cancel/void a transaction |
The plugin includes built-in numeric currency codes for all major currencies. If your currency is not listed, it defaults to EUR (). See for the full list.
# Install dependenciesnpm install# Buildnpm run build# Run testsnpm test# Watch mode (for local plugin development)npm run dev
# From your plugin directorynpm run dev# In your Medusa project directory:npx medusa plugin:add ../path-to/medusa-payment-redsys
MIT — see LICENSE file for details.
For issues and questions, please open an issue on GitHub.