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.
Please note, that the ePay client needs to be fetched each time a new payment session is initialized and therefore can't be cached.
{
"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.
<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.
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.
paymentCancel​
Dispatched on end user payment cancel for supported payment methods like ApplePay.
confirmSurcharge​
Dispatched if a surcharge / fee is added to the transaction.
If you wish to display a surcharge confirmation UI. Make sure to return false in your event handler, as the transaction will otherwise continue, without waiting for cardholder consent.
Call epay.process() to continue the transaction or epay.cancelTransaction() to cancel it.
error​
Dispatched on any error not covered by other events.
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.
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 Blocks will be mounted.
In addition to specifying the container, you pass a configuration object that controls several aspects:
themelanguagefieldsvariables
The configuration object is optional.
Theme theme​
Determines the overall style of the payment fields in Blocks (for example, "default" provides an ePay-inspired look).
Themes​
| Name | Description |
|---|---|
default | The default ePay inspired styling. |
Language language​
Optionally sets the language for labels and messages.
Languages​
| Name | Description |
|---|---|
dk | Danish |
en | English |
sv | Swedish |
no | Norwegian |
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 the following options:
| Variable | Description |
|---|---|
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 |
showBrandSelectorEU 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.
Styling Variables variables​
Allows you to customize visual aspects such as text color, border radius, fonts, spacing, and more.
General​
| Variable | Description |
|---|---|
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)​
| Variable | Description |
|---|---|
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​
| Variable | Description |
|---|---|
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​
| Variable | Description |
|---|---|
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​
| Variable | Description |
|---|---|
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​
| Variable | Description |
|---|---|
colorDanger | The color used to indicate problems or input validation errors. |
colorPrimary | The primary theme color for the payment fields. |
<div id="fields"></div>
epay.mountFields("fields", {
// 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.
This method takes a single parameter:
- id: The same container identifier (e.g.
fields) used when callingepay.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.
epay.clearFields("fields");
Adding a payment button​
This button must call the appropriate payment method initialization method:
| Method | Description |
|---|---|
epay.createCardTransaction() | Initializes and begins processing of a card (Blocks) 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. |
epay.createGooglePayTransaction() | Initializes and begins processing of a GooglePay based payment. |
epay.createAnydayTransaction() | Initializes and begins processing of a Anyday based payment. |
epay.createViabillTransaction() | Initializes and begins processing of a Viabill based payment. |
epay.createSwishTransaction() | Initializes and begins processing of a Swish based payment. |
As the payment is processing JavaScript events will be notified to the function described in the JavaScript events section
To comply with Apple Pay, Vipps MobilePay, and Google Pay terms and conditions, you must use their respective buttons.
<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.
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.
To enable this functionality, you must also set a customerId when initializing the payment session.
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.
epay.getStoredPaymentMethods()
.then(data => {
console.log('Stored Payment Methods:', data.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 a list of object with the following keys:
- name: The name of the payment method (Not static)
- url: Url to a payment method logo
- method: Reference to the method to call, to initialize a payment of this type
To uniquely identify a payment method, merchant should refer to the key of the object and not the name property.
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 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.
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);
});
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.
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.
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).
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).
- amount: The amount to calculate the fee for, in the smallest currency unit (e.g.
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.
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.
epay.startAgeVerification({
successUrl: "https://xyz.com",
failureUrl: "https://zyz.com",
});
Get payment data for request getGooglePayPaymentData(merchantId)​
Returns object for request to isReadyToPay and loadPaymentData
allowedCardNetworks - in the returned data - is based on what is available on the current session.
Optional parameter merchantId to explicit specify the merchantId to be sent to Google Pay - if omitted, the id is taken from the merchant configuration.
The merchantId is assigned by Google and available in the Google Pay & Wallet Console
epay.getGooglePayPaymentData("ASDF1234");
Get networks supported by Google Pay getGooglePaySupportedNetworks()​
Returns list of card networks available on the current session and supported by Google Pay.
epay.getGooglePaySupportedNetworks();
Get Google Pay client getGooglePaymentsClient(options)​
Returns Google Pay client to call Google Pay endpoint.
epay.getGooglePaymentsClient();
Mount Google Pay button mountGooglePayButton(id, options, merchantId)​
Add the Google Pay button to layout at the specified element
epay.mountGooglePayButton("googlePayContainer", {
buttonColor: "black",
buttonType: "buy",
buttonRadius: 48,
buttonSizeMode: "fill",
});