@decodeblock/nodejs-ercaspay

0.1.3 • Public • Published

Node.js Ercaspay Integration

License Latest Version Tests Status Total Downloads Contributors

A Node.js package for seamless integration with the Ercaspay API, providing utilities for encrypting card details, initiating payment transactions, and more.

Features

  • Card Encryption: Securely encrypt sensitive card details using a public key.
  • Transaction Initiation: Easily initiate payment transactions.
  • Logging Support: Includes customizable logging support with Winston.

Requirement

Installation

Install the package using npm:

npm install @decodeblock/nodejs-ercaspay

Usage

Setting Up the Client

First, import the package and initialize the client with your configurations.

const Ercaspay = require('@decodeblock/nodejs-ercaspay');

const ercaspay = new Ercaspay({
  baseUrl: 'https://api.ercaspay.com', // Base URL of the API
  secretKey: 'your-key', // Secret key from Ercaspay
  logger: logger // (optional) your winston instance (default output: ercaspay-client.log default log level: 'info')
});

Initiating a Payment Transaction

Send payment details to initiate a transaction.

  const transactionData ={
    amount: '100',
    paymentReference: ercaspay.generatePaymentReferenceUuid(),
    paymentMethods: 'card,bank-transfer,ussd',
    customerName: 'John Doe',
    customerEmail: 'johndoe@gmail.com',
    currency: 'NGN',
    customerPhoneNumber: '09061626364',
    redirectUrl: 'https://omolabakeventures.com',
    description: 'The description for this payment goes here',
    feeBearer: 'customer',
    metadata: {
        firstname: 'Ola',
        lastname: 'Benson',
        email: 'iie@mail.com',
    }
  }
  try {
    const response = await ercaspay.initiateTransaction(transactionData);

    console.log('Transaction Response:', response);
  } catch (error) {
    console.error('Error initiating transaction:', error.responseData || error.message);
  }

Initiating Card Transaction

try {
  const response = await ercaspay.initiateCardTransaction({
    request: req, // The request object of any Node.js framework being used (eg: Express.js)
    transactionRef:'ERCS|20241214202721|1734204441927',
    cardCvv: '111',
    cardNumber: '252435456456756756756787865',
    cardExpiryMonth: '12',
    cardExpiryYear: '2025',
    cardPin: '1234',
  });

  res.status(200).json({
    success: true,
    message: 'Transaction initiated successfully',
    data: response,
  });
} catch (error) {
  console.error('Error initiating transaction:', error);
  res.status(error.statusCode).json({
    success: false,
    message: 'Failed to initiate transaction',
    error: error.message,
  });
}

Configuration

  • baseUrl: The base URL of the Ercaspay API.
  • secretKey: The Secret key for authenticating requests.
  • logger: Custom logger instance (e.g., Winston) for logging requests and errors.

Error Handling

The package throws errors in cases like:

  • API response errors.

Example of handling errors:

try {
  const response = await ercaspay.initiateTransaction(data);
} catch (error) {
  console.error('Error:', error.responseData || error.message);
}

Logging

This package provides logging capabilities with winston to help you monitor and troubleshoot API interactions and errors. By default, important information about API requests, responses, and exceptions is logged, which can be useful for debugging and keeping track of system behavior.

What is Logged?

The package logs the following information:

1. API Request Details:

  • URL of the API endpoint
  • HTTP method (GET, POST, etc.)

2. API Response Details:

  • HTTP status code of the response
  • Response body (if available)
  • Error messages (for failed requests)

3. Exceptions:

  • Details of exceptions, including client and server errors
  • Stack trace and error context for easier debugging

Configuring custom Logger

import Ercaspay from '@decodeblock/nodejs-ercaspay';
import winston from 'winston';

// Create a logger instance
const logger = winston.createLogger({
    level: 'info',  // Default log level
    format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.printf(({ timestamp, level, message, ...metadata }) => {
            return `${timestamp} [${level}]: ${message} ${Object.keys(metadata).length ? JSON.stringify(metadata) : ''}`;
        })
    ),
    transports: [
        new winston.transports.Console(),  // Log to the console
        new winston.transports.File({ filename: 'app.log' }),  // Log to a file
    ],
});

// Initialize your Ercaspay client
const ercaspay = new Ercaspay({
  baseUrl: 'https://api.ercaspay.com', // Base URL of the API
  secretKey: 'your-key', // Secret key from Ercaspay
  logger: logger, // Replace with your secret key
});

Available Methods

Method Name Description
initiateTransaction(data) Initiates a new payment transaction.
verifyTransaction(transactionRef) Verifies the status of a transaction.
initiateBankTransfer(transactionRef) Initiates a bank transfer transaction.
initiateUssdTransaction(transactionRef, bankName) Initiates a USSD transaction.
getBankListForUssd() Retrieves a list of banks supporting USSD payments.
generatePaymentReferenceUuid() Generates a unique payment reference UUID.
fetchTransactionDetails(transactionRef) Fetches details of a specific transaction.
fetchTransactionStatus(transactionRef, paymentReference, paymentMethod) Fetches the status of a transaction.
cancelTransaction(transactionRef) Cancels a transaction.
initiateCardTransaction({params}) Initiates a card payment transaction.
submitCardOTP(transactionRef, paymentReference, otp) Submits OTP for a card transaction.
resendCardOTP(transactionRef, paymentReference) Requests OTP resend for a card transaction.
getCardDetails(transactionRef) Retrieves saved card details for a transaction.
verifyCardTransaction(transactionRef) Verifies a card transaction.

Changelog

Detailed changes for each release are documented in the CHANGELOG.


Contributing

Contributions are welcome! Please see the CONTRIBUTING guide for details.


Credits


License

This project is licensed under the MIT License.

Package Sidebar

Install

npm i @decodeblock/nodejs-ercaspay

Weekly Downloads

60

Version

0.1.3

License

MIT

Unpacked Size

41.7 kB

Total Files

25

Last publish

Collaborators

  • gabbyti
  • echovick