npm.io
1.1.0 • Published 1 month ago

euplatesc

Licence
MIT
Version
1.1.0
Deps
0
Size
185 kB
Vulns
0
Weekly
0
Stars
17

EuPlătesc Node.js API Library

The EuPlătesc Node Library provides access to the entire EuPlătesc API from applications written in server-side JavaScript.

IMPORTANT: To use this package, you need to ask and apply for an account on the EuPlătesc website. After signing a contract with EuPlătesc, you will receive credentials for accessing the API.

Table of Contents

  1. Table of contents
  2. Getting started
  3. Installation
  4. Usage
  5. API
  6. Test cards
  7. Built with
  8. License

Getting started

This package is the result of my passion and openness to open-source software. I had to implement this service many times in my projects, and almost every time, I had to deal with a headache due to the poor documentation and the non-standard "REST API" provided by EuPlătesc.

This package covers all the actions provided in the EuPlătesc documentation. It can be used either as a CommonJS or ES module, and it has no runtime dependencies - it builds on the fetch and FormData globals, so it requires Node 18 or newer.

Installation

Using npm:

$ npm install euplatesc

Using yarn:

$ yarn add euplatesc

Usage

Create a client file and instantiate the EuPlătesc class:

// ./src/lib/epClient.js
import { EuPlatesc } from 'euplatesc';

export default epClient = new EuPlatesc({
  merchantId: process.env.EUPLATESC_MERCHANT_ID,
  secretKey: process.env.EUPLATESC_SECRET_KEY
});

Import the client and call the methods you need:

// ./src/index.js
import epClient from './lib/epClient';

epClient.checkMid().then((midInfo) => console.log(midInfo));

// Also it can be used with async-await:
// await epClient.checkMid()

API

Constructor

import { EuPlatesc } from 'euplatesc';

const epClient = new EuPlatesc({
  merchantId: process.env.EUPLATESC_MERCHANT_ID,
  secretKey: process.env.EUPLATESC_SECRET_KEY,
  testMode: 'true' === process.env.EUPLATESC_TEST_MODE,
  userKey: process.env.EUPLATESC_USER_KEY,
  userApi: process.env.EUPLATESC_USER_API
});

The merchant ID (MID) and the secret key (KEY) can be found at EuPlătesc Panel > Integrations parameters.

The user key (UKEY) and the user API (UAPI) are optional for some methods, but required for others - these methods are indicated with a notice. These credentials can be found at EuPlătesc Panel > Settings > User settings > Account permissions.

Parameter list
Field Type Description
merchantId * string The merchant ID.
secretKey * string The secret key.
testMode boolean Optional. Whether the module is in test mode or not. Default: false.
userKey string Optional. The user key
userApi string Optional. The user API.
timeout number Optional. HTTP request timeout, in milliseconds. Default: 30000.

* Required field.

paymentUrl

Generate EuPlătesc payment URL.

import epClient from './lib/epClient';

const data = {
  amount: 12.34,
  currency: 'USD',
  invoiceId: 'invoice id',
  orderDescription: 'The description of the order'
};

console.log(epClient.paymentUrl(data));
Parameter list
Field Type Description
amount * number
currency * 'RON' | 'EUR' | 'USD' | 'HUF' | 'MDL' | 'BGN' | 'GBP' | 'PLN'
invoiceId * string
orderDescription * string
frequency { days: number; expiresAt?: Date } Marks the order as the Base transaction of a recurring chain. expiresAt defaults to one year from now.
baseEpId string The ep_id of the initial Base transaction. Required for merchant-initiated subsequent recurring transactions.
recurrentType 'Base' | 'Recurent' | 'Recurent2CIT' Defaults to Base when frequency is set, and to Recurent when only baseEpId is set.
billingFirstName string
billingLastName string
billingCompany string Billing company name.
billingAddress string Billing (company) address.
billingCity string Billing (company) city.
billingState string Billing (company) county.
billingZip string Billing (company) ZIP code.
billingCountry string Billing (company) country.
billingPhone string Billing (company) phone number.
billingEmail string Billing (company) email address.
shippingFirstName string
shippingLastName string
shippingCompany string Company data.
shippingAddress string
shippingCity string
shippingState string
shippingZip string
shippingCountry string
shippingPhone string
shippingEmail string
Extra string Additional information sent by the merchant to the gateway. This data is echoed back to the merchant in the reply request.
silentUrl string Callback URL (server to server POST request).
silentUrlSec string SecStatus callback URL (server to server POST request).
successUrl string URL to redirect the client in case of a successful transaction.
failedUrl string URL to redirect the client in case of a failed transaction.
epTarget string "self" for the case of using iframe.
epMethod 'post' | 'get' | 'getclean' Method used for the succes/fail redirect. getclean keeps the original query params.
backToSite string URL to redirect the client when clicking back to the site button or after 60 seconds on the result page.
backToSiteMethod string "post" or "get" for the back-to-site button.
expireUrl string If a timer is set on the payment page, you can change the URL to which the client will be redirected when the timer reaches 0.
rate string Installments number. Format: [bank_code]-[installments_no].
filterRate string Installments number. Format: [bank_code1]-[i_no1]-...-[i_noN],[bank_code2]-[i_no1]-...-[i_no2]. Ex: apb-3-4,btrl-5-6
channel string Filter the available payment channels. Any combination of CC, OP, C2P, GPAY, APAY, TBI, paypo, comma-separated.
generateEpId string If specified and have value 1, instead of redirecting the client will return a JSON containing the URL of the payment page.
validateCc boolean Allow card validation with an amount of 0.
valability Date Payment link available until the specified timestamp.
c2pId string Unique ID of the client used for C2P wallet, blank values disable the wallet.
c2pCid string Unique ID of the enrolled card used for C2P wallet.
lang 'ro' | 'en' | 'fr' | 'de' | 'it' | 'es' | 'hu' Preselect the language of the payment page. If not sent, the language will be chosen based on the client's IP.

* required fields

Return

Example:

{
  paymentUrl: 'https://secure.euplatesc.ro/tdsprocess/tranzactd.php?amount=...';
}

The returned URL will redirect the user to a secure EuPlătesc payment page.

Type:

{
  paymentUrl: string;
}

paymentParams

Build the full field set posted to the gateway, without wrapping it into a URL.

Use it when you need to POST the fields yourself. That is the only supported way to run a subsequent recurring transaction, since that call is made server to server, without the customer being present.

import epClient from './lib/epClient';

const fields = epClient.paymentParams({
  amount: 12.34,
  currency: 'RON',
  invoiceId: 'invoice id',
  orderDescription: 'Recurent payment',
  baseEpId: '15F124618DA2E299CBEFA787A09464352946F422' // implies recurrentType: 'Recurent'
});

await fetch('https://secure.euplatesc.ro/tdsprocess/tranzactd.php', {
  method: 'POST',
  body: new URLSearchParams(fields)
});

It takes the same parameters as paymentUrl and returns a Record<string, string>.

Recurring payments come in two parts. The initial (enrolling) transaction carries frequency and is sent as recurent=Base; the merchant redirects the customer to it like any other payment. Subsequent transactions carry baseEpId and are sent as recurent=Recurent (or Recurent2CIT for a 3-D Secure one). Depending on how your merchant account is configured, EuPlătesc may initiate the subsequent transactions on its own cron jobs, in which case you never have to send them.

checkResponse

Check the backward response received by the EuPlătesc POST request.

This logic should be used as a callback in an API endpoint that processes a POST request from the EuPlătesc server.

import epClient from './lib/epClient';

// The data below should be passed from a POST request from EuPlătesc server after a payment is made.
const params = {
  amount: '',
  currency: '',
  invoiceId: '',
  epId: '',
  merchantId: '',
  action: '',
  message: '',
  approval: '',
  timestamp: '',
  nonce: '',
  fpHash: ''
};

console.log(epClient.checkResponse(params));

Reply to the EuPlătesc server with the plain text OK, otherwise the request may be retried.

Parameter list
Field Type Description
amount string The made transaction's amount.
currency 'RON' | 'EUR' | 'USD' | 'HUF' | 'MDL' | 'BGN' | 'GBP' | 'PLN' The made transaction's currency.
invoiceId string The made transaction's invoice ID.
epId string The made transaction's ep ID.
merchantId string The made transaction's merchant ID.
action string The made transaction's action.
message string The made transaction's message.
approval string The made transaction's approval value.
timestamp string The made transaction's timestamp.
nonce string The made transaction's nonce.
fpHash string The made transaction's hash.
Additional response fields

These are only sent when you enable them for the MID, in the EuPlătesc panel. They take part in the hash, so pass exactly the ones you received - an extra or a missing one makes the check return invalid.

Field Type Description
secStatus string Additional security info.
rrn string Code generated by the bank, shown on the customer's bank statement.
mcard string Last 4 digits of the used card.
cardExp string Expiration date of the used card. Format: YYmm.
discountAmount string Applied discount.
paymentChannel string CARD, GPay, ApplePay, C2P, OP, SMS or TBI.
cardType string Visa, Mastercard or Maestro.
bin string First 6 digits of the used card.
rate string Installments number. Format: X rate BANK, ex: 6 rate BTRL.
cardHolder string Name on the used card.
email string Email of the customer.
rtype string Transaction type: Normal, Base or Recurent.
cce string Unique ID of the PAN.
Return

Example:

// ResponseResult
{ success: true, response: 'complete' }

Type:

type ResponseResult = {
  success: boolean;
  response: 'complete' | 'failed' | 'invalid';
};

getStatus

Get the status of a transaction.

import epClient from './lib/epClient';

const params = {
  epId: '15F124618DA2E299CBEFA787A09464352946F422'
  // invoiceId: 'FPS12145601'
};

console.log(await epClient.getStatus(params));
Parameter list
Field Type Description
epId string The ID of the transaction.
invoiceId string The ID of the transaction's invoice.

You have to pass either epId or invoiceId as a param object to get the status. If both are passed, the epId field has priority.

Return

Example:

{
  success: `[{merch_id: "4484xxxxxxxxx", invoice_id: "00000", ep_id:"0000000000000000000000000000000000000000", action: "0", message: "Approved", captured: "0", refunded: "0", masked_card: "444444xxxxxx4444", card_expire: "mm-yy", name_on_card: "Test", email: "test@test.com", timestamp: "2014-11-26 10:11:48", tran_type: "Normal", recurent_exp: "", recurent_cancel_date: "" }]`;
}

Type:

{ success: string | TransactionStatus[] } | { error: string; ecode?: string }

Merchant accounts set to the newer response format (v=1.2) get an already parsed array of TransactionStatus objects, carrying extra fields such as captured_amount, approval or channel. The others get the legacy JSON string above.

printTransaction

Get the transaction receipt as a base64 encoded PDF.

import epClient from './lib/epClient';

const epId = '15F124618DA2E299CBEFA787A09464352946F422';
const result = await epClient.printTransaction(epId);

if ('success' in result) {
  await fs.writeFile('receipt.pdf', Buffer.from(result.file, 'base64'));
}
Parameter list
Field Type Description
epId string The EPID of the transaction.
Return

Example:

{
  success: '1',
  file: 'JVBERi0xLjQK...' // base64 encoded PDF
}

Type:

{ success: string; file: string } | { error: string; ecode?: string }

capture

Capture a transaction.

IMPORTANT: For using this method, in addition to merchant ID and secret key in the EuPlătesc client instantiation you should pass both userKey and userApi, too.

import epClient from './lib/epClient';

const epId = '15F124618DA2E299CBEFA787A09464352946F422';
console.log(await epClient.capture(epId));
Parameter list
Field Type Description
epId string The ID of the transaction.
Return

Example:

{
  success: '1';
}

Type:

{ success: string } | { error: string; ecode: string }

reversal

Reversal of a transaction.

IMPORTANT: For using this method, in addition to merchant ID and secret key in the EuPlătesc client instantiation you should pass both userKey and userApi, too.

import epClient from './lib/epClient';

const epId = '15F124618DA2E299CBEFA787A09464352946F422';
console.log(await epClient.reversal(epId));
Parameter list
Field Type Description
epId string The ID of the transaction.
Return

Example:

{
  success: '1';
}

Type:

{ success: string } | { error: string; ecode: string }

partialCapture

Partial capture of a transaction.

IMPORTANT: For using this method, in addition to merchant ID and secret key in the EuPlătesc client instantiation you should pass both userKey and userApi, too.

import epClient from './lib/epClient';

const epId = '15F124618DA2E299CBEFA787A09464352946F422';
const amount = 123.78;

console.log(await epClient.partialCapture(epId, amount));
Parameter list
Field Type Description
epId string The ID of the transaction.
amount number Partially captured amount.
Return

Example:

{
  success: '1';
}

Type:

{ success: string } | { error?: string; message?: string; ecode: string }

refund

(Partial) Refund a transaction.

IMPORTANT: For using this method, in addition to merchant ID and secret key in the EuPlătesc client instantiation you should pass both userKey and userApi, too.

import epClient from './lib/epClient';

const epId = '15F124618DA2E299CBEFA787A09464352946F422';
const amount = 123.78;
const reason = 'Refund reason.';

console.log(await epClient.refund(epId, amount, reason));
Parameter list
Field Type Description
epId string The ID of the transaction.
amount number The refunded amount. It can be smaller than the total amount of the transaction.
reason string Optional. The reason, the transaction is to be refunded.
Return

Example:

{
  success: '1';
}

Type:

{ success: string } | { error?: string; message?: string; ecode: string }

cancelRecurring

Cancel a recurring transaction.

IMPORTANT: For using this method, in addition to merchant ID and secret key in the EuPlătesc client instantiation you should pass both userKey and userApi, too.

import epClient from './lib/epClient';

const epId = '15F124618DA2E299CBEFA787A09464352946F422';
const reason = 'The user asked to cancel this recurrent transaction.';

console.log(await epClient.cancelRecurring(epId, reason));
Parameter list
Field Type Description
epId string The ID of the transaction.
reason string Optional. The reason, the recurring transaction is to be canceled.
Return

Example:

{
  success: '<base EPID>';
}

Type:

{ success: string } | { error?: string; message?: string; ecode: string }

updateInvoiceId

Update the invoice ID of a transaction.

IMPORTANT: For using this method, in addition to merchant ID and secret key in the EuPlătesc client instantiation you should pass both userKey and userApi, too.

import epClient from './lib/epClient';

const epId = '15F124618DA2E299CBEFA787A09464352946F422';
const newInvoiceId = 'INV-0075';

console.log(await epClient.updateInvoiceId(epId, newInvoiceId));
Parameter list
Field Type Description
epId string The ID of transaction invoice ID is to be updated.
newInvoiceId string The new invoice ID is to be updated.
Return

Example:

{
  success: '1';
}

Type:

{ success: string } | { error: string }

getInvoiceList

Get invoice list.

IMPORTANT: For using this method, in addition to merchant ID and secret key in the EuPlătesc client instantiation you should pass both userKey and userApi, too.

import epClient from './lib/epClient';

const from = new Date('2022-08-24');
const to = new Date('2022-09-14');

console.log(await epClient.getInvoiceList({ from, to }));
Parameter list
Field Type Description
from Date Optional. The date from which the filter starts to search invoices.
to Date Optional. The date to which the filter ends to search invoices.

If from and to are sent empty, it will look for invoices from the last three months. It returns max 100 records.

Return

Example:

// { success: Invoice[] } | { error: string }
{
  success: [
    {
      invoice_number: '',
      invoice_date: '',
      invoice_amount_novat: '',
      invoice_amount_vat: '',
      invoice_currency: '',
      transactions_number: '',
      transactions_amount: '',
      transferred_amount: ''
    }
  ];
}

Type:

type Invoice = {
  invoice_number: string;
  invoice_date: string;
  invoice_amount_novat: string;
  invoice_amount_vat: string;
  invoice_currency: 'RON' | 'EUR' | 'USD';
  transactions_number: string;
  transactions_amount: string;
  transferred_amount: string;
};

getInvoiceTransactions

Get invoice transaction list.

IMPORTANT: For using this method, in addition to merchant ID and secret key in the EuPlătesc client instantiation you should pass both userKey and userApi, too.

import epClient from './lib/epClient';

const invoice = 'FPSxxxxxxxx';

console.log(await epClient.getInvoiceTransactions(invoice));
Parameter list
Field Type Description
invoice string Settlement invoice number.
Return

Example:

// { success: InvoiceTransaction[] } | { error: string }
{
  success: [{
    mid: string;
    invoice_id: string;
    epid: string;
    rrn: string;
    amount: string;
    currency: string;
    commission: string;
    installments: string;
    type: 'capture' | 'refund' | 'chargeback';
  }]
}

Type:

type InvoiceTransaction = {
  mid: string;
  invoice_id: string;
  epid: string;
  rrn: string;
  amount: string;
  currency: string;
  commission: string;
  installments: string;
  type: 'capture' | 'refund' | 'chargeback';
};

getCapturedTotal

Get captured total.

IMPORTANT: For using this method, in addition to merchant ID and secret key in the EuPlătesc client instantiation you should pass both userKey and userApi, too.

import epClient from './lib/epClient';

const params = {
  mids: '4484xxxxxxxxx,4484xxxxxxxxx', // or just "4484xxxxxxxxx"
  from: new Date('2022-02-13'),
  to: new Date('2022-03-22')
};

console.log(await epClient.getCapturedTotal(params));
Parameter list
Field Type Description
mids string Optional. Separated merchant IDs by commas. If empty, it will set up the merchant ID from client initialization.
from Date Optional. The date from which the filter starts to search totals.
to Date Optional. The date to which the filter ends to search totals.

If from and to are empty, it will look for the total in the last month.

Return

Example:

// { success: CapturedTotal } | { error: string }
{
  success: {
    EUR: "xxx",
    GBP: "xxx",
    RON: "xxx",
    USD: "xxx"
  }
}

Type:

type CapturedTotal = {
  EUR?: string;
  GBP?: string;
  RON?: string;
  USD?: string;
};

getTransactionList

Get the transaction list.

import epClient from './lib/epClient';

const params = {
  from: new Date('2021-01-01'),
  to: new Date('2021-06-01'),
  status: 'success',
  limit: 100
};

console.log(await epClient.getTransactionList(params));
Parameter list
Field Type Description
mid string Optional. Merchant ID. If empty, it will set up the merchant ID from client initialization.
from Date Optional. The date from which the filter starts to search transactions.
to Date Optional. The date to which the filter ends to search transactions.
by 'complete' | 'auth' | 'capture' | 'refund' | 'recurent_cancel' Optional. The date field the interval applies to. Default: complete.
status 'all' | 'success' | 'fail' | 'captured' | 'notcaptured' | 'refunded' | 'base' | 'recurent' Optional. Transaction status filter. Default: all.
limit number Optional. Number of returned records, 1-5000. Default: 5000.
page number Optional. Result page, 1-based. Default: 1.

The searched interval cannot be longer than one year.

Return

Type:

{ success: string | TransactionStatus[] } | { error: string; ecode?: string }

getCardArt

Get card art data.

IMPORTANT: For using this method, in addition to merchant ID and secret key in the EuPlătesc client instantiation you should pass both userKey and userApi, too.

import epClient from './lib/epClient';

const epId = '15F124618DA2E299CBEFA787A09464352946F422';

console.log(await epClient.getCardArt(epId));
Parameter list
Field Type Description
epId string The EPID of the transaction.
Return

Example:

// CardArt | { error: string; ecode?: string }
{
  bin: "4xxxxx",
  last4: "xxxx",
  exp: "yymm",
  cardart: "*BASE64 ENCODED IMAGE*"
}

Type:

type CardArt = {
  bin: string;
  last4: string;
  exp: string;
  cardart: string;
};

getSavedCards

Get saved cards of a customer.

import epClient from './lib/epClient';

const clientId = '1';
const mid = '4484xxxxxxxxx';

console.log(await epClient.getSavedCards(clientId, mid));
Parameter list
Field Type Description
clientId string The ID of the client.
mid string Optional. Merchant ID. If empty, it will set up the merchant ID from client initialization.
Return

Example:

// { cards: SavedCard[] } | { error: string; ecode: string }
{
  cards: [
    {
      id: 'xxxxxx',
      bin: '479032',
      last4: '4512',
      mask: '479032xxxxxx4512',
      exp: '23-10',
      cardart:
        'https://secure.euplatesc.ro/tdsprocess/images/ca8_small/1698962c052c3c6e40468363636304b23070222638c5f7071d415372b5119ba6.jpg'
    }
  ];
}

Type:

type SavedCard = {
  id: string;
  bin: string;
  last4: string;
  mask: string;
  exp: string;
  cardart: string;
};

removeCard

Remove a saved card of a customer.

import epClient from './lib/epClient';

const clientId = '1';
const cardId = '234';
const mid = '4484xxxxxxxxx';

console.log(await epClient.removeCard(clientId, cardId, mid));
Parameter list
Field Type Description
clientId string The ID of the client.
cardId string The ID of the card.
mid string Optional. Merchant ID. If empty, it will set up the merchant ID from client initialization.
Return

Example:

{
  success: '1';
}

Type:

{ success: string } | { error: string; ecode: string }

checkMid

Check a merchant ID.

import epClient from './lib/epClient';

const mid = '4484xxxxxxxxx';

console.log(await epClient.checkMid(mid));

// { success: "1" } or { error, ecode }
Parameter list
Field Type Description
mid string Optional. Merchant ID. If empty, it will se tup the merchant ID from client initialization.
Return

Example:

// Merchant | { error: string }
{
  name: "...",
  url: "...",
  cui: "...",
  j: "...",
  status: "test/live",
  recuring: "N/Y/YA",
  tpl: "tpl-v15/tpl-v17/tpl-v21",
  rate_mode: "C/EP",
  rate_apb: "6;12",
  rate_btrl: "2;3;4;5;6",
  rate_brdf: "3;6",
  rate_fbr: "2;3;4",
  rate_gbr: "",
  rate_rzb: "2;3;4;5;6;7;8;9;10;11;12;15;18;20;24"
}

Type:

type Merchant = {
  name: string;
  url: string;
  cui: string;
  j: string;
  status: string;
  recuring: string;
  tpl: string;
  rate_mode: string;
  rate_apb: string;
  rate_btrl: string;
  rate_brdf: string;
  rate_fbr: string;
  rate_gbr: string;
  rate_rzb: string;
};

Test cards

Card number Expire date CVC Name Result
4111111111111111 28/01 123 Test Approved
4444333322221111 28/01 123 Test Not sufficient funds
4000020000000000 28/01 123 Test Transaction declined
4400000000000008 28/01 123 Test Expired card
4607000000000009 28/01 123 Test Invalid response
4000640000000005 28/01 123 Test Approved
5454545454545454 28/01 123 Test Authentication failed
5555555555554444 28/01 123 Test Approved
2222400010000008 28/01 123 Test Transaction declined
2222400030000004 28/01 123 Test Expired card
5100060000000002 28/01 123 Test Invalid response
5500000000000004 28/01 123 Test Approved
4989882771777727 28/01 123 Test Approved
5500000000000012 28/01 123 Test Issuer unavailable
5500000000000020 28/01 123 Test System malfunction
5186001700008785 28/01 123 Test Approved
5186001700009726 28/01 123 Test Approved
5120350100064537 28/01 123 Test Approved
5120350100064545 28/01 123 Test Approved
2223001870064586 28/01 123 Test Approved
5204731620064595 28/01 123 Test Approved
4622943123103732 28/01 123 Test Approved
4622943123103740 28/01 123 Test Approved

These work only while the account is in test state. Test accounts also accept real cards in the test environment, so that you can exercise the processing terminal; for PSP customers the amount is capped at 1. Contact the EuPlătesc team if you need live card acceptance disabled in the test environment.

Built with

Nothing - the package has no runtime dependencies. It uses the fetch and FormData globals built into Node, so it needs Node 18 or newer.

License

MIT License

Keywords