How to Integrate the 4Geeks Payments API into a Node.js Application
This guide outlines the steps to integrate the 4Geeks Payments API into a Node.js application, based on the blog post provided.
Prerequisites¶
- Node.js: Version 14 or higher.
- 4Geeks Payments Account: You need your Public and Secret keys from the developer dashboard.
- Basic Knowledge: REST APIs and asynchronous JavaScript (
async/await).
Step 1: Set Up Your Project¶
Initialize a new Node.js project and install the necessary dependencies (axios, dotenv, express, body-parser).
- Initialize the project:
mkdir 4geeks-payments-integration
cd 4geeks-payments-integration
npm init -y
npm install axios dotenv express body-parser
- Configure Environment Variables: Create a
.envfile to store your API credentials securely.
Step 2: Authenticate with the API¶
Create a service file (e.g., paymentService.js) to handle API requests. You will use axios to send your Secret Key in the Authorization header.
// paymentService.js
require('dotenv').config();
const axios = require('axios');
const API_URL = 'https://api.4geeks.io/v1'; // Base API Endpoint
const client = axios.create({
baseURL: API_URL,
headers: {
'Authorization': `Bearer ${process.env.FOURGEEKS_SECRET_KEY}`,
'Content-Type': 'application/json'
}
});
module.exports = client;
Step 3: Create a Payment Intent¶
Add a function to paymentService.js to create a “Payment Intent” (or Charge). This initiates the transaction.
const createPaymentIntent = async (amount, currency = 'USD', customerId) => {
try {
const response = await client.post('/charges', {
amount: amount, // Amount in cents (e.g., 1000 = $10.00)
currency: currency,
customer: customerId,
description: 'SaaS Subscription Charge'
});
return response.data;
} catch (error) {
console.error('Payment Error:', error.response ? error.response.data : error.message);
throw new Error('Failed to create payment intent');
}
};
module.exports = { createPaymentIntent };
Step 4: Handle Webhooks¶
Set up an Express server (e.g., in server.js) to listen for webhook events. This is critical for confirming payments asynchronously (e.g., charge.succeeded).
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// Webhook endpoint to listen for payment events
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (req, res) => {
const event = req.body;
// In production, verify the signature here to ensure the request is genuine.
switch (event.type) {
case 'charge.succeeded':
const charge = event.data.object;
console.log('Payment successful:', charge.id);
// Logic to update user subscription or fulfill order
break;
case 'charge.failed':
console.log('Payment failed:', event.data.object.id);
// Logic to notify the user
break;
default:
console.log('Unhandled event type:', event.type);
}
res.json({received: true});
});
app.listen(process.env.PORT || 3000, () => console.log('Server running...'));
Step 5: Test & Deploy¶
- Sandbox Mode: Use the 4Geeks Payments sandbox environment to test charges, declined cards, and errors without using real money.
- Go Live: Once verified, switch your credentials to the live keys.
Tip: For simple use cases, the article mentions that 4Geeks also offers no-code checkout links if you do not need a full custom API integration.
- Still questions? Ask to the community.
- Check out the changelog.