PAYCOW / DOCUMENTATION

Signature verification

Receive and verify real-time payment events.

Signature Verification

Verify webhook authenticity with HMAC-SHA256

HeaderDescription
PayCow-Event-IdUnique event ID, identical across retries
PayCow-TimestampUnix timestamp (seconds) for replay prevention (300s window)
PayCow-Signaturev1=<hex_hash> — HMAC-SHA256 over timestamp.rawBody
Raw Body Requirement: Always compute HMAC on the raw, unparsed HTTP body. Re-serializing parsed JSON can alter key order and invalidate signatures.

Verification Implementation

import crypto from 'node:crypto';

function verifyPayCowWebhook({ rawBody, timestamp, signature, secret, toleranceSeconds = 300 }) {
  if (!Buffer.isBuffer(rawBody) || !timestamp || !signature || !secret) return false;

  const timestampNumber = Number(timestamp);
  if (!Number.isInteger(timestampNumber)) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - timestampNumber) > toleranceSeconds) return false;
  if (!/^v1=[a-fA-F0-9]{64}$/.test(String(signature))) return false;

  const signedPayload = Buffer.concat([Buffer.from(`${timestamp}.`, 'utf8'), rawBody]);
  const expectedHex = crypto.createHmac('sha256', secret).update(signedPayload).digest('hex');
  const receivedHex = String(signature).slice(3);
  const expected = Buffer.from(expectedHex, 'hex');
  const received = Buffer.from(receivedHex, 'hex');

  return expected.length === received.length && crypto.timingSafeEqual(expected, received);
}
import hmac, hashlib, re, time

def verify_paycow_webhook(raw_body: bytes, timestamp: str, signature: str, secret: str, tolerance=300) -> bool:
    try:
        if not re.fullmatch(r"v1=[a-fA-F0-9]{64}", signature or ""):
            return False
        if abs(int(time.time()) - int(timestamp)) > tolerance:
            return False
        signed = f"{timestamp}.".encode() + raw_body
        expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
        return hmac.compare_digest(expected, signature[3:])
    except Exception:
        return False
<?php
function verifyPayCowWebhook($rawBody, $timestamp, $signature, $secret, $tolerance = 300) {
    if (!preg_match('/^v1=[a-fA-F0-9]{64}$/', $signature ?? '')) return false;
    if (abs(time() - intval($timestamp)) > $tolerance) return false;
    $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
    return hash_equals($expected, substr($signature, 3));
}

Express Receiver Placement

Register the raw webhook route before the application's global JSON parser. Replace acceptWebhookEventIdempotently with a database transaction that uniquely stores event.id and applies payment.paid fulfillment once.

app.post('/webhooks/paycow', express.raw({ type: 'application/json', limit: '256kb' }), async (req, res) => {
  const timestamp = req.get('PayCow-Timestamp');
  const signature = req.get('PayCow-Signature');

  if (!verifyPayCowWebhook({
    rawBody: req.body,
    timestamp,
    signature,
    secret: process.env.PAYCOW_WEBHOOK_SECRET
  })) return res.sendStatus(401);

  let event;
  try {
    event = JSON.parse(req.body.toString('utf8'));
  } catch {
    return res.sendStatus(400);
  }

  if (event.id !== req.get('PayCow-Event-Id')) return res.sendStatus(400);
  await acceptWebhookEventIdempotently(event);
  return res.sendStatus(200);
});

app.use(express.json());