Verify Webhook

Why do we need to verify?

Once the server is configured to receive payloads, it will listen for any deliveries sent to the endpoint you configured. To ensure that your server only processes Webhooks sent by NFTGo and to verify that the webhook has not been tampered with, you should validate the webhook signature before further processing the delivery. This helps avoid server time processing webhooks that did not come from NFTGo and also helps prevent man-in-the-middle attacks.

How to verify webhook?

Step1: Retrieve signature

  • If you set the webhook manually, use the 'signing key' provided in the configuration interface.

  • If you use API to set up webhooks, need to generate the signature, use the body and secret of the webhook, and generate it using the HMAC SHA-256 method. The following code sample calculates the expected signature:

import hmac
import hashlib
def verify_webhook_signature(signature: str, body: bytes, secret: str):
    key = bytes(secret, 'utf-8')
    h = hmac.new(key, body, hashlib.sha256)
    expected_signature = h.hexdigest()
    # Compare the generated signature with the header x-signature
    return hmac.compare_digest(bytes(signature, 'utf-8'), bytes(expected_signature, 'utf-8'))

function verifyWebhookSignature(signature, body, secret) {
  const key = Buffer.from(secret, 'utf-8');
  const hmac = crypto.createHmac('sha256', key);
  hmac.update(body);
  const expectedSignature = hmac.digest('hex');
  // Compare the generated signature with the header x-signature
  return crypto.timingSafeEqual(Buffer.from(signature, 'utf-8'), Buffer.from(expectedSignature, 'utf-8'));
}

When verifying webhooks, it's important to use the raw request body as the cryptographic signature is sensitive to even the smallest changes. Be cautious of frameworks that parse the request as JSON and then stringify it, as this can also disrupt the signature verification.

Step 2: Retrieve the notification's signature

  • check the x-signaturein in the request header.

Step 3: Compare the two signatures and check if they are consistent.

  • If they are consistent, the verification is successful.