Authentication: Signing Every Request the Right Way


EFIcyent APIs use the HMAC-SHA256 algorithm to authenticate requests securely. Every request comprising the URL path and body must be signed using your API Secret. Our server verifies this signature before processing the request to verify its authenticity and integrity.

This section includes a complete guide on how to encrypt and sign API requests using JavaScript, utilizing the CryptoJS library to implement HMAC-SHA256 encryption.

Important Notes

All private REST API requests must include the following headers to be processed successfully.

The API request payload and the signature payload must follow the exact same parameter order. Any mismatch can lead to authentication failure. Maintaining this alignment is important for making sure the data integrity and adhering to EFIcyent’s security protocols.

For the URLPath, use only the last segment of the endpoint.

Example: For https://example.com/api/user/s2s/create_transaction, use **/create_transaction** as the URL path for signing.

Do not include files or images in the request body. It is because HMAC authentication is based on hashing, which only supports plain text or binary content. Including such files will cause the signature validation to fail.

Header Parameters

All private REST API requests must include the following headers:
  1. X-Api-Key Your API key in plain string format. This is used to identify your application.
  2. X-Api-Signature: The Base64-encoded HMAC signature generated from your request.

(Refer to the Encryption & Signing section for more implementation details.)

Encryption and Signing Function

This function is used to generate a secure signature for authenticating your API requests. It accepts the following parameters:
  1. urlPath: The endpoint’s final URL segment (e.g., /create_transaction).
  2. Body (optional): The request payload. If not present, an empty string is used.
  3. apiKey: Your assigned API key. Contact Us for API Key
  4. saltKey: Your associated Salt key used for signature generation. Contact Us for Salt Key

The function returns a string containing the HMAC-generated signature, which must be included in the request headers.Use this function to sign your API requests before sending them to ensure both authenticity and data integrity.

Below is a sample JavaScript function to generate a signature for your API request. Before using it, make sure the CryptoJS library is installed in your project.

You can install it via npm with the following command

Plain Text
npm install crypto-js
Plain Text
const CryptoJS = require("crypto-js");
/**
 * Generate a signature for the API request.
 * @param    {string} urlPath - The URL End segment of the API endpoint. (Ex: /create_transaction, /transaction_status)
 * @param    {object} body - The request body (if any).
 * @param    {string} apiKey - Your API key.
 * @param    {string} saltKey - Your salt key.
 * @returns    {string} - The generated signature.
 */
function signContent(urlPath, body, apiKey, saltKey) {
    // Concatenate URL, request body (if available), and salt key
    const plainContent = `${urlPath}${body ? JSON.stringify(body) : ""}${saltKey}`;
    // Generate HMAC-SHA256 hash and convert it to Hex
    return CryptoJS.HmacSHA256(plainContent, apiKey).toString(CryptoJS.enc.Hex);
}
const urlPath = "/create_transaction";
const body = {
    requestId: "fd33ba787612d595eff03f866b745ed4f",
    amount: "1000"
};
const apiKey = "";
const saltKey = "";
const signature = signContent(urlPath, body, apiKey, saltKey);

console.log("Generated Signature:", signature)

Below is a sample Java function that you can use to generate a signature for your API request.

To use this function, ensure you have the necessary cryptography libraries available in your project. Most Java environments include support for HMAC-SHA256 via the javax.crypto and java.security packages.

This function will help you securely sign your API requests and maintain request integrity during transmission.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
 
public class HMACExample {
    public static String calculateHMAC(String data, String apiKey) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(apiKey.getBytes(), "HmacSHA256");
        hmacSha256.init(secretKey);
        byte[] hmacBytes = hmacSha256.doFinal(data.getBytes());
        StringBuilder hexString = new StringBuilder();
 
        for (byte b : hmacBytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
 
        return hexString.toString();
    }
 
    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
        String urlPath = "/create_transaction";
        String body = "{"requestId":"fd33ba787612d595eff03f866b745ed4f","amount":"1000"}"; //Make sure the body values is a stringified JSON object
        String apiKey = "";
        String saltKey = "";
        String data = urlPath+body+saltKey
        String hmac = calculateHMAC(data, apiKey);
        System.out.println(hmac);
    }
}

Below is a sample PHP function you can use to generate a signature for your API request.

To get started, ensure your PHP environment supports the hash_hmac function, which is commonly available in most standard PHP installations. You do not need CryptoJS or npm for PHP.

This function will help you securely sign your requests to ensure data authenticity and integrity when interacting with the EFIcyent API.

Example Breakdown:

In this example:

'urlPath': Represents the final segment of the API endpoint (e.g., "/create_transaction").

'body': Contains the request payload parameters, such as requestId and amount.

'apiKey': Your assigned API key used for authenticating the request.

'saltKey': The salt key provided to enhance request security.

'signature': Stores the output generated by the signContent function.

Be sure to replace <the-provided-api-key> and <the-provided-salt-key> with your actual credentials. Once executed, this code will generate a valid signature for your API request.

How to Include Signing Keys in API Headers

Once you have generated the required keys, you will need to include them in the request headers to authenticate and authorize your API calls.

Below is an example of how to add the generated keys to your API headers using JavaScript:
const headers = {
'X-Api-Key': apiKey,
'X-Api-Signature': signature,
};
const apiEndpoint = "https://example.com/api/user/create_transaction";
// Include headers in your API request (example using Fetch API)
fetch(apiEndpoint, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(body),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Example Breakdown:

In this example:

'urlPath': Represents the final segment of the API endpoint (e.g.,"/create_transaction").

'body': Contains the request payload parameters, such as requestId and amount.

'apiKey': Your assigned API key used for authenticating the request.

'saltKey': The salt key provided to enhance request security.

'signature': Stores the output generated by the signContent function.

Make sure to replace apiEndpoint with the actual URL of your EFIcyent API endpoint. This example shows how to send an authenticated POST request using JavaScript’s Fetch API.

API Reference Guide

A detailed breakdown of all available endpoints.

Sandbox Environment

Test your API calls in a safe environment that mirrors.

SDKs and Developer Tools

Pre-built SDKs and ready-to-use code examples.

Error Handling and Response Codes

Standardized error messages, HTTP status codes.

User Wallet Management

Create, fund and manage the user wallets.