Verifying a signature

Do this before you give anyone value.

Your webhook URL is a public address. Anyone who learns it can post to it. The signature is how you know a callback came from us.

The scheme

The headerhttp
X-GetElectric-Signature: t=1763456077,v1=5f0e8b2c91d47a63e8f05c1b7a9d2e4406c3b8f1d95a7e20c48b16d3f9027ace
PartMeaning
tUnix seconds when we signed it.
v1HMAC-SHA256, lowercase hex.

The signed string is the timestamp, a full stop, then the raw request body:

What gets signedtext
<t>.<raw body>

The key is your webhook signing secret for that mode. Live callbacks are signed with your live secret, test callbacks with your test one.

Important

Sign the bytes you received, not a re-serialised object. Parsing the JSON and stringifying it again changes key order and whitespace, and the signature will never match. Capture the raw body first, verify, then parse.

Node

Express hands you a parsed object by default, so ask for the raw bytes on this route.

Expressjs
const crypto = require('node:crypto')

app.post(
  '/webhooks/getelectric',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const header = req.get('X-GetElectric-Signature') ?? ''
    const parts = new Map(
      header.split(',').map((piece) => {
        const [key, ...rest] = piece.trim().split('=')
        return [key, rest.join('=')]
      }),
    )

    const timestamp = parts.get('t')
    const signature = parts.get('v1')
    if (!timestamp || !signature) return res.sendStatus(400)

    const expected = crypto
      .createHmac('sha256', process.env.GETELECTRIC_WEBHOOK_SECRET)
      .update(`${timestamp}.`)
      .update(req.body)
      .digest('hex')

    const a = Buffer.from(signature, 'hex')
    const b = Buffer.from(expected, 'hex')
    if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
      return res.sendStatus(400)
    }

    const event = JSON.parse(req.body.toString('utf8'))
    // Acknowledge first, then do the work.
    res.sendStatus(200)
    queue.push(event)
  },
)

PHP

PHPphp
$raw = file_get_contents('php://input');
$header = $_SERVER['HTTP_X_GETELECTRIC_SIGNATURE'] ?? '';

$parts = [];
foreach (explode(',', $header) as $piece) {
    [$key, $value] = array_pad(explode('=', trim($piece), 2), 2, '');
    $parts[$key] = $value;
}

if (empty($parts['t']) || empty($parts['v1'])) {
    http_response_code(400);
    exit;
}

$expected = hash_hmac('sha256', $parts['t'] . '.' . $raw, getenv('GETELECTRIC_WEBHOOK_SECRET'));

if (!hash_equals($expected, $parts['v1'])) {
    http_response_code(400);
    exit;
}

$event = json_decode($raw, true);
http_response_code(200);

Python

Flaskpython
import hmac, hashlib, os
from flask import request, abort

@app.post("/webhooks/getelectric")
def getelectric_webhook():
    raw = request.get_data()
    header = request.headers.get("X-GetElectric-Signature", "")
    parts = dict(
        piece.strip().split("=", 1)
        for piece in header.split(",")
        if "=" in piece
    )

    timestamp, signature = parts.get("t"), parts.get("v1")
    if not timestamp or not signature:
        abort(400)

    expected = hmac.new(
        os.environ["GETELECTRIC_WEBHOOK_SECRET"].encode(),
        f"{timestamp}.".encode() + raw,
        hashlib.sha256,
    ).hexdigest()

    if not hmac.compare_digest(expected, signature):
        abort(400)

    event = request.get_json()
    return "", 200

Compare in constant time

Use timingSafeEqual, hash_equals or compare_digest. A plain == on the hex leaks, through timing, roughly how much of a guess was right, which is enough to find the rest. Every language has the safe comparison; it is one call.

Reject old timestamps

A valid callback replayed next week is still correctly signed. Compare t with your own clock and refuse anything beyond a sensible window, five minutes say:

Freshnessjs
const age = Math.abs(Date.now() / 1000 - Number(timestamp))
if (age > 300) return res.sendStatus(400)

Be aware of the trade-off before you set that window. We retry a failed delivery for up to about 21 hours, and each retry is signed fresh at the time it is sent, so retries are not the problem. A short window only bites if your own server clock drifts. Keep NTP running.

Test it before you need it

The Webhooks page sends a real, correctly signed callback to your endpoint on demand. The body is a fixed sample, with reference set to test-<unix> and a message saying no order was placed, so nothing of yours should act on it except your signature check.

Get that returning 200 before you place your first order.