Skip to main content

ePay.js reference

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.

info

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.

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

Initializing 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.

in the .setCallbacks method, you can set up event listeners to handle different events during the payment process. However, this is optional.

JavaScript events

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

Each javascript function takes in one parameter, which is an object of data.

Events
Notifications with information of the current transaction state

clientReady

Dispatched once the client has verified the session id and secret.

invalidSession

Dispatched if the client cannot verify the session id and secret.

challengeIssued

Dispatched before a client redirect to the challenge page. Return false to cancel follow-up events.

transactionAccepted

Dispatched on transaction success. Funds are guaranteed.

transactionDeclined

Dispatched on transaction rejection.

feeUpdated

Dispatched when the transaction fee is calculated

clientRedirect

Dispatched before any client redirect. Return false to cancel redirect behaviour.

invalidInput

Dispatched if the payment method input cannot be used for processing.

inputValidity

Dispatched on end user payment method input during validity checks.

inputSubmit

Dispatched on user submit by submitting the fields directly within the fields.

sessionExpired

Dispatched if the session has expired. Return false to cancel follow-up events.

error

Dispatched on any error not covered by other events.

info

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.

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,
error: errorCallback,
})
.init();

Mounting the fields mountFields

The mountFields method is used to integrate and display hosted payment fields into a specified container on your webpage.

After initializing the payment session, you call mountFields to embed the fields in a given HTML element and configure their appearance, behavior, and additional input options.

The method takes a container identifier (typically the ID of a <div> element. In our example we used fields as an ID) where the hosted fields will be mounted.

In addition to specifying the container, you pass a configuration object that controls several aspects:

  • theme
  • language
  • fields
  • variables
info

The configuration object is optional.

Theme theme

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

Themes

NameDescription
defaultThe default ePay inspired styling.

Language language

Optionally sets the language for labels and messages.

Languages

NameDescription
dkDanish
enEnglish
svSwedish
noNorwegian

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.

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

PAN field pan

The PAN field supports auto-focus, which is enabled by default. If needed, set focus to false to disable auto-focus.

Loader loader

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

Styling Variables variables

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

General

VariableDescription
colorTextThe font color of text, used for labels and input content.
borderRadiusThe border radius for inputs and the window.
borderColorThe default border color for inputs and the window.
fontFamilyThe font used for labels, input content, and placeholders.

Spacing between the input fields (horizontal and vertical)

VariableDescription
gridColumnSpacingHorizontal spacing between input fields in the grid layout.
gridRowSpacingVertical spacing between input fields in the grid layout.
gridTemplateColumnsDefines the column structure of the grid layout.

Displaying icons and brands

VariableDescription
iconDisplayControls the visibility of icons in the fields (e.g., block or none).
cardBrandDisplayControls the visibility of card brand icons (e.g., block or none).

Label elements

VariableDescription
labelColorThe font color for labels.
labelFontSizeThe font size for labels.
labelFontWeightThe font weight for labels.
labelMarginBottomThe spacing below labels.

Input elements

VariableDescription
inputColorThe font color for user input.
inputBorderRadiusThe border radius for input fields.
inputBorderColorThe border color for input fields.
inputFocusBorderColorThe border color when an input field is in focus.
inputFontSizeThe font size for input fields.
inputPaddingThe padding inside input fields.
inputPlaceholderColorThe font color for placeholder text in input fields.
inputBackgroundColorThe background color for input fields.
inputBoxShadowThe box shadow for input fields.
inputFocusBoxShadowThe box shadow for input fields when they are in focus.
windowPaddingThe padding around the window containing the hosted fields.
windowBackgroundColorThe background color of the window containing the hosted fields.
windowBorderStyleThe border style of the window containing the hosted fields.
windowBorderRadiusThe border radius of the window containing the hosted fields.
windowBorderColorThe border color of the window containing the hosted fields.

Color specific

VariableDescription
colorDangerThe color used to indicate problems or input validation errors.
colorPrimaryThe primary theme color for the hosted fields.
Element to mount fields to
<div id="fields"></div>
Mounting the fields
epay.mountFields("fields", {
// The configuration object is optional
theme: "default",
language: "da",
fields: {
name: { enabled: true, value: "" },
pan: { focus: true },
},
loader: {
backgroundColor: "transparent",
borderStyle: "none",
height: "150px",
},
variables: {
colorText: "#2e3033",
},
});

Clearing the fields clearFields

The clearFields method resets all input fields in the hosted fields 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.

This method takes a single parameter:

  • id: The same container identifier (e.g. fields) used when calling epay.mountFields(id).

You must pass the same id that was used to mount the fields using mountFields. If the ID does not match, the method will have no effect.

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

Adding a payment button

This button must call the appropriate payment method initialization method:

MethodDescription
epay.createCardTransaction()Initializes and begins processing of a card (hosted-fields) based payment.
epay.createVippsMobilePayTransaction()Initializes and begins processing of a Vipps-MobilePay based payment.
epay.createApplePayTransaction()Initializes and begins processing of a ApplePay based payment.

As the payment is processing JavaScript events will be notified to the function described in the JavaScript events section

warning

To be comply with ApplePay and MobilePays terms and conditions, you must use their respective buttons.

Payment button: Card (hosted-fields) 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.

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

Payment options

amount Number

Sets the payment amount when dynamic amount mode is enabled. The amount is typically provided in minor currency units (for example, 10000 might represent 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 can be obtained via a checkbox or similar method.

info

To enable this functionality, you must also set a customerId when initializing the payment session.

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.

info

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.

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

Create transaction createTransaction(options)

This method creates a transaction based on the provided options. The options are similar to those used with epay.setPaymentOptions(). In addition, you can include the key paymentMethodId to initiate a quick card-on-file 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
})
.then(response => {
console.log('Transaction created successfully:', response);
})
.catch(error => {
console.error('Transaction creation failed:', error);
});

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).

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().

It accepts the following parameters:

  • paymentMethodId: ID of the stored payment method (required).

  • request: An optional object that can include:

    • amount: The amount to calculate the fee for, in the smallest currency unit (e.g. 100 = 1.00).

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.

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. It accepts an options object with two optional parameters:

  • successUrl: URL to redirect to upon successful verification.
  • failureUrl: URL to redirect to if verification fails.

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

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