Adyen Checkout: Sessions flow, Drop-in and HMAC webhooks
Accept payments with Adyen's sessions flow: create a session on your server, render Drop-in with Adyen Web, handle redirects, confirm the outcome from HMAC-verified AUTHORISATION webhooks and refund by PSP reference.
- Provider
- Adyen
- Level
- Intermediate
- Stacks
- Node.js (Express), Java (Spring), React
- Code maturity
- Sandbox-ready
- Last verified
- 25 Nov 2026
Introduction
Adyen is a global payments platform used mostly by mid-size and enterprise merchants. Its recommended online integration is the sessions flow: your server makes one /sessions call, and Adyen's front-end library (Drop-in) handles payment-method selection, 3-D Secure and redirects.
This guide covers the full loop on Adyen's test environment: create a session, mount Drop-in, handle redirects, confirm the result from an HMAC-verified webhook, and refund.
What the sessions flow does
- Server:
POST https://checkout-test.adyen.com/v71/sessions→ returnsidandsessionData. - Browser:
AdyenCheckout({ session: { id, sessionData }, ... })+new Dropin(checkout).mount('#dropin'). - Shopper pays; Drop-in calls
onPaymentCompletedoronPaymentFailedwith aresultCode. - Adyen sends an AUTHORISATION webhook to your server — this is the outcome you fulfil from.
Tip: Adyen's sessions example uses Checkout API v71 while its refund example uses v72. The official libraries pin a version for you; if you call the REST API directly, use one version consistently and check the API Explorer for the latest.
Countries and currencies
Adyen operates in many countries and supports many currencies and local methods, but which ones you get depends on your merchant account setup and contract. Confirm coverage with Adyen; this guide makes no country claims.
Payment methods
Drop-in shows every method enabled on your merchant account that matches countryCode, amount and currency — cards plus wallets and local methods (for example iDEAL in the Netherlands). Enable methods in the Customer Area.
When to use it
- You need many payment methods across many countries behind one integration.
- You want Adyen to handle 3-D Secure and redirect methods for you.
- You are a business that fits Adyen's onboarding (typically larger volumes).
When not to use it
- Very small businesses or individuals — Adyen onboarding is aimed at established companies.
- You need full control over each API call (use Adyen's advanced flow instead:
/paymentMethods,/payments,/payments/details).
Typical scenarios
- An e-commerce site selling in several European countries that needs cards plus local methods.
- A marketplace or platform already on Adyen that adds a web checkout.
Registration
Sign up for an Adyen test account. In the Customer Area you get a company account and a merchant account (its name is the merchantAccount value in API calls).
Test environment
- Test Checkout API base:
https://checkout-test.adyen.com. - Libraries:
environment: EnvironmentEnum.TEST(Node) /Environment.TEST(Java); Adyen Web:environment: 'test'. - Live requires your account-specific
liveEndpointUrlPrefixin the library config.
Credentials
- API key (server only) from an API credential in the Customer Area.
- Client key (public,
test_...) from the same credential, with your site's origin added to its allowed origins. - HMAC key (hex string) generated when you configure a Standard webhook.
- Merchant account name.
Security: API key and HMAC key are secrets. Keep them in environment variables; only the client key goes to the browser.
Environment configuration
A .env.example with placeholders only:
ADYEN_ENV=test # test | live
ADYEN_API_KEY=replace-me # server only
ADYEN_MERCHANT_ACCOUNT=replace-me
ADYEN_HMAC_KEY=replace-me # hex string from the webhook settings
ADYEN_LIVE_URL_PREFIX= # live only
APP_BASE_URL=http://localhost:3000
# Front end (public)
REACT_APP_ADYEN_CLIENT_KEY=test_replace-meAuthentication
Server-to-server calls authenticate with the API key in the X-API-Key header; the official libraries add it from Config({ apiKey }). The browser authenticates with the client key, which is only usable from allowed origins.
Backend: create a session
Create the session from your order record: amount in minor units (1000 = 10.00 EUR), a unique reference, and a returnUrl for redirect methods. Pass an idempotency key so a retried request does not create a duplicate.
import express from "express";
import { Client, Config, EnvironmentEnum, CheckoutAPI } from "@adyen/api-library";
const config = new Config({
apiKey: process.env.ADYEN_API_KEY,
environment: process.env.ADYEN_ENV === "live" ? EnvironmentEnum.LIVE : EnvironmentEnum.TEST,
liveEndpointUrlPrefix: process.env.ADYEN_LIVE_URL_PREFIX || undefined,
});
const checkout = new CheckoutAPI(new Client(config));
const app = express();
// The webhook route (see Webhooks) is registered before express.json() too.
app.use(express.json());
app.post("/api/sessions", async (req, res) => {
const order = await db.orders.findById(req.body.orderId); // your DB
if (!order || order.status !== "pending") return res.status(400).end();
const session = await checkout.PaymentsApi.sessions(
{
merchantAccount: process.env.ADYEN_MERCHANT_ACCOUNT,
amount: { value: order.amountMinor, currency: order.currency },
reference: order.id,
countryCode: order.countryCode,
returnUrl: `${process.env.APP_BASE_URL}/checkout/return?orderId=${order.id}`,
},
{ idempotencyKey: `session-${order.id}-${order.attempt}` },
);
res.json({ id: session.id, sessionData: session.sessionData });
});import com.adyen.Client;
import com.adyen.Config;
import com.adyen.enums.Environment;
import com.adyen.model.RequestOptions;
import com.adyen.model.checkout.*;
import com.adyen.service.checkout.PaymentsApi;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
public class SessionController {
private final PaymentsApi payments;
private final OrderRepository orders; // your persistence
public SessionController(OrderRepository orders) {
Config config = new Config()
.apiKey(System.getenv("ADYEN_API_KEY"))
.environment(Environment.TEST); // LIVE also needs liveEndpointUrlPrefix
this.payments = new PaymentsApi(new Client(config));
this.orders = orders;
}
@PostMapping("/api/sessions")
public Map<String, String> create(@RequestBody Map<String, String> body) throws Exception {
Order order = orders.findPending(body.get("orderId")).orElseThrow();
CreateCheckoutSessionRequest req = new CreateCheckoutSessionRequest()
.merchantAccount(System.getenv("ADYEN_MERCHANT_ACCOUNT"))
.amount(new Amount().currency(order.getCurrency()).value(order.getAmountMinor()))
.reference(order.getId())
.countryCode(order.getCountryCode())
.returnUrl(System.getenv("APP_BASE_URL") + "/checkout/return?orderId=" + order.getId());
CreateCheckoutSessionResponse res = payments.sessions(req,
new RequestOptions().idempotencyKey("session-" + order.getId() + "-" + order.getAttempt()));
return Map.of("id", res.getId(), "sessionData", res.getSessionData());
}
}Frontend: Drop-in (Adyen Web v6)
Install @adyen/adyen-web, fetch a session from your server, create AdyenCheckout and mount Dropin. The callbacks only update the UI — fulfilment happens from the webhook.
import { useEffect, useRef, useState } from "react";
import { AdyenCheckout, Dropin } from "@adyen/adyen-web/auto";
import "@adyen/adyen-web/styles/adyen.css";
export default function AdyenDropin({ orderId, amount, countryCode, locale }) {
const ref = useRef(null);
const [msg, setMsg] = useState("");
useEffect(() => {
let dropin;
(async () => {
const res = await fetch("/api/sessions", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ orderId }),
});
const session = await res.json();
const checkout = await AdyenCheckout({
session, // { id, sessionData }
environment: "test",
clientKey: process.env.REACT_APP_ADYEN_CLIENT_KEY,
amount, countryCode, locale,
onPaymentCompleted: (result) =>
setMsg(`Result: ${result.resultCode}. We'll confirm by email once the payment is verified.`),
onPaymentFailed: () => setMsg("Payment failed. Please try another method."),
onError: (err) => setMsg(err.message || "Something went wrong."),
});
dropin = new Dropin(checkout, {}).mount(ref.current);
})();
return () => dropin?.unmount();
}, [orderId, amount, countryCode, locale]);
return (<><div ref={ref} /><p role="status">{msg}</p></>);
}Tip: @adyen/adyen-web/auto registers all payment methods (bigger bundle). To shrink it, import AdyenCheckout, Dropin and individual methods from @adyen/adyen-web instead, as the docs show.
Initiating a payment
- Create a
pendingorder with the price in minor units. - Call
/sessionswith that order's amount andreference. - Mount Drop-in with the returned
id+sessionData.
For redirect methods the shopper comes back to returnUrl?sessionId=...&redirectResult=.... Create AdyenCheckout with session: { id: sessionId } and call checkout.submitDetails({ details: { redirectResult } }); Drop-in then calls onPaymentCompleted. If the shopper never returns, do nothing — wait for the webhook.
Confirming the payment
result.resultCode in the browser (Authorised, Refused, Pending, ...) is for messaging only. The authoritative outcome is the AUTHORISATION webhook: success: "true" means authorised. Match it to your order by merchantReference and check amount.value/currency against the order.
Warning: Never fulfil from onPaymentCompleted or from the return URL — both are controlled by the shopper's browser.
Webhooks with HMAC verification
Configure a Standard webhook in the Customer Area and generate an HMAC key. Each NotificationRequestItem carries additionalData.hmacSignature: Base64(HMAC-SHA256(hexDecode(key), payload)) where payload is
pspReference:originalReference:merchantAccountCode:merchantReference:value:currency:eventCode:success (empty fields become empty strings).
Adyen wants a 2xx response (for example 202) within 10 seconds, before your business logic runs; otherwise the webhook is marked failing and retried. Duplicates share eventCode + pspReference.
import { hmacValidator } from "@adyen/api-library";
const validator = new hmacValidator();
app.post("/webhooks/adyen", express.json({ limit: "1mb" }), (req, res) => {
const items = (req.body.notificationItems || []).map((i) => i.NotificationRequestItem);
const valid = items.filter((item) => {
try { return validator.validateHMAC(item, process.env.ADYEN_HMAC_KEY); }
catch { return false; }
});
if (valid.length !== items.length) console.warn("Adyen webhook item(s) with invalid HMAC ignored");
res.status(202).end(); // acknowledge first, then process
for (const item of valid) queue.push(item); // e.g. a job queue
});
async function processItem(item) {
const key = `${item.eventCode}:${item.pspReference}`;
if (!(await db.webhookEvents.insertIfAbsent(key))) return; // duplicate
if (item.eventCode === "AUTHORISATION" && item.success === "true") {
const order = await db.orders.findById(item.merchantReference);
if (order && order.amountMinor === item.amount.value && order.currency === item.amount.currency) {
await fulfilOnce(order.id, item.pspReference);
}
}
if (item.eventCode === "REFUND") await db.refunds.markDone(item.originalReference, item.success === "true");
}import com.adyen.model.notification.NotificationRequest;
import com.adyen.model.notification.NotificationRequestItem;
import com.adyen.notification.WebhookHandler;
import com.adyen.util.HMACValidator;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
public class WebhookController {
private final HMACValidator hmac = new HMACValidator();
private final WebhookHandler handler = new WebhookHandler();
private final WebhookQueue queue; // your async processor (dedupes eventCode+pspReference)
public WebhookController(WebhookQueue queue) { this.queue = queue; }
@PostMapping("/webhooks/adyen")
public ResponseEntity<Void> receive(@RequestBody String json) throws Exception {
NotificationRequest request = handler.handleNotificationJson(json);
String key = System.getenv("ADYEN_HMAC_KEY");
for (NotificationRequestItem item : request.getNotificationItems()) {
boolean ok;
try { ok = hmac.validateHMAC(item, key); } catch (Exception e) { ok = false; }
if (ok) queue.enqueue(item); // process after acknowledging
}
return ResponseEntity.accepted().build(); // 202 within 10 s
}
}Security: HMAC covers only the eight listed fields, not the whole body. Optionally also enable basic authentication on the webhook endpoint in the Customer Area, and keep the old HMAC key valid for a while when rotating.
Checking status
The sessions flow is webhook-driven: store every AUTHORISATION result against the order. For orders that stay pending, check the payment in the Customer Area or your webhook logs; do not poll in a tight loop. Webhooks that failed are retried from Adyen's retry queue once your endpoint is healthy again.
Refunds
Refund with POST /v72/payments/{paymentPspReference}/refunds (body: merchantAccount, amount, reference). The response only means the request was received; the outcome arrives as a REFUND (or REFUND_FAILED) webhook.
app.post("/admin/orders/:id/refund", requireStaff, async (req, res) => {
const order = await db.orders.findById(req.params.id);
const response = await checkout.ModificationsApi.refundCapturedPayment(
order.pspReference,
{
merchantAccount: process.env.ADYEN_MERCHANT_ACCOUNT,
amount: { value: order.amountMinor, currency: order.currency },
reference: `refund-${order.id}`,
},
{ idempotencyKey: `refund-${order.id}` },
);
await db.refunds.create({ orderId: order.id, pspReference: response.pspReference, status: "received" });
res.json({ status: response.status });
});Errors
Library calls throw on non-2xx responses (HttpClientException in Node/Java) with Adyen's errorCode and message. Common causes: wrong merchant account, invalid API key (401), client key used from a non-allowed origin (Drop-in onError), or amount.value sent as a decimal instead of minor units.
Going to production
- Get a live account approved; create live API key, client key and webhook HMAC key.
- Set
environmentto LIVE with yourliveEndpointUrlPrefix, andenvironment: 'live'in Adyen Web. - Add your production domain to the client key's allowed origins.
- Make sure the webhook endpoint answers 2xx fast and processes asynchronously.
Security
- API key and HMAC key only in env vars / a secrets manager.
- Amount and reference from your database, never from the browser.
- Verify HMAC on every notification item; reject items that fail.
- Fulfil idempotently keyed by
eventCode+pspReference. - Restrict and audit refund endpoints.
Testing
Adyen's published test cards (any name):
- Visa
4111 1111 4555 1142— expiry03/2030, CVC737. - Mastercard
5555 3412 4444 1115— expiry03/2030, CVC737.
Use the Customer Area's webhook Test button to send a sample notification and confirm your HMAC check passes.
Common mistakes
- Processing business logic before responding — slow handlers exceed 10 s and the webhook is marked failing.
- Treating
onPaymentCompletedas proof of payment. - Not decoding the HMAC key from hex before computing the signature (only relevant if you skip the library).
- Sending
amount.value: 10.00instead of1000. - Calling
submitDetailswhen the shopper never returned toreturnUrl.
Troubleshooting
- HMAC always invalid: wrong key (each webhook has its own), key rotated recently, or
valuere-formatted before validation. - Drop-in shows no methods: methods not enabled for the merchant account, or
countryCode/currency mismatch. - Drop-in
onErrorabout origin: add the page origin to the client key's allowed origins. - Webhooks marked failing: endpoint unreachable, non-2xx, or slower than 10 s.
Further reading
Official documentation
Official documentation
Sources
More payment guides
- Adyen provider profile
- Airtel Money Collections: USSD Push with the Airtel Africa Open API
- Flutterwave Checkout (Standard): hosted payment page, webhooks, verify and refunds
- M-Pesa Daraja STK Push (Lipa na M-Pesa Online)
- MTN MoMo Collections: Request to Pay with the MoMo Open API
- Mercado Pago Checkout Pro: preferences, back URLs and signed webhooks
- Mollie Payments API: hosted checkout, webhooks and refunds
- PayHero Kenya: M-Pesa STK Push via the PayHero API
- PayPal Checkout with Orders v2, verified webhooks and refunds