Skip to content

Search docs

Jump between documentation pages.

Browse docs

Accept payments with Adyen in DaloyJS

Adyen is a single platform for cards, wallets, and local payment methods across Europe, the US, APAC, and LATAM. This guide uses the official @adyen/api-library Node SDK (32.x, which targets Checkout API v72) from a DaloyJS server, the Sessions flow with Adyen Web (6.x) on the frontend, and the bundled hmacValidator for Standard webhooks.

What you should know up front

  • Use Sessions for Drop-in / Components. In the Sessions flow your server creates a session, the frontend hands it to Adyen Web, and Adyen handles 3-D Secure 2, redirects, and payment-method quirks. Direct /payments is still supported for server-to-server use cases.
  • The amount comes from your order. The browser sends an order id; the server builds amount from the stored total. See never trust client amounts.
  • Live needs a URL prefix. Production Checkout calls go through a merchant-specific endpoint. Set liveEndpointUrlPrefix on the Client for live.
  • Webhooks are double-checked. Protect the endpoint with HTTP Basic auth (core basicAuth()), then verify each item's HMAC-SHA256 signature in additionalData.hmacSignature with hmacValidator, and check the top-level live flag matches your environment.
  • Amounts are minor units. EUR 10.00 is { currency: "EUR", value: 1000 }; JPY 1000 is value: 1000.

1. Provision

  1. Create a test account and a merchant account inside it.
  2. Generate an API key (Customer Area -> Developers -> API credentials) and grant it the Checkout webservice role.
  3. Configure a Standard notification webhook in Customer Area -> Developers -> Webhooks. Point it at your DaloyJS endpoint, choose JSON, generate an HMAC key, and set a Basic auth username and password.
  4. For production: note your liveEndpointUrlPrefix from Customer Area -> Developers -> API URLs.

2. Install

bash
pnpm add @adyen/api-library

3. Environment variables

.envbash
ADYEN_ENVIRONMENT=TEST                         # or LIVE
ADYEN_API_KEY=AQE...replace_me
ADYEN_MERCHANT_ACCOUNT=YourMerchantAccountName
ADYEN_HMAC_KEY=hex_string_from_customer_area   # webhook signing key (hex)
ADYEN_WEBHOOK_USER=replace_me                  # Basic auth username
ADYEN_WEBHOOK_PASSWORD=replace_me              # Basic auth password
ADYEN_LIVE_URL_PREFIX=                         # required when ENVIRONMENT=LIVE
ADYEN_CLIENT_KEY=test_...replace_me            # public key, ships to the browser

4. Plugin

src/plugins/adyen.tsts
import { Client, CheckoutAPI, EnvironmentEnum, Types, hmacValidator } from "@adyen/api-library";
import type { App } from "@daloyjs/core";

export const ADYEN_ENVIRONMENT = process.env.ADYEN_ENVIRONMENT === "LIVE" ? "LIVE" : "TEST";

const client = new Client({
  apiKey: process.env.ADYEN_API_KEY!,
  environment: ADYEN_ENVIRONMENT === "LIVE" ? EnvironmentEnum.LIVE : EnvironmentEnum.TEST,
  ...(ADYEN_ENVIRONMENT === "LIVE" ? { liveEndpointUrlPrefix: process.env.ADYEN_LIVE_URL_PREFIX! } : {}),
});

const checkout = new CheckoutAPI(client);
const validator = new hmacValidator();
const merchantAccount = process.env.ADYEN_MERCHANT_ACCOUNT!;

type Amount = { currency: string; value: number };

export interface AdyenClient {
  createSession(input: {
    amount: Amount;
    reference: string;
    returnUrl: string;
    shopperReference?: string;
    idempotencyKey: string;
  }): Promise<Types.checkout.CreateCheckoutSessionResponse>;
  capture(input: { pspReference: string; amount: Amount; idempotencyKey: string }): Promise<{ pspReference: string }>;
  refund(input: { pspReference: string; amount: Amount; idempotencyKey: string }): Promise<{ pspReference: string }>;
  verifyWebhookItem(item: Types.notification.NotificationRequestItem): boolean;
}

// Exported so job handlers (which run outside a request) can use it too.
export const adyenClient: AdyenClient = {
  createSession({ amount, reference, returnUrl, shopperReference, idempotencyKey }) {
    return checkout.PaymentsApi.sessions(
      { merchantAccount, amount, reference, returnUrl, shopperReference },
      { idempotencyKey },
    );
  },

  async capture({ pspReference, amount, idempotencyKey }) {
    const res = await checkout.ModificationsApi.captureAuthorisedPayment(
      pspReference,
      { merchantAccount, amount },
      { idempotencyKey },
    );
    return { pspReference: res.pspReference };
  },

  async refund({ pspReference, amount, idempotencyKey }) {
    const res = await checkout.ModificationsApi.refundCapturedPayment(
      pspReference,
      { merchantAccount, amount },
      { idempotencyKey },
    );
    return { pspReference: res.pspReference };
  },

  verifyWebhookItem(item) {
    // validateHMAC throws (not returns false) when the item carries no
    // hmacSignature or is malformed. Treat that as a failed check so the
    // route answers 401, not 500.
    try {
      return validator.validateHMAC(item, process.env.ADYEN_HMAC_KEY!);
    } catch {
      return false;
    }
  },
};

// Call with the root app, not through app.register(): a decoration made
// inside a registered plugin is visible only to that plugin's own routes.
export function adyenPlugin(app: App) {
  app.decorate("adyen", adyenClient);
}

declare module "@daloyjs/core" {
  interface AppState {
    adyen: AdyenClient;
  }
}

hmacValidator is a class; instantiate it once. Capture and refund live on the plugin so routes and job handlers call them the same way, always with an idempotency key.

5. Create a session for Drop-in / Components

The frontend renders Adyen Web with the id and sessionData from this response. You never touch a PAN, and 3-D Secure 2 runs inside the Drop-in. The route relies on the shared app wiring (session, scoped csrf() and rateLimit()) and the overview's orders module.

src/routes/checkout-adyen.tsts
import { z } from "zod";
import { adyenPlugin } from "../plugins/adyen.ts";
import { orders } from "../orders.ts";

adyenPlugin(app);

app.post(
  "/checkout/session",
  {
    operationId: "createAdyenSession",
    request: {
      body: z.object({ orderId: z.string().min(1).max(80) }).strict(),
    },
    responses: {
      201: {
        description: "session created",
        body: z.object({ id: z.string(), sessionData: z.string(), clientKey: z.string() }),
      },
    },
  },
  async ({ body, state }) => {
    const userId = state.session.get<string>("userId");
    const order = await orders.forCheckout(body.orderId, userId);
    const session = await state.adyen.createSession({
      amount: { currency: order.currency, value: order.amountMinor }, // server-side total
      reference: order.id,
      shopperReference: userId,
      returnUrl: `${process.env.APP_URL}/checkout/return?ref=${encodeURIComponent(order.id)}`,
      idempotencyKey: `session:${order.id}:v${order.version}`,
    });
    return {
      status: 201,
      body: { id: session.id!, sessionData: session.sessionData!, clientKey: process.env.ADYEN_CLIENT_KEY! },
    };
  },
);

6. Standard webhook notifications

Webhook verification
AdyenDaloyJS routeJob worker
  1. 01requestAdyenDaloyJS routePOST /webhooks/adyenBasic auth + { live, notificationItems[] }
  2. 02noteDaloyJS routeDaloyJS routebasicAuth(), live flag, then validateHMAC per itemadditionalData.hmacSignature, HMAC-SHA256
  3. 03responseDaloyJS routeAdyen401 on bad credentials, HMAC, or environmentproblem+json
  4. 04asyncDaloyJS routeJob workerenqueue keyed by pspReference + eventCode, then 200worker compares amount with the order
Basic auth runs before the body is read, the live flag rejects test events on a live endpoint, the per-item HMAC proves the fields came from Adyen, and the job key collapses duplicate deliveries.

Adyen posts JSON like { "live": "false", "notificationItems": [{ "NotificationRequestItem": { ... } }] }. Core basicAuth() compares the credentials before the body is read; compare both fields with timingSafeEqual and without short-circuiting:

src/webhooks/adyen.tsts
import { z } from "zod";
import { basicAuth, jobIdempotencyKey, timingSafeEqual } from "@daloyjs/core";
import type { Types } from "@adyen/api-library";
import { ADYEN_ENVIRONMENT } from "../plugins/adyen.ts";

const adyenWebhookAuth = basicAuth({
  verify: (username, password) => {
    const userOk = timingSafeEqual(username, process.env.ADYEN_WEBHOOK_USER!);
    const passOk = timingSafeEqual(password, process.env.ADYEN_WEBHOOK_PASSWORD!);
    return userOk && passOk;
  },
});

app.post(
  "/webhooks/adyen",
  {
    operationId: "adyenWebhook",
    hooks: adyenWebhookAuth,
    request: {
      body: z.object({
        live: z.enum(["true", "false"]),
        notificationItems: z.array(z.object({ NotificationRequestItem: z.record(z.string(), z.unknown()) })).max(100),
      }),
    },
    responses: {
      200: { description: "ack", body: z.object({ notificationResponse: z.literal("[accepted]") }) },
      401: { description: "rejected", body: z.object({ error: z.string() }) },
    },
  },
  async ({ body, state }) => {
    // A test event must never mark a live order paid (and the reverse).
    if (body.live !== (ADYEN_ENVIRONMENT === "LIVE" ? "true" : "false")) {
      return { status: 401, body: { error: "wrong environment" } };
    }

    const items = body.notificationItems.map(
      (w) => w.NotificationRequestItem as unknown as Types.notification.NotificationRequestItem,
    );
    // Verify every item before acting on any of them.
    if (!items.every((item) => state.adyen.verifyWebhookItem(item))) {
      return { status: 401, body: { error: "bad hmac" } };
    }

    for (const item of items) {
      const key = `${item.pspReference}:${item.eventCode}:${item.success}`;
      await app.jobs!.enqueue({
        name: "adyen.notification",
        payload: {
          pspReference: item.pspReference,
          eventCode: item.eventCode,
          success: item.success,
          merchantReference: item.merchantReference,
          amount: { currency: item.amount.currency, value: item.amount.value },
        },
        idempotencyKey: jobIdempotencyKey({ name: "adyen.notification", key }),
      });
    }

    return { status: 200, body: { notificationResponse: "[accepted]" as const } };
  },
);

Adyen's current docs accept a delivery based on the HTTP status code (a 2xx); the [accepted] body is the long-standing convention and is harmless to keep. Duplicates share pspReference and eventCode, which is why those make the job key.

src/jobs/adyen.tsts
import type { JobHandler } from "@daloyjs/core";
import { orders } from "../orders.ts";

type AdyenNotification = {
  pspReference: string;
  eventCode: string;
  success: string;
  merchantReference: string;
  amount: { currency?: string; value?: number };
};

export const handleAdyenNotification: JobHandler<AdyenNotification> = async ({ job }) => {
  const n = job.payload;
  if (n.eventCode !== "AUTHORISATION" || n.success !== "true") return;
  await orders.markPaid(n.merchantReference, {
    amountMinor: n.amount.value ?? -1,
    currency: n.amount.currency ?? "",
    providerRef: n.pspReference,
  });
};
// Register it in your single app.useJobs() call (see the payments overview).

AUTHORISATION with success === "true" is the canonical "the money is good" signal. The HTTP response from /payments or the Sessions callback is only a hint; the HMAC-verified webhook is the source of truth, and orders.markPaid() still compares the amount and currency with the stored order.

7. Modifications (capture, refund, cancel)

Expose refunds only through a protected refund route. The plugin calls:

ts
// Capture an authorisation (manual capture flow).
await state.adyen.capture({
  pspReference: order.providerRef!,
  amount: { currency: order.currency, value: order.amountMinor },
  idempotencyKey: `capture:${order.id}`,
});

// Refund part of a captured payment.
await state.adyen.refund({
  pspReference: order.providerRef!,
  amount: { currency: order.currency, value: 250 },
  idempotencyKey: `refund:${order.id}:${order.refundedMinor}:250`,
});

Modifications are asynchronous at Adyen: the API answers received, and the outcome arrives later as a CAPTURE or REFUND webhook. Update your ledger from those events.

Runtimes

The SDK uses Node's built-in https module by default and runs on Node hosts (long-lived Node, Vercel Node.js functions, AWS Lambda, Azure Functions). Deno, Cloudflare Workers, and Vercel Edge are not verified; there, call the Checkout API (https://checkout-test.adyen.com/v72/... in test) directly with fetch and keep hmacValidator or a WebCrypto port for webhooks. See the runtime table.

Errors

Adyen returns RFC 7807-shaped errors with status, errorCode, message, and errorType; the SDK throws HttpClientException carrying them. Log those fields and map the failure to problem+json with your own type and title.

Modernisation notes

  • Sessions over /payments + /payments/details. The Advanced flow still works, but Sessions removes a class of state-management bugs.
  • Keep Adyen Web current. Sessions responses map directly onto the Adyen Web 6 checkout configuration.
  • Don't roll your own HMAC. Adyen signs a colon-delimited subset of fields with an escape rule and a hex-decoded key; hmacValidator handles both.
  • Consider stronger webhook auth. Adyen documents Basic auth for every webhook type and recommends OAuth where available.

See also the payments overview, Braintree guide, Authorize.Net guide, and problem+json errors.

Edit this page on GitHub

Last updated