Looking for ePay classic docs? Go to docs.epay.dk
ePay documentationDocsePay documentation

ePay.js reference

Embed secure payment fields, trigger wallet flows, and manage payment state from your own checkout with a reference built for implementation speed.

Introduction

Welcome to the ePay.js reference documentation. This guide provides a complete overview of how to integrate ePay.js into your web application for secure and seamless payment processing.

Before integrating ePay.js, you need:

  • An ePay account
  • An API key for server-side authentication
  • A Point of Sale ID to identify your business

The first thing you need to do is to initialize a payment session. This needs to be done server side, as it requires your API key.

The response from the server will include a link to the ePay.js client, which includes the session ID for the payment session.

The link is available in the javascript field of the response object.

You will also need to save the session ID (id) and the session key (key) for the payment session, as you will need to provide these when initializing the ePay.js client.

Please note, that the ePay client needs to be fetched each time a new payment session is initialized and therefore can't be cached.

Example response: Initialize payment session
{  "paymentWindowUrl": "https://payments.epay.eu/payment-window?sessionId=01954c23-7baa-755c-839c-957efd4892c2&sessionKey=c1690a71-154c-4ab6-b789-ec21c9a224fb",  "session": {    "id": "01954c23-7baa-755c-839c-957efd4892c2",    "pointOfSaleId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",    "timeout": 20,    "instantCapture": "OFF",    "reference": "my-reference-1",    "amount": 100,    "currency": "DKK",    "textOnStatement": null,    "state": "PENDING",    "dynamicAmount": false,    "createdAt": "2025-02-28T10:39:08.713109269Z",    "expiresAt": "2025-02-28T10:59:08.713109269Z",    "notificationUrl": "https://my-notification-url.com",    "successUrl": "https://my-success-url.com",    "failureUrl": "https://my-failure-url.com",    "preAuthUrl": null,    "retryUrl": null,    "attributes": null,    "scaMode": "NORMAL",    "reportFailure": false,    "exemptions": [],    "subscriptionId": null,    "maxAttempts": 5,    "attempts": 0  },  "key": "c1690a71-154c-4ab6-b789-ec21c9a224fb",  "javascript": "https://payments.epay.eu/sessions/01954c23-7baa-755c-839c-957efd4892c2/client.js"}

Include ePay.js

Once the payment session is initialized, include the ePay.js script in your webpage using the URL from the javascript-field in the session response.

This can be done by adding the following line of code inside the <head></head> tag your website.

Always load ePay.js from the javascript URL returned when you initialize the payment session. Do not hard-code the URL, download the script, or bundle a copy into your application.

ePay.js changes over time. Loading the session-provided script ensures your checkout receives compatible updates and avoids broken payment flows when new client versions are released.

Including ePay.js
<script    src="https://payments.epay.eu/sessions/01954c23-7baa-755c-839c-957efd4892c2/client.js"></script>

Initialize the ePay.js client

After including ePay.js, initialize the client using your Session ID (session.id) and Session Key (key) from the session response.

setSessionId, setSessionKey, and setCallbacks return the ePay client, so they can be chained. init() returns Promise<void>; it resolves when the session is verified and rejects when it cannot be verified.

Use setCallbacks(callbacks) before init() to receive payment-state notifications. Each callback receives one event object. The event property identifies the callback that was dispatched.

JavaScript events

The javascript functions below can be set to receive notifications from the client with information of the current transaction state.

All events have a default handler that makes sure the payment is processed as expected.

If merchants wants to modify this flow, like handling redirects differently, they can register a handler with their own logic and return false to disable the default handler.

Do note that ePay cannot guarantee correct handling of events in this case.

Client methods
setSessionId(sessionId)Epay

Sets the payment-session ID.

setSessionKey(sessionKey)Epay

Sets the payment-session key used for client API calls.

setCallbacks(callbacks)Epay

Registers callbacks for the event names below.

init()Promise<void>

Verifies the configured session and loads its client configuration.

Callbacks
clientReady{ event: "clientReady" }

The session has been verified and the client is ready to use.

invalidSession{ event, errorCode, message }

The provided session ID or key could not be verified.

challengeIssued{ event, context }

A challenge flow, such as 3-D Secure, is about to start.

transactionAccepted{ event, context }

The transaction was accepted.

transactionDeclined{ event, context, maxAttemptsReached }

The transaction was declined. `maxAttemptsReached` is true when no further attempts are allowed.

feeUpdated{ event, fee: number }

The calculated transaction fee changed. `fee` is in minor currency units.

clientRedirect{ event, context }

The client is about to redirect the shopper. `context.url` contains the destination URL.

invalidInput{ event, errorCode, message }

The selected payment method cannot be processed with the submitted input.

inputValidity{ event, state }

Hosted-fields validity changed. `state` contains `pan`, `expiry`, `cvc`, optional `name`, and aggregate `valid` booleans.

inputSubmit{ event: "inputSubmit" }

The shopper submitted hosted fields directly, for example by pressing Enter.

sessionExpired{ event: "sessionExpired" }

The current session expired.

paymentMethodInitiated{ event, paymentMethod }

A payment-method flow was started. `paymentMethod` is the ePay payment-method type.

paymentCancel{ event, paymentMethod }

The shopper cancelled a wallet payment flow.

confirmSurcharge{ event, context }

A surcharge requires shopper confirmation before processing continues.

error{ event, errorCode, message }

The client encountered an error that is not reported by a more specific callback.

transactionAccepted and transactionDeclined are emitted only when the payment completes on the current page. They are not emitted after the shopper has already left the page for a redirect flow, such as 3-D Secure, age verification, or a payment-method-specific redirect.

Initialize the ePay.js client
epay  .setSessionId("<SESSION_ID>")  .setSessionKey("<SESSION_KEY>")  .setCallbacks({    // This method is optional    clientReady: clientReadyCallback,    invalidSession: invalidSessionCallback,    challengeIssued: challengeIssuedCallback,    transactionAccepted: transactionAcceptedCallback,    transactionDeclined: transactionDeclinedCallback,    feeUpdated: feeUpdatedCallback,    clientRedirect: clientRedirectCallback,    invalidInput: invalidInputCallback,    inputValidity: inputValidityCallback,    inputSubmit: inputSubmitCallback,    sessionExpired: sessionExpiredCallback,    paymentMethodInitiated: paymentMethodInitiatedCallback,    paymentCancel: paymentCancelCallback,    confirmSurcharge: confirmSurchargeCallback,    error: errorCallback,  })  .init();

Mounting the fields mountFields

The mountFields(id, appearance) method renders hosted payment fields in the specified container. It returns Promise<void>, which resolves when the fields are ready for shopper input.

Call it after configuring the session. id is the ID of the target container element; appearance configures the hosted fields.

The appearance object supports:

  • theme
  • language
  • fields
  • variables

Only one hosted-fields instance can be mounted at a time. Mounting multiple field containers is not supported.

Hosted fields are a live payment application. For a hosted card payment, keep the mounted fields and their iframe in the DOM until the payment completes or ePay starts a redirect flow. Do not remove or replace the container while payment processing is active.

Signature — mountFields(id, appearance): Promise<void>
idString

ID of the element that will contain the hosted fields.

appearanceObject

Hosted-fields configuration. Use `theme`, `language`, `fields`, `loader`, and `variables` as described below.

Theme theme

Determines the overall style of the payment fields in Blocks (for example,  "default" provides an ePay-inspired look).

Themes
default

The default ePay inspired styling.

Language language

Optionally sets the language for labels and messages.

Languages
da

Danish

en

English

sv

Swedish

no

Norwegian

de

German

bg

Bulgarian

et

Estonian

fi

Finnish

fr

French

el

Greek

ga

Irish

it

Italian

hr

Croatian

lv

Latvian

lt

Lithuanian

mt

Maltese

nl

Dutch

pl

Polish

pt

Portuguese

ro

Romanian

sk

Slovak

sl

Slovenian

es

Spanish

cs

Czech

hu

Hungarian

fo

Faroese

Additional Fields fields

By default, only the essential payment method fields are included. If you need extra fields, such as a cardholder name field use this object to enable them.

Cardholder name name

By default, there is no input field for the cardholder name. If you need to collect this information, you can enable it when mounting the fields by passing the fields object.

Name field options
enabledBoolean

Displays the cardholder-name field when true.

valueString

Optional initial cardholder name.

A prefilled cardholder name can be given by sending the fields.name.value parameter.

PAN field pan

The PAN field supports the following options:

PAN field options
focus

Boolean: Controls whether the field should be focused on mount. Default is true.

showSupportedSchemes

Boolean: Controls the visibility of supported schemes. Default is true.

showBrandSelector

Boolean: Controls the visibility of the card brand selector. Default is true.

showBrandSelector

EU PSD2 requires the card brand selector (showBrandSelector) to be displayed.

Loader loader

Allows you to customize visual aspects of the loader, such as background color, border style, and height.

Loader options
backgroundColorString (optional)

CSS background color for the loader.

borderStyleString (optional)

CSS border style for the loader, for example `solid` or `none`.

heightString (optional)

CSS height for the loader and hosted-fields container, for example `150px`.

Styling Variables variables

Allows you to customize visual aspects such as text color, border radius, fonts, spacing, and more.

Every value in variables must be a string, including numeric CSS values. For example, use { borderRadius: "0" }, not { borderRadius: 0 }.

General
colorText

The font color of text, used for labels and input content.

borderRadius

The border radius for inputs and the window.

borderColor

The default border color for inputs and the window.

fontFamily

The font used for labels, input content, and placeholders.

Spacing between the input fields (horizontal and vertical)
gridColumnSpacing

Horizontal spacing between input fields in the grid layout.

gridRowSpacing

Vertical spacing between input fields in the grid layout.

gridTemplateColumns

Defines the column structure of the grid layout.

Displaying icons and brands
iconDisplay

Controls the visibility of icons in the fields (e.g., block or none).

cardBrandDisplay

Controls the visibility of card brand icons (e.g., block or none).

supportedSchemesDisplay

Controls the visibility of supported schemes (e.g., flex or none).

Label elements
labelColor

The font color for labels.

labelFontSize

The font size for labels.

labelFontWeight

The font weight for labels.

labelMarginBottom

The spacing below labels.

Input elements
inputColor

The font color for user input.

inputBorderRadius

The border radius for input fields.

inputBorderColor

The border color for input fields.

inputFocusBorderColor

The border color when an input field is in focus.

inputFontSize

The font size for input fields.

inputPadding

The padding inside input fields.

inputPlaceholderColor

The font color for placeholder text in input fields.

inputBackgroundColor

The background color for input fields.

inputBoxShadow

The box shadow for input fields.

inputFocusBoxShadow

The box shadow for input fields when they are in focus.

windowPadding

The padding around the window containing the payment fields.

windowBackgroundColor

The background color of the window containing the payment fields.

windowBorderStyle

The border style of the window containing the payment fields.

windowBorderRadius

The border radius of the window containing the payment fields.

windowBorderColor

The border color of the window containing the payment fields.

Color specific
colorDanger

The color used to indicate problems or input validation errors.

colorPrimary

The primary theme color for the payment fields.

Element to mount fields to
<div id="containerId"></div>
Mounting the fields
epay.mountFields("containerId", {  // The configuration object is optional  theme: "default",  language: "da",  fields: {    name: { enabled: true, value: "" },    pan: {      focus: true,      showSupportedSchemes: true,      showBrandSelector: true,    },  },  loader: {    backgroundColor: "transparent",    borderStyle: "none",    height: "150px",  },  variables: {    colorText: "#2e3033",  },});

Clearing the fields clearFields

The clearFields method resets all input fields in the Blocks component — including PAN (card number), CVC, and expiry — without unmounting or reloading the component.

It is typically used if a user wants to re-enter card details after submitting or cancelling a payment attempt.

clearFields
idString

The same container identifier used when calling epay.mountFields(id).

Clearing the fields
epay.clearFields("containerId");

Control hosted fields

Use these methods after calling mountFields(id, appearance) to control the mounted field instance.

Methods
epay.updateLanguage(id, language)void

Updates the hosted-fields language. Use one of the supported language codes listed above.

epay.setFocusField(id, field)void

Moves focus to `pan`, `expiry`, `cvc`, or `name`.

Update the hosted-fields language
epay.updateLanguage("containerId", "en");

Adding a payment button

This button must call the appropriate payment method initialization method:

Each method accepts an optional payment-options object. Transaction outcome is reported through callbacks, including transactionAccepted, transactionDeclined, clientRedirect, and error.

For hosted card payments, keep the mounted fields and iframe in the DOM after calling createCardTransaction() until the payment completes or a redirect flow begins.

To comply with Apple Pay, Vipps MobilePay, and Google Pay terms and conditions, you must use their respective buttons.

Methods
epay.createCardTransaction()(options?: PaymentOptions) => Promise<void>

Initializes and begins processing of a card (Blocks) based payment.

epay.createVippsMobilePayTransaction()(options?: PaymentOptions) => Promise<void>

Initializes and begins processing of a Vipps-MobilePay based payment.

epay.createApplePayTransaction()(options?: PaymentOptions) => void

Initializes and begins processing of a ApplePay based payment.

epay.createGooglePayTransaction()(options?: PaymentOptions, merchantId?: string, googleOptions?: object) => Promise<void>

Initializes and begins processing of a GooglePay based payment.

epay.createAnydayTransaction()(options?: PaymentOptions) => Promise<void>

Initializes and begins processing of a Anyday based payment.

epay.createViabillTransaction()(options?: PaymentOptions) => Promise<void>

Initializes and begins processing of a Viabill based payment.

epay.createSwishTransaction()(options?: PaymentOptions) => Promise<void>

Initializes and begins processing of a Swish based payment.

epay.createKlarnaTransaction()(options?: PaymentOptions) => Promise<void>

Initializes and begins processing of a Klarna based payment.

Payment button: Card based payment
<button type="button" onclick="epay.createCardTransaction()">  Pay</button>

Payment options setPaymentOptions

The setPaymentOptions() method is used to configure the payment options by setting the amount and store parameters for the transaction.

Signature: setPaymentOptions(options: PaymentOptions): Epay. Values are retained for later transaction calls; values passed to an individual transaction method take precedence.

This method is particularly useful when dynamic amounts are enabled, or when you need to store the payment method for future quick deposits.

amount Number

Sets the payment amount when dynamic amount mode is enabled. The amount is provided in minor currency units (for example, 10000 represents 100.00 in your currency).

store Boolean

When set to true, the payment method is saved for future use (e.g., quick deposits). This functionality requires cardholder approval in Denmark, which should be obtained via a checkbox or similar method.

PaymentOptions
amountNumber (optional)

Transaction amount in minor currency units. Use for sessions with dynamic amounts enabled.

storeBoolean (optional)

Requests storage of the payment method for future use.

Mounting the fields
epay.setPaymentOptions({amount: 10000, store: true});

Get stored Payment options getStoredPaymentMethods

This method retrieves all stored payment methods (cards) for the current user. The stored cards are scoped based on the customerId provided during session initialization.

If no customerId is set during session initialization, the method will return an empty array.

While this method can be used to fetch stored cards, it is expected that you might not need it if you are already managing your own account system.

Response — Promise<StoredPaymentMethod[]>
feeNumber

Current fee in minor currency units.

paymentMethodObject

Stored method: `id`, `customerId`, `displayText`, `type`, `subType`, `expiry`, and `createdAt`.

Getting stored Payment Methods
epay  .getStoredPaymentMethods()  .then(paymentMethods => {    console.log('Stored Payment Methods:', paymentMethods);  })  .catch(error => {    console.error('Error fetching stored payment methods:', error);  });

Get supported Payment method types getSupportedPaymentMethodTypes

This method retrieves available supported payment method types for the current session. The method is context-aware, meaning it will dynamically filter payment methods depending on the session data, and your account settings.

It will match the requirement of specific payment method types to the current session.

This method can be used by partners / plugins who needs to dynamically build their UI depending on the context of the current merchant or payment.

The method returns Promise<Record<string, SupportedPaymentMethod>>. Each object key is the stable payment-method type; use it to identify the method.

  • name: Display name. Do not use it as an identifier.
  • url: URL to a payment-method logo.
  • method: Function that starts that payment method.

To uniquely identify a payment method, merchant should refer to the key of the object and not the name property.

SupportedPaymentMethod
nameString

Display name for the payment method.

urlString

Absolute URL to the payment-method logo.

methodFunction

Bound ePay.js function that starts payment with this method.

Getting available Payment Method types
epay  .getSupportedPaymentMethodTypes()  .then(data => {    console.log('Supported Payment Methods:', data);  })  .catch(error => {    console.error('Error fetching supported payment methods:', error);  });/** Example:    {        "CARD": {            "name": "Card",            "url": "https://payments.epay.eu/assets/images/payment-options/credit-card.svg",            "method": fn(),        },        "VIPPS_MOBILEPAY": {            "name": "Vipps MobilePay",            "url": "https://payments.epay.eu/assets/images/payment-options/mobile-pay.svg"            "method": fn(),        },        "APPLE_PAY": {            "name": "ApplePay",            "url": "https://payments.epay.eu/assets/images/payment-options/apple-pay.svg"            "method": fn(),        }    }*/

Create transaction createTransaction(options)

This method creates a transaction with Promise<void> initiation semantics. Use callbacks to observe the transaction result. The options are similar to those used with epay.setPaymentOptions(). In addition, include paymentMethodId to initiate a card-on-file payment using stored card details.

The options passed into epay.createTransaction() are merged with any options that were previously set using epay.setPaymentOptions().

Adding the paymentMethodId key in the options will trigger a card-on-file using the stored card data.

Create transaction
epay  .createTransaction({    amount: 10000,        // Set the amount (e.g., 100.00 in minor units)    store: true,          // Option to store the card for card-on-file    paymentMethodId: 'stored-card-id' // Card-on-file using a stored card  });

Cancel transaction cancelTransaction()

This method cancels any current transaction for the session. It is only possible to cancel a transaction before any operations attempts, such as authorizations, has begun.

This can be useful for merchants implementing surcharge confirmation dialogs, where this method can be used to cancel the transaction if a cardholder does not wish to confirm the surcharge.

Cancel Transaction
epay.cancelTransaction()

Process transaction process()

If a transaction processing is halted for any reason, such as a surcharge confirmation, the transaction processing can be resumed by calling epay.process(). This method is typically not needed to implement, unless your implementation pauses processing midway.

Cancel Transaction
epay.process()

Delete stored Payment Method deleteStoredPaymentMethod(paymentMethodId)

This method allows the customer to delete a stored card via the frontend. Once a stored payment method is deleted, it can no longer be used for card-on-file.

This action is typically initiated by the customer and ensures that their stored card data is removed from future transactions (e.g., card-on-file).

Returns Promise<{}> when the stored payment method was deleted.

Delete stored payment method
epay  .deleteStoredPaymentMethod(paymentMethodId)  .then((response) => {    console.log("Stored payment method deleted successfully:", response);  })  .catch((error) => {    console.error("Error deleting stored payment method:", error);  });

Calculate fee for stored payment method calculateStoredPaymentMethodFee()

This method calculates the fee for a specific stored payment method (such as a saved card).

It requires a paymentMethodId, which can be obtained from a previously retrieved paymentMethod object using epay.getStoredPaymentMethods().

If request is not provided or does not include an amount, the default amount from the current session will be used.

This method is useful if you want to show the expected transaction fee to your users before initiating a payment.

Returns Promise<{ fee: number }>, where fee is in minor currency units.

calculateStoredPaymentMethodFee
paymentMethodIdString

ID of the stored payment method.

requestObject (optional)

Optional request payload used when you want to calculate the fee with a specific amount.

Supports amount, where the amount is provided in the smallest currency unit (e.g. 100 = 1.00).
Calculate fee for stored payment method
epay  .calculateStoredPaymentMethodFee("0295ec1b-a6b0-7701-8050-31b0add07282")  .then(({ fee }) => {    console.log("Calculated Fee (default amount):", fee);  })  .catch((error) => {    console.error("Error calculating fee:", error);  });

Start age verification startAgeVerification()

This method initiates the age verification process.

If neither URL is provided, the current window location is used as the fallback.

The client redirects through the standard clientRedirect callback flow.

startAgeVerification
successUrlString (optional)

URL to redirect to upon successful verification.

failureUrlString (optional)

URL to redirect to if verification fails.

Start age verification
epay.startAgeVerification({  successUrl: "https://xyz.com",  failureUrl: "https://zyz.com",});

Get a shopper message getClientMessage(request?)

Fetches the client message associated with the current session, for example after a failed payment attempt. The request may provide ePayCode and lang; by default the client reads ePayCode from the current URL and uses the selected hosted-fields language.

Response — Promise<ClientMessage>
rawMessageString | null

The message text returned by ePay.

domElementHTMLDivElement | null

A DOM element built from the message, preserving line breaks and bold text.

Display a client message
const message = await epay.getClientMessage();if (message.domElement) {  document.querySelector("#payment-message").replaceChildren(message.domElement);}

Get Google Pay payment data getGooglePayPaymentData(merchantId?, paymentOptions?)

Returns Promise for isReadyToPay and loadPaymentData.

allowedCardNetworks is derived from the current session. merchantId is assigned by Google and can be supplied explicitly; otherwise the session's Google Pay configuration is used. paymentOptions supports the same amount override used for transactions.

getGooglePayPaymentData
merchantIdString (optional)

Explicit merchantId to send to Google Pay. If omitted, the id is taken from the merchant configuration.

paymentOptionsPaymentOptions (optional)

Per-request payment options. Use `amount` to override the dynamic amount.

responsePaymentDataRequest

Google Pay request with `allowedPaymentMethods`, `transactionInfo`, `merchantInfo`, and `callbackIntents`.

Get payment data for request
epay.getGooglePayPaymentData("ASDF1234");

Get readiness request getGooglePayIsReadyToPayRequest()

Returns Promise* for Google Pay's isReadyToPay() method. Its allowed card networks are derived from the current session.

Response — Promise<IsReadyToPayRequest>
apiVersion / apiVersionMinorNumber

Google Pay API version values: `2` and `0`.

allowedPaymentMethodsArray

A CARD payment-method definition with supported authentication methods and card networks.

Check whether Google Pay is ready
const request = await epay.getGooglePayIsReadyToPayRequest();const result = await googlePayClient.isReadyToPay(request);

Get networks supported by Google Pay getGooglePaySupportedNetworks()

Returns Promise<string[]>: card networks available on the current session and supported by Google Pay.

Get networks supported by Google Pay
epay.getGooglePaySupportedNetworks();

Get Google Pay client getGooglePaymentsClient(options?, paymentOptions?)

Returns Promise<google.payments.api.PaymentsClient>. Use it only for a custom Google Pay integration; for the standard integration, use mountGooglePayButton().

For Google Pay SDK loading, button setup, and custom-flow guidance, see the Google Pay integration guide.

Get Google Pay client
epay.getGooglePaymentsClient();

Mount Google Pay button mountGooglePayButton(id, options?, merchantId?, paymentOptions?)

Creates and appends the official Google Pay button to the element identified by id. Returns Promise<void>.

options is passed to Google's button factory. merchantId overrides the configured Google merchant ID. paymentOptions supplies per-payment options, such as a dynamic amount.

See the Google Pay integration guide for SDK loading and the recommended setup.

Mount Google Pay button
epay.mountGooglePayButton("googlePayContainer", {  buttonColor: "black",  buttonType: "buy",  buttonRadius: 48,  buttonSizeMode: "fill",});