Verify a payment with Node.js

Estimated reading: 3 minutes views

Summary: An Express route that compares the secret safely, checks status and amount, and inserts the transaction id once.

This Node.js example uses Express and the built-in crypto module. It reads the JSON body, compares the secret with crypto.timingSafeEqual, checks that the status is confirmed, validates the fiat amount and order reference, and inserts the transaction id behind a unique constraint. The result is an endpoint that survives retries without paying twice.

Customer completing a card-style crypto checkout

The route

const express = require('express');
const crypto = require('crypto');
const { Pool } = require('pg');

const app = express();
const pool = new Pool();
const SECRET = process.env.RASTERPAY_WEBHOOK_SECRET;

// Raw body keeps the JSON intact; 1 MB is plenty.
app.post('/webhooks/rasterpay',
  express.json({ limit: '1mb' }),
  async (req, res) => {
    const body = req.body || {};
    const t = body.transaction;

    if (!t || typeof body.key !== 'string') {
      return res.status(400).send('bad payload');
    }

    // Constant-time secret comparison.
    const a = Buffer.from(body.key, 'utf8');
    const b = Buffer.from(SECRET, 'utf8');
    const ok = a.length === b.length && crypto.timingSafeEqual(a, b);
    if (!ok) return res.status(403).send('forbidden');

    if (t.status !== 'C') return res.status(200).send('ignored');

    const txId = String(t.id || '');
    const orderRef = String(t.external_reference || '');
    const paid = String(t.amount_fiat || '0');

    if (!txId || !orderRef) {
      return res.status(400).send('missing id or reference');
    }

    const expected = await orderTotal(orderRef); // "49.00"
    if (!sameAmount(paid, expected)) {
      console.warn('amount mismatch', { txId, paid, expected });
      return res.status(200).send('amount mismatch');
    }

    try {
      await pool.query(
        `INSERT INTO payments
           (transaction_id, order_ref, amount_fiat, currency, tx_hash)
         VALUES ($1, $2, $3, $4, $5)
         ON CONFLICT (transaction_id) DO NOTHING`,
        [txId, orderRef, paid, t.currency, t.hash || '']
      );
    } catch (err) {
      console.error('insert failed', err.message);
      return res.status(500).send('db error');
    }

    await markOrderPaid(orderRef);
    return res.status(200).send('ok');
  }
);

Comparing decimal amounts

Never subtract floats to decide whether a payment matches. Convert to integer minor units first:

function sameAmount(a, b) {
  const toMinor = (v) => {
    const n = Number(v);
    return Number.isFinite(n) ? Math.round(n * 100) : NaN;
  };
  const x = toMinor(a), y = toMinor(b);
  return Number.isFinite(x) && x === y;
}

Why the length check comes first

timingSafeEqual throws when the buffers differ in length, so compare lengths before calling it. Return 403 for a bad secret and 200 for anything you handled, even a mismatch, so the sender does not retry forever. Log txId, orderRef, and both amounts on every mismatch.

Order of operations

Validate first, write second, fulfil last. If the write fails, return 500 so the call is retried. If fulfilment fails after the write, your duplicate handling will catch the retry and you can retry the fulfilment step from the stored row. For a REST integration, contact support.

Share this Doc

Verify a payment with Node.js

Or copy link

CONTENTS