---
title: Best Practices
slug: best-practices
icon: {"lucideIcon":"ThumbsUp"}
createdAt: 2025-08-20T18:51:21.485Z
---

There are many important considerations to take when implementing webhook consumers, and these have been well-documented and explained here: [https://webhooks.fyi/best-practices/webhook-consumers](https://webhooks.fyi/best-practices/webhook-consumers). But outlined below are more specifics to setting up&#x20;

## Timestamp Checks

EquiDeFi webhook requests include a `X-Webhook-Timestamp` header that can be used to verify the timing of the request to help mitigate and block [replay attacks](https://webhooks.fyi/security/replay-prevention).

## Duplicate Sends

While uncommon, it is possible for events to be fired multiple times. This usually will only happen on failed webhook deliveries. The `X-Webhook-Id` can be used to block duplicate events from being processed in your application more than once.

## Payload Verification

Since your endpoints need to be public, you can use the `X-Webhook-Signature` header in combination with the [Signing Secret](https://docs.equidefi.io/getting-started#webhook-signing-secret) to verify the incoming request is valid and coming from EquiDeFi. Below are some example code snippets you can copy into your webhook endpoint to validate the request body coming in from EquiDeFi.

:::CodeblockTabs
```javascript
const crypto = require("node:crypto");

const TOLERANCE_SECONDS = 300;

/**
 * Verifies an EquiDeFi webhook. `rawBody` must be the request body exactly as
 * received (a Buffer or string); a re-serialized JSON object will not match.
 */
function verifyEquidefiWebhook(rawBody, signatureHeader, secret, now = Date.now()) {
  if (!signatureHeader) return false;

  // X-Webhook-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>] (two v1 values during secret rotation)
  let timestamp;
  const signatures = [];
  for (const part of signatureHeader.split(",")) {
    const separator = part.indexOf("=");
    if (separator === -1) continue;
    const key = part.slice(0, separator).trim();
    const value = part.slice(separator + 1).trim();
    if (key === "t" && /^\d+$/.test(value)) timestamp = Number(value);
    else if (key === "v1" && value) signatures.push(value);
  }
  if (timestamp === undefined || signatures.length === 0) return false;

  // Reject stale or future-dated deliveries to limit replays.
  if (Math.abs(Math.floor(now / 1000) - timestamp) > TOLERANCE_SECONDS) return false;

  const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest("hex");

  return signatures.some(
    (signature) =>
      signature.length === expected.length &&
      crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)),
  );
}

module.exports = { verifyEquidefiWebhook };

// Express: read the body raw on this route, then parse it yourself after verifying.
//
// app.post("/webhooks/equidefi", express.raw({ type: "application/json" }), (req, res) => {
//   if (!verifyEquidefiWebhook(req.body, req.get("X-Webhook-Signature"), process.env.EQUIDEFI_WEBHOOK_SECRET)) {
//     return res.sendStatus(400);
//   }
//   const event = JSON.parse(req.body.toString("utf8"));
//   // X-Webhook-Id is the same on every retry of an event; use it to skip duplicates.
//   res.sendStatus(200);
// });

```

```typescript
import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SECONDS = 300;

/**
 * Verifies an EquiDeFi webhook. `rawBody` must be the request body exactly as
 * received; a re-serialized JSON object will not match the signature.
 */
export function verifyEquidefiWebhook(
  rawBody: string | Buffer,
  signatureHeader: string | undefined,
  secret: string,
  now: number = Date.now(),
): boolean {
  if (!signatureHeader) return false;

  // X-Webhook-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>] (two v1 values during secret rotation)
  let timestamp: number | undefined;
  const signatures: string[] = [];
  for (const part of signatureHeader.split(",")) {
    const separator = part.indexOf("=");
    if (separator === -1) continue;
    const key = part.slice(0, separator).trim();
    const value = part.slice(separator + 1).trim();
    if (key === "t" && /^\d+$/.test(value)) timestamp = Number(value);
    else if (key === "v1" && value) signatures.push(value);
  }
  if (timestamp === undefined || signatures.length === 0) return false;

  // Reject stale or future-dated deliveries to limit replays.
  if (Math.abs(Math.floor(now / 1000) - timestamp) > TOLERANCE_SECONDS) return false;

  const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest("hex");

  return signatures.some(
    (signature) =>
      signature.length === expected.length && timingSafeEqual(Buffer.from(signature), Buffer.from(expected)),
  );
}

// Express: read the body raw on this route, then parse it yourself after verifying.
//
// import express from "express";
//
// app.post("/webhooks/equidefi", express.raw({ type: "application/json" }), (req, res) => {
//   const secret = process.env.EQUIDEFI_WEBHOOK_SECRET as string; // whsec_...
//   if (!verifyEquidefiWebhook(req.body, req.get("X-Webhook-Signature"), secret)) {
//     return res.sendStatus(400);
//   }
//   const event = JSON.parse(req.body.toString("utf8"));
//   // X-Webhook-Id is the same on every retry of an event; use it to skip duplicates.
//   res.sendStatus(200);
// });

```

```python
import hashlib
import hmac
import time
from typing import Optional

TOLERANCE_SECONDS = 300

def verify_equidefi_webhook(
    raw_body: bytes, signature_header: Optional[str], secret: str, now: Optional[float] = None
) -> bool:
    """Verifies an EquiDeFi webhook. `raw_body` must be the request body bytes
    exactly as received; a re-serialized JSON object will not match."""
    if not signature_header:
        return False

    # X-Webhook-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>] (two v1 values during secret rotation)
    timestamp = None
    signatures = []
    for part in signature_header.split(","):
        key, separator, value = part.strip().partition("=")
        if not separator:
            continue
        if key == "t" and value.isdigit():
            timestamp = int(value)
        elif key == "v1" and value:
            signatures.append(value)
    if timestamp is None or not signatures:
        return False

    # Reject stale or future-dated deliveries to limit replays.
    current = int(time.time() if now is None else now)
    if abs(current - timestamp) > TOLERANCE_SECONDS:
        return False

    expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()

    return any(hmac.compare_digest(expected, signature) for signature in signatures)


# Flask:
#
# @app.post("/webhooks/equidefi")
# def equidefi_webhook():
#     secret = os.environ["EQUIDEFI_WEBHOOK_SECRET"]  # whsec_...
#     if not verify_equidefi_webhook(request.get_data(), request.headers.get("X-Webhook-Signature"), secret):
#         return "", 400
#     event = request.get_json()
#     # X-Webhook-Id is the same on every retry of an event; use it to skip duplicates.
#     return "", 200

```

```ruby
require "openssl"

module EquidefiWebhook
  TOLERANCE_SECONDS = 300

  # Verifies an EquiDeFi webhook. `raw_body` must be the request body exactly as
  # received; a re-serialized JSON object will not match the signature.
  def self.verify(raw_body, signature_header, secret, now: Time.now.to_i)
    return false if signature_header.nil? || signature_header.empty?

    # X-Webhook-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>] (two v1 values during secret rotation)
    timestamp = nil
    signatures = []
    signature_header.split(",").each do |part|
      key, value = part.strip.split("=", 2)
      next if value.nil?

      if key == "t" && value.match?(/\A\d+\z/)
        timestamp = value.to_i
      elsif key == "v1" && !value.empty?
        signatures << value
      end
    end
    return false if timestamp.nil? || signatures.empty?

    # Reject stale or future-dated deliveries to limit replays.
    return false if (now - timestamp).abs > TOLERANCE_SECONDS

    # Binary strings, so a body with non-ASCII bytes can't raise an encoding error.
    expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{timestamp}.".b + raw_body.b)

    signatures.any? { |signature| secure_compare(expected, signature) }
  end

  def self.secure_compare(a, b)
    return false unless a.bytesize == b.bytesize

    result = 0
    a.bytes.zip(b.bytes) { |x, y| result |= x ^ y }
    result.zero?
  end
end

# Rails:
#
#   def equidefi
#     secret = ENV.fetch("EQUIDEFI_WEBHOOK_SECRET") # whsec_...
#     unless EquidefiWebhook.verify(request.raw_post, request.headers["X-Webhook-Signature"], secret)
#       return head :bad_request
#     end
#     event = JSON.parse(request.raw_post)
#     # X-Webhook-Id is the same on every retry of an event; use it to skip duplicates.
#     head :ok
#   end
#
# Sinatra: use `request.body.read` as the raw body.

```

```php
<?php

const EQUIDEFI_WEBHOOK_TOLERANCE_SECONDS = 300;

/**
 * Verifies an EquiDeFi webhook. $rawBody must be the request body exactly as
 * received (file_get_contents('php://input')); a re-encoded JSON array will not match.
 */
function verify_equidefi_webhook(string $rawBody, ?string $signatureHeader, string $secret, ?int $now = null): bool
{
    if ($signatureHeader === null || $signatureHeader === '') {
        return false;
    }

    // X-Webhook-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>] (two v1 values during secret rotation)
    $timestamp = null;
    $signatures = [];
    foreach (explode(',', $signatureHeader) as $part) {
        $pair = explode('=', trim($part), 2);
        if (count($pair) !== 2) {
            continue;
        }
        [$key, $value] = $pair;
        if ($key === 't' && ctype_digit($value)) {
            $timestamp = (int) $value;
        } elseif ($key === 'v1' && $value !== '') {
            $signatures[] = $value;
        }
    }
    if ($timestamp === null || count($signatures) === 0) {
        return false;
    }

    // Reject stale or future-dated deliveries to limit replays.
    if (abs(($now ?? time()) - $timestamp) > EQUIDEFI_WEBHOOK_TOLERANCE_SECONDS) {
        return false;
    }

    $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);

    $verified = false;
    foreach ($signatures as $signature) {
        // hash_equals is constant-time.
        if (hash_equals($expected, $signature)) {
            $verified = true;
        }
    }

    return $verified;
}

// Plain PHP:
//
// $rawBody = file_get_contents('php://input');
// $secret = getenv('EQUIDEFI_WEBHOOK_SECRET'); // whsec_...
// if (!verify_equidefi_webhook($rawBody, $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? null, $secret)) {
//     http_response_code(400);
//     exit;
// }
// $event = json_decode($rawBody, true);
// // X-Webhook-Id ($_SERVER['HTTP_X_WEBHOOK_ID']) is the same on every retry of an event; use it to skip duplicates.
// http_response_code(200);
//
// Laravel: verify_equidefi_webhook($request->getContent(), $request->header('X-Webhook-Signature'), $secret)

```
:::

