Verification and handler checklist
Every delivery is signed. A valid signature proves the request came from Peer and the body was not altered; the timestamp check stops replays of old deliveries. Verify both before acting on a payload.
Signature format
Each delivery includes these headers:
| Header | Description |
|---|---|
X-Webhook-Id | Delivery id, the same on every retry |
X-Webhook-Timestamp | Unix timestamp in seconds, fresh on every attempt |
X-Webhook-Signature | HMAC-SHA256 signature, hex-encoded |
The signature is:
HMAC-SHA256(secret, timestamp + "." + payload)
secretis the webhook's signing secret, returned once at creationtimestampis theX-Webhook-Timestampheaderpayloadis the raw request body
Implementation examples
Node.js / Express
import express from 'express';
import crypto from 'crypto';
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;
if (!WEBHOOK_SECRET) throw new Error('Set WEBHOOK_SECRET before starting the webhook handler');
function verifyWebhookSignature(secret: string, payload: Buffer, signature?: string, timestamp?: string): boolean {
const now = Math.floor(Date.now() / 1000);
if (!timestamp || !/^\d+$/.test(timestamp) || Math.abs(now - Number(timestamp)) > 300 ||
!signature || !/^[0-9a-f]{64}$/.test(signature)) {
return false;
}
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(timestamp + '.')
.update(payload)
.digest();
return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), expectedSignature);
}
const app = express();
app.post('/webhooks/zkp2p', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.get('x-webhook-signature');
const timestamp = req.get('x-webhook-timestamp');
const payload: Buffer = req.body;
if (!verifyWebhookSignature(WEBHOOK_SECRET, payload, signature, timestamp)) {
return res.status(401).send('Invalid signature');
}
const event = JSON.parse(payload.toString('utf8'));
// Process event...
res.status(200).send('OK');
});
Python / Flask
import hmac
import hashlib
import os
import re
import time
from flask import Flask, request, abort
WEBHOOK_SECRET = os.environ['WEBHOOK_SECRET']
if not WEBHOOK_SECRET:
raise RuntimeError('Set WEBHOOK_SECRET before starting the webhook handler')
def verify_webhook_signature(payload: bytes, signature: str, timestamp: str) -> bool:
if not re.fullmatch(r'[0-9]{1,12}', timestamp) or not re.fullmatch(r'[0-9a-f]{64}', signature):
return False
if abs(int(time.time()) - int(timestamp)) > 300:
return False
signature_base = timestamp.encode('ascii') + b'.' + payload
expected_signature = hmac.new(
WEBHOOK_SECRET.encode('utf-8'),
signature_base,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, expected_signature)
app = Flask(__name__)
@app.route('/webhooks/zkp2p', methods=['POST'])
def handle_webhook():
signature = request.headers.get('X-Webhook-Signature', '')
timestamp = request.headers.get('X-Webhook-Timestamp', '0')
payload = request.get_data()
if not verify_webhook_signature(payload, signature, timestamp):
abort(401)
event = request.get_json()
# Process event...
return 'OK', 200
Go
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"os"
"strconv"
"time"
)
var webhookSecret = []byte(os.Getenv("WEBHOOK_SECRET"))
func verifyWebhookSignature(payload []byte, signature, timestamp string) bool {
ts, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil || len(webhookSecret) == 0 {
return false
}
age := time.Now().Unix() - ts
if age > 300 || age < -300 {
return false
}
mac := hmac.New(sha256.New, webhookSecret)
mac.Write([]byte(timestamp + "."))
mac.Write(payload)
expectedSignature := hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(signature), []byte(expectedSignature))
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
signature := r.Header.Get("X-Webhook-Signature")
timestamp := r.Header.Get("X-Webhook-Timestamp")
payload, err := io.ReadAll(r.Body)
if err != nil || !verifyWebhookSignature(payload, signature, timestamp) {
http.Error(w, "Invalid signature", http.StatusUnauthorized)
return
}
// Process event...
w.WriteHeader(http.StatusOK)
}
Handler checklist
- Verify the signature and the timestamp on every delivery, including in development. Reject anything more than 5 minutes from your clock in either direction.
- Compare signatures with a timing-safe function. A plain
==leaks timing information. - Verify the raw body, then parse it, so you check the exact bytes you received.
- Respond 2xx first and process asynchronously.
- Deduplicate on the body's
id. It is the same on every retry, and for payout and dispute events it is also the same on every webhook endpoint. - Treat each delivery as current state, not as a step: events can repeat and arrive out of
order. Reconcile from the full snapshots, keyed on
data.order.idfor order events. - Keep fulfillment state and chargeback state in separate fields. A chargeback doesn't undo
SETTLEDorFULFILLED, andchargebackStatuscan move fromCHARGEBACKEDback toPARTIALLY_CHARGEBACKEDwhen another payment settles. - Read
payment.penaltiesbefore you treat a lownetSettledUsdcAmountas an underpayment. A non-empty array means the credited amount was reduced, for example because the customer sent a Venmo or PayPal payment with purchase protection on. See payment penalties. - Release goods only on
ORDER_FULFILLED, or whendata.order.statusisFULFILLED. No other event or redirect is a release signal. - Log
id,typeand the order or payout id of every delivery you handle. - Keep the signing secret out of source code and logs. If it leaks, create a new webhook, which gets a new secret, and delete the old one.