Integrating with Node.js using Axios
This guide demonstrates how to integrate the Trustist Ecommerce Payments API into your Node.js application using Axios as the HTTP client and Hawk authentication.
1. Installation
First, ensure you have Axios and the Hawk authentication library installed in your Node.js project:
npm install axios @hapi/hawk
Or with yarn:
yarn add axios @hapi/hawk
2. Configuration
Create an Axios instance and configure it with your API credentials and the desired environment (sandbox or production). The Hawk authentication will be set up for all requests using an interceptor.
const axios = require('axios');
const hawk = require('@hapi/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,
});
// Add Hawk authentication interceptor
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 /v1/payments endpoint with the payment details.
async function createPayment(amount, reference, returnUrl) {
try {
const response = await trustistEcommerceAPI.post('/v1/payments', {
amount: amount,
reference: reference,
returnUrl: returnUrl,
});
return response.data;
} catch (error) {
console.error('Error creating payment:', error.response?.data || error.message);
throw error;
}
}
Usage Example
const payment = await createPayment(
99.99,
'ORDER-12345',
'https://yoursite.com/payment/success'
);
console.log('Payment ID:', payment.id);
console.log('Payment Link:', payment.payLink);
// Redirect customer to payment.payLink
4. Retrieving a Payment
To retrieve the details of an existing payment, make a GET request to the /v1/payments/{paymentId} endpoint.
async function getPayment(paymentId) {
try {
const response = await trustistEcommerceAPI.get(`/v1/payments/${paymentId}`);
return response.data;
} catch (error) {
console.error('Error retrieving payment:', error.response?.data || error.message);
throw error;
}
}
Usage Example
const payment = await getPayment('your-payment-id');
console.log('Payment Status:', payment.status);
console.log('Amount:', payment.amount);
console.log('Reference:', payment.sourceReference);
Example: Express.js Integration
Here's a complete example showing how to integrate with an Express.js application:
const express = require('express');
const app = express();
app.use(express.json());
// Create payment endpoint
app.post('/api/payments', async (req, res) => {
try {
const { amount, reference, returnUrl } = req.body;
const payment = await createPayment(amount, reference, returnUrl);
res.json({
id: payment.id,
payLink: payment.payLink
});
} catch (error) {
res.status(500).json({
error: 'Failed to create payment',
message: error.message
});
}
});
// Get payment status endpoint
app.get('/api/payments/:id', async (req, res) => {
try {
const { id } = req.params;
const payment = await getPayment(id);
res.json(payment);
} catch (error) {
res.status(500).json({
error: 'Failed to retrieve payment',
message: error.message
});
}
});
// Payment return handler
app.get('/payment/complete', async (req, res) => {
try {
const { paymentId } = req.query;
// Verify payment status
const payment = await getPayment(paymentId);
if (payment.status === 'COMPLETE') {
res.redirect('/payment/success');
} else {
res.redirect('/payment/failed');
}
} catch (error) {
res.redirect('/payment/error');
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Creating Standing Orders
To create a standing order (Direct Debit), use the /v1/standingorders endpoint:
async function createStandingOrder(amount, reference, startDate, frequency, numberOfPayments) {
try {
const response = await trustistEcommerceAPI.post('/v1/standingorders', {
amount,
reference,
startDate, // yyyy-MM-dd format
frequency, // 'Weekly', 'Monthly', or 'Annually'
numberOfPayments, // 0 for never-ending
returnUrl: 'https://yoursite.com/standing-order/success'
});
return response.data;
} catch (error) {
console.error('Error creating standing order:', error.response?.data || error.message);
throw error;
}
}
Best Practices
- Never expose API credentials in client-side code
- Always verify payment status server-side before fulfilling orders
- Use environment variables for API credentials
- Implement error handling for all API calls
- Set up webhooks for real-time payment notifications
- Use HTTPS for all production endpoints
Environment Variables
Store your credentials securely using environment variables:
require('dotenv').config();
const clientId = process.env.TRUSTIST_CLIENT_ID;
const privateKey = process.env.TRUSTIST_PRIVATE_KEY;
const environment = process.env.TRUSTIST_ENV || 'sandbox';
Create a .env file:
TRUSTIST_CLIENT_ID=your-client-id
TRUSTIST_PRIVATE_KEY=your-private-key
TRUSTIST_ENV=sandbox
Next Steps
- Review the API Reference for detailed endpoint documentation
- Set up Payment Webhooks for real-time notifications
- Test your integration in the Sandbox environment
- Explore other SDKs: JavaScript, .NET, PHP, Python