GTRADEDocs
SDKs

Node.js SDK

The official gtrade-payments package for Node.js 18 and later. No runtime dependencies, CommonJS and ES modules, TypeScript types included.

#Install

bash
npm install https://docs.gtradegateway.io/sdk/gtrade-payments-1.0.0.tgz

This adds "gtrade-payments": "https://docs.gtradegateway.io/sdk/gtrade-payments-1.0.0.tgz" to your package.json. You can verify the file against the checksums.

#Configure

js
const { Gtrade } = require('gtrade-payments');
// or: import { Gtrade } from 'gtrade-payments';

const gtrade = new Gtrade({
  apiKey: process.env.GTRADE_API_KEY, // required
  baseUrl: 'https://api.gtradegateway.io',             // API base URL
  timeoutMs: 30000,                   // per request, default 30000
  maxRetries: 2,                      // retries on 429, 5xx and network errors, default 2
});
console.log(gtrade.baseUrl);

#Create a payment

js
const { Gtrade } = require('gtrade-payments');
const gtrade = new Gtrade({ apiKey: process.env.GTRADE_API_KEY, baseUrl: 'https://api.gtradegateway.io' });

async function main() {
  const payment = await gtrade.payments.create({
    amountUsd: 25,
    customerEmail: '[email protected]',
    customerId: 'cust_1042',            // optional
    metadata: { order_id: 'ORD-1042' }, // optional
    idempotencyKey: 'order-ORD-1042',   // optional, recommended
  });
  console.log(payment.id, payment.status, payment.checkout_url);
}
main();

Parameters use camelCase; the returned objects keep the API's snake_case field names (payment.checkout_url).

#Retrieve and list payments

js
const { Gtrade } = require('gtrade-payments');
const gtrade = new Gtrade({ apiKey: process.env.GTRADE_API_KEY, baseUrl: 'https://api.gtradegateway.io' });

async function main() {
  const payment = await gtrade.payments.retrieve('9f439f25-f403-446c-9c6a-ecd4aab265e3');
  console.log(payment.status, payment.amount_paid_usd);

  // One page
  const page = await gtrade.payments.list({ limit: 10, status: 'open' });
  console.log(page.data.length, page.has_more);

  // Next page
  if (page.has_more) {
    const next = await gtrade.payments.list({ limit: 10, status: 'open', startingAfter: page.data[page.data.length - 1].id });
    console.log(next.data.length);
  }

  // Every payment, page by page
  let count = 0;
  for await (const p of gtrade.payments.listAutoPaging({ limit: 100 })) count++;
  console.log('payments:', count);
}
main();

#Webhooks

Manage endpoints:

js
const { Gtrade } = require('gtrade-payments');
const gtrade = new Gtrade({ apiKey: process.env.GTRADE_API_KEY, baseUrl: 'https://api.gtradegateway.io' });

async function main() {
  const endpoint = await gtrade.webhooks.create('https://shop.example.com/webhooks/gtrade');
  const delivery = await gtrade.webhooks.test(endpoint.id);
  console.log('test delivery:', delivery.status, delivery.response_status);
  const list = await gtrade.webhooks.list();
  console.log('endpoints:', list.data.map((w) => w.url));
  await gtrade.webhooks.delete(endpoint.id);
}
main();

Verify incoming events with the raw body. With Express, use express.raw() on the webhook route:

js
const express = require('express');
const { Webhook } = require('gtrade-payments');

const app = express();

app.post('/webhooks/gtrade', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try {
    event = Webhook.constructEvent(req.body, req.get('X-Gtrade-Signature'), process.env.GTRADE_API_KEY);
  } catch (err) {
    return res.status(400).send('invalid signature'); // err is a SignatureVerificationError
  }
  switch (event.type) {
    case 'payment.paid':
      console.log('Paid:', event.data.id, event.data.metadata); // fulfil the order
      break;
    case 'payment.cancelled':
      console.log('Cancelled:', event.data.id); // release the order
      break;
    default:
      console.log('Event:', event.type, event.data.status);
  }
  res.sendStatus(200);
});

app.listen(process.env.PORT || 3000);

Webhook.verify(rawBody, signatureHeader, apiKey) returns true or false if you only need the check.

#Errors

All errors extend GtradeError and carry statusCode, type, code and requestId:

js
const { Gtrade, GtradeError, ValidationError, RateLimitError } = require('gtrade-payments');
const gtrade = new Gtrade({ apiKey: process.env.GTRADE_API_KEY, baseUrl: 'https://api.gtradegateway.io' });

async function main() {
  try {
    await gtrade.payments.create({ amountUsd: -5, customerEmail: '[email protected]' });
  } catch (err) {
    if (err instanceof ValidationError) {
      console.log('Invalid request:', err.code, err.message);
    } else if (err instanceof RateLimitError) {
      console.log('Slow down, retry after', err.retryAfter, 'seconds');
    } else if (err instanceof GtradeError) {
      console.log('API error', err.statusCode, err.code, 'request', err.requestId);
    } else {
      throw err;
    }
  }
}
main();
ClassWhen
AuthenticationError401: missing or invalid API key.
NotFoundError404: unknown payment, webhook or route.
ConflictError409: idempotency key reused or in use.
ValidationError400, 422: invalid parameters.
RateLimitError429, with retryAfter in seconds.
ApiError5xx and any other status (for example 405, 413).
ConnectionErrorNetwork failure or timeout.
SignatureVerificationErrorWebhook.constructEvent with a wrong or missing signature.

#TypeScript

Types ship with the package (Payment, PaymentStatus, Event, EventType, WebhookEndpoint, WebhookDelivery and the option types).

ts
import { Gtrade, type Payment, type Event } from 'gtrade-payments';