> ## Documentation Index
> Fetch the complete documentation index at: /llms.txt
> Use this file to discover all available pages before exploring further.

# Verify signatures

> Check the HMAC-SHA256 signature and the timestamp on every webhook before you trust it.

Every delivery is signed with your endpoint's signing secret. Verify the signature before you read the body. Anyone can post JSON to your URL; only Payve can sign it.

## The scheme

```text
X-Payve-Signature: t=1763460017,v1=5c7e0d6a1b9f48e2...
```

1. Take `t` and `v1` from the `X-Payve-Signature` header.
2. Build the signed string: the timestamp, a full stop, then the **raw request body**: `<t>.<raw body>`.
3. Compute HMAC-SHA256 of that string with your signing secret as the key. Encode it as lowercase hex.
4. Compare your result with `v1` using a constant-time comparison.
5. Reject the request if `t` is more than five minutes from your server's clock.

The secret is the whole string the dashboard gave you, including the `whsec_` prefix.

> [!WARNING]
>
> **Sign the raw bytes, not parsed JSON.** If your framework parses the body and you re-serialise
> it, key order and spacing change and the signature will not match. Capture the raw body before any
> JSON middleware runs.

## Working examples

Each example verifies the signature, rejects old timestamps, and answers `200` before doing slow work.

```javascript Node (Express)
import express from 'express';
import crypto from 'node:crypto';

const app = express();
const SECRET = process.env.PAYVE_WEBHOOK_SECRET; // whsec_...
const TOLERANCE_SECONDS = 300;

function verify(rawBody, header) {
  if (!header) return false;
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
  const timestamp = Number(parts.t);
  if (!timestamp || !parts.v1) return false;

  // Replay protection: refuse anything outside the tolerance window.
  if (Math.abs(Date.now() / 1000 - timestamp) > TOLERANCE_SECONDS) return false;

  const expected = crypto
    .createHmac('sha256', SECRET)
    .update(`${parts.t}.${rawBody}`)
    .digest('hex');

  const a = Buffer.from(expected, 'hex');
  const b = Buffer.from(parts.v1, 'hex');
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// express.raw keeps the body as the exact bytes Payve signed.
app.post('/webhooks/payve', express.raw({ type: 'application/json' }), async (req, res) => {
  const rawBody = req.body.toString('utf8');

  if (!verify(rawBody, req.get('X-Payve-Signature'))) {
    return res.status(401).send('Invalid signature');
  }

  const event = JSON.parse(rawBody);

  // Store the event id; skip if you have seen it. Then queue the work.
  const isNew = await saveEventIdIfNew(event.id);
  if (isNew) await queue.add('payve-event', event);

  res.status(200).send('ok');
});

app.listen(3000);
```

```python Python (Flask)
import hashlib, hmac, json, os, time
from flask import Flask, request

app = Flask(__name__)
SECRET = os.environ["PAYVE_WEBHOOK_SECRET"].encode()  # whsec_...
TOLERANCE_SECONDS = 300


def verify(raw_body: bytes, header: str | None) -> bool:
    if not header:
        return False
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    timestamp, signature = parts.get("t"), parts.get("v1")
    if not timestamp or not signature or not timestamp.isdigit():
        return False

    # Replay protection: refuse anything outside the tolerance window.
    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    signed = timestamp.encode() + b"." + raw_body
    expected = hmac.new(SECRET, signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)


@app.post("/webhooks/payve")
def payve_webhook():
    raw_body = request.get_data()  # the exact bytes Payve signed

    if not verify(raw_body, request.headers.get("X-Payve-Signature")):
        return "Invalid signature", 401

    event = json.loads(raw_body)

    # Store the event id; skip if you have seen it. Then queue the work.
    if save_event_id_if_new(event["id"]):
        queue.enqueue("payve-event", event)

    return "ok", 200
```

```php PHP
<?php
$secret = getenv('PAYVE_WEBHOOK_SECRET'); // whsec_...
$toleranceSeconds = 300;

// php://input is the exact body Payve signed. Do not use $_POST.
$rawBody = file_get_contents('php://input');
$header  = $_SERVER['HTTP_X_PAYVE_SIGNATURE'] ?? '';

function verify(string $rawBody, string $header, string $secret, int $tolerance): bool
{
    $parts = [];
    foreach (explode(',', $header) as $pair) {
        $kv = explode('=', $pair, 2);
        if (count($kv) === 2) {
            $parts[$kv[0]] = $kv[1];
        }
    }
    if (empty($parts['t']) || empty($parts['v1']) || !ctype_digit($parts['t'])) {
        return false;
    }

    // Replay protection: refuse anything outside the tolerance window.
    if (abs(time() - (int) $parts['t']) > $tolerance) {
        return false;
    }

    $expected = hash_hmac('sha256', $parts['t'] . '.' . $rawBody, $secret);
    return hash_equals($expected, $parts['v1']);
}

if (!verify($rawBody, $header, $secret, $toleranceSeconds)) {
    http_response_code(401);
    exit('Invalid signature');
}

$event = json_decode($rawBody, true);

// Store the event id; skip if you have seen it. Then queue the work.
if (save_event_id_if_new($event['id'])) {
    enqueue('payve-event', $event);
}

http_response_code(200);
echo 'ok';
```

```ruby Ruby (Sinatra)
require 'sinatra'
require 'openssl'
require 'json'

SECRET = ENV.fetch('PAYVE_WEBHOOK_SECRET') # whsec_...
TOLERANCE_SECONDS = 300

def verify(raw_body, header)
  return false if header.nil?

  parts = header.split(',').map { |p| p.split('=', 2) }.to_h
  timestamp, signature = parts['t'], parts['v1']
  return false unless timestamp&.match?(/\A\d+\z/) && signature

  # Replay protection: refuse anything outside the tolerance window.
  return false if (Time.now.to_i - timestamp.to_i).abs > TOLERANCE_SECONDS

  expected = OpenSSL::HMAC.hexdigest('SHA256', SECRET, "#{timestamp}.#{raw_body}")
  return false unless expected.bytesize == signature.bytesize

  OpenSSL.fixed_length_secure_compare(expected, signature)
end

post '/webhooks/payve' do
  raw_body = request.body.read # the exact bytes Payve signed

  halt 401, 'Invalid signature' unless verify(raw_body, request.env['HTTP_X_PAYVE_SIGNATURE'])

  event = JSON.parse(raw_body)

  # Store the event id; skip if you have seen it. Then queue the work.
  enqueue('payve-event', event) if save_event_id_if_new(event['id'])

  status 200
  'ok'
end
```

```go Go
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io"
	"math"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

var secret = []byte(os.Getenv("PAYVE_WEBHOOK_SECRET")) // whsec_...

const toleranceSeconds = 300

func verify(rawBody []byte, header string) bool {
	parts := map[string]string{}
	for _, p := range strings.Split(header, ",") {
		if k, v, ok := strings.Cut(p, "="); ok {
			parts[k] = v
		}
	}
	timestamp, err := strconv.ParseInt(parts["t"], 10, 64)
	if err != nil || parts["v1"] == "" {
		return false
	}

	// Replay protection: refuse anything outside the tolerance window.
	if math.Abs(float64(time.Now().Unix()-timestamp)) > toleranceSeconds {
		return false
	}

	mac := hmac.New(sha256.New, secret)
	mac.Write([]byte(parts["t"] + "."))
	mac.Write(rawBody)
	expected := hex.EncodeToString(mac.Sum(nil))

	return hmac.Equal([]byte(expected), []byte(parts["v1"]))
}

func handler(w http.ResponseWriter, r *http.Request) {
	rawBody, err := io.ReadAll(r.Body) // the exact bytes Payve signed
	if err != nil || !verify(rawBody, r.Header.Get("X-Payve-Signature")) {
		http.Error(w, "Invalid signature", http.StatusUnauthorized)
		return
	}

	var event struct {
		ID   string `json:"id"`
		Type string `json:"type"`
	}
	if err := json.Unmarshal(rawBody, &event); err != nil {
		http.Error(w, "Bad request", http.StatusBadRequest)
		return
	}

	// Store the event id; skip if you have seen it. Then queue the work.
	if saveEventIDIfNew(event.ID) {
		enqueue("payve-event", rawBody)
	}

	w.WriteHeader(http.StatusOK)
	w.Write([]byte("ok"))
}

func main() {
	http.HandleFunc("/webhooks/payve", handler)
	http.ListenAndServe(":3000", nil)
}
```

```java Java (Spring)
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
public class PayveWebhookController {
  private static final String SECRET = System.getenv("PAYVE_WEBHOOK_SECRET"); // whsec_...
  private static final long TOLERANCE_SECONDS = 300;

  static boolean verify(byte[] rawBody, String header) throws Exception {
    if (header == null) return false;
    Map<String, String> parts = new HashMap<>();
    for (String p : header.split(",")) {
      String[] kv = p.split("=", 2);
      if (kv.length == 2) parts.put(kv[0], kv[1]);
    }
    String t = parts.get("t");
    String v1 = parts.get("v1");
    if (t == null || v1 == null || !t.matches("\\d+")) return false;

    // Replay protection: refuse anything outside the tolerance window.
    if (Math.abs(Instant.now().getEpochSecond() - Long.parseLong(t)) > TOLERANCE_SECONDS) {
      return false;
    }

    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    mac.update((t + ".").getBytes(StandardCharsets.UTF_8));
    String expected = HexFormat.of().formatHex(mac.doFinal(rawBody));

    return MessageDigest.isEqual(
        expected.getBytes(StandardCharsets.UTF_8), v1.getBytes(StandardCharsets.UTF_8));
  }

  // byte[] keeps the body as the exact bytes Payve signed.
  @PostMapping("/webhooks/payve")
  public ResponseEntity<String> receive(
      @RequestBody byte[] rawBody,
      @RequestHeader(value = "X-Payve-Signature", required = false) String signature)
      throws Exception {
    if (!verify(rawBody, signature)) {
      return ResponseEntity.status(401).body("Invalid signature");
    }

    String json = new String(rawBody, StandardCharsets.UTF_8);

    // Read the event id from the JSON, store it, and skip it if you have seen it.
    // Then queue the work.
    queuePayveEvent(json);

    return ResponseEntity.ok("ok");
  }
}
```

```csharp C# (ASP.NET Core)
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

var app = WebApplication.CreateBuilder(args).Build();
var secret = Encoding.UTF8.GetBytes(
    Environment.GetEnvironmentVariable("PAYVE_WEBHOOK_SECRET")!); // whsec_...
const long ToleranceSeconds = 300;

bool Verify(byte[] rawBody, string? header)
{
    if (string.IsNullOrEmpty(header)) return false;
    var parts = header.Split(',')
        .Select(p => p.Split('=', 2))
        .Where(kv => kv.Length == 2)
        .ToDictionary(kv => kv[0], kv => kv[1]);
    if (!parts.TryGetValue("t", out var t) || !parts.TryGetValue("v1", out var v1)) return false;
    if (!long.TryParse(t, out var timestamp)) return false;

    // Replay protection: refuse anything outside the tolerance window.
    if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - timestamp) > ToleranceSeconds)
        return false;

    var prefix = Encoding.UTF8.GetBytes(t + ".");
    var signed = new byte[prefix.Length + rawBody.Length];
    prefix.CopyTo(signed, 0);
    rawBody.CopyTo(signed, prefix.Length);

    var expected = Convert.ToHexString(HMACSHA256.HashData(secret, signed)).ToLowerInvariant();

    return CryptographicOperations.FixedTimeEquals(
        Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(v1));
}

app.MapPost("/webhooks/payve", async (HttpRequest request) =>
{
    using var buffer = new MemoryStream();
    await request.Body.CopyToAsync(buffer);
    var rawBody = buffer.ToArray(); // the exact bytes Payve signed

    if (!Verify(rawBody, request.Headers["X-Payve-Signature"]))
        return Results.Text("Invalid signature", statusCode: 401);

    using var doc = JsonDocument.Parse(rawBody);
    var eventId = doc.RootElement.GetProperty("id").GetString()!;

    // Store the event id; skip if you have seen it. Then queue the work.
    if (await SaveEventIdIfNew(eventId)) await Enqueue("payve-event", rawBody);

    return Results.Text("ok");
});

app.Run();
```

The functions that store the event id and queue the work are yours to supply. [Handle events safely](/webhooks/handling-events.md) shows how.

## Check your implementation

Use this fixed example to test your code without a live delivery.

| Input | Value |
| - | - |
| Secret | `whsec_test_secret` |
| Timestamp | `1763460017` |
| Raw body | `{"id":"evt_test","type":"payout.successful"}` |
| Signed string | `1763460017.{"id":"evt_test","type":"payout.successful"}` |
| Expected `v1` | `adc8bee45e602d89e4a78f38e1f45bc6d28f0ec8d9c90b7cbf22448bb599cf90` |

Skip the timestamp check when you run this fixed example, because the timestamp is in the past.

## Replay protection

A signature proves who sent a request. It does not prove the request is new. Someone who captures a valid delivery could send it to you again.

Two checks stop that:

* **Reject old timestamps.** `X-Payve-Timestamp` and the `t` in the signature are set fresh on every delivery attempt, including retries. A genuine delivery is always recent. Five minutes of tolerance allows for clock drift.
* **Reject event ids you have already processed.** See [Handle events safely](/webhooks/handling-events.md).

> [!NOTE]
>
> Keep your server clock synchronised. A clock that is minutes out makes every delivery look too old
> or too new.

## When a secret is rotated

For 24 hours after a signing secret is rotated, each delivery carries two signatures:

* `X-Payve-Signature`, signed with the new secret.
* `X-Payve-Signature-Previous`, signed with the old secret.

Accept the request if either one verifies against a secret you hold. After 24 hours only `X-Payve-Signature` is sent.

## Common mistakes

> [accordion] The signature never matches
>
> You are almost certainly signing parsed JSON. Sign the raw body. Also check that you are using
> the secret for this endpoint and this environment: sandbox and live secrets differ.

> [accordion] It works locally but fails behind a proxy
>
> A proxy or body-parsing layer may be changing the body. Read the raw bytes as early as you can.

> [accordion] Comparing with == or ===
>
> Use a constant-time comparison: `crypto.timingSafeEqual`, `hmac.compare_digest` or
> `hash_equals`.

> [accordion] Every delivery is rejected as too old
>
> Your server clock is wrong, or you are comparing seconds with milliseconds. The timestamp is in
> seconds.
