Integrating with Node.js using Axios

In this section, we will guide you through the process of integrating the Trustist Ecommerce Payments API into your Node.js application using Axios as the HTTP client.

1. Installation #

To get started, ensure you have Axios installed in your Node.js project. You can install it using npm or yarn:

npm install axios

or

yarn add axios

2. Configuration #

Create a new Axios instance and configure it with your API credentials and the desired environment (sandbox or production). The base URL and Hawk authentication will be set up for all requests made using this instance. Here’s an example:

const axios = require('axios');
const hawk = require('hawk'); // You'll need to install the 'hawk' package as well: npm install hawk

const clientId = 'your-client-id';
const privateKey = 'your-private-key';
const environment = 'sandbox'; // or 'production'

const apiBaseURL = environment === 'sandbox'
    ? 'https://api-sandbox.trustistecommerce.com'
    : 'https://api.trustistecommerce.com';

const trustistEcommerceAPI = axios.create({
  baseURL: apiBaseURL,
});

trustistEcommerceAPI.interceptors.request.use((config) => {
  const { method, url, data, headers } = config;
  const contentType = headers['Content-Type'] || 'application/json';

  const requestOptions = {
    credentials: {
      id: clientId,
      key: privateKey,
      algorithm: "sha256",
    },
    payload: JSON.stringify(data),
    contentType,
  };

  const { header } = hawk.client.header(
    apiBaseURL + url,
    method,
    requestOptions
  );
  config.headers['Authorization'] = header;

  return config;
});

3. Creating a Payment #

To create a new payment, make a POST request to the `/payments` endpoint, passing a JSON object containing the necessary payment details.

Example:

async function createPayment(amount, reference, returnUrl) {
  try {
    const response = await trustistEcommerceAPI.post('/payments', {
      Amount: amount,
      Reference: reference,
      ReturnUrl: returnUrl,
    });

    return response.data;
  } catch (error) {
    console.error('Error creating payment:', error);
    throw error;
  }
}

4. Retrieving a Payment #

To retrieve the details of an existing payment, make a GET request to the `/payments/{paymentId}` endpoint, passing the payment ID as a parameter.

Example:

async function getPayment(paymentId) {
  try {
    const response = await trustistEcommerceAPI.get(`/payments/${paymentId}`);
    return response.data;
  } catch (error) {
    console.error('Error retrieving payment:', error);
    throw error;
  }
}

By following these steps, you should now be able to integrate the Trustist Ecommerce Payments API into your Node.js application using Axios. For further information or assistance, please consult our comprehensive API documentation or contact our support team.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *