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

# Webhook Verification

> Verify webhook authenticity using HMAC signatures

## Overview

All Daya webhooks include an `X-Daya-Signature` header containing an HMAC-SHA256 signature of the payload. **Always verify** this signature to ensure the webhook came from Daya.

> [!WARNING]
>
> Never process unverified webhooks. Attackers could send fake webhooks to manipulate your system.

## Signature Header

```
X-Daya-Signature: a8f5f167f44f4964e6c998dee827110c447be52d40d67b6a60b78c1e3e01b7e8
```

## Verification Algorithm

1. Get raw request body as string
2. Compute HMAC-SHA256 using your webhook secret
3. Compare computed signature with `X-Daya-Signature` header
4. Use timing-safe comparison to prevent timing attacks

## Implementation Examples

```javascript Node.js theme={"dark"}
const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  // Compute expected signature
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload, 'utf8')
    .digest('hex');
  
  // Timing-safe comparison
  try {
    return crypto.timingSafeEqual(
      Buffer.from(signature),
      Buffer.from(expectedSignature)
    );
  } catch (error) {
    return false;
  }
}

// Express.js middleware
app.post('/webhooks/daya', express.raw({ type: 'application/json' }), (req, res) => {
  const signature = req.headers['x-daya-signature'];
  const payload = req.body.toString('utf8');
  
  if (!verifyWebhookSignature(payload, signature, process.env.DAYA_WEBHOOK_SECRET)) {
    return res.status(401).json({ error: 'Invalid signature' });
  }
  
  // Process webhook...
  const event = JSON.parse(payload);
  res.status(200).send('OK');
});
```

```python Python theme={"dark"}
import hmac
import hashlib

def verify_webhook_signature(payload: bytes, signature: str, secret: str) -> bool:
    """Verify webhook HMAC signature"""
    expected_signature = hmac.new(
        secret.encode('utf-8'),
        payload,
        hashlib.sha256
    ).hexdigest()
    
    # Timing-safe comparison
    return hmac.compare_digest(signature, expected_signature)

# Flask example
from flask import Flask, request, jsonify

@app.route('/webhooks/daya', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-Daya-Signature')
    payload = request.get_data()
    
    if not verify_webhook_signature(payload, signature, DAYA_WEBHOOK_SECRET):
        return jsonify({'error': 'Invalid signature'}), 401
    
    # Process webhook...
    event = request.json
    return jsonify({'status': 'ok'}), 200
```

```go Go theme={"dark"}
package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "io"
    "net/http"
)

func verifyWebhookSignature(payload []byte, signature string, secret string) bool {
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write(payload)
    expectedSignature := hex.EncodeToString(mac.Sum(nil))
    return hmac.Equal([]byte(signature), []byte(expectedSignature))
}

func handleWebhook(w http.ResponseWriter, r *http.Request) {
    signature := r.Header.Get("X-Daya-Signature")
    payload, _ := io.ReadAll(r.Body)
    
    if !verifyWebhookSignature(payload, signature, DAYA_WEBHOOK_SECRET) {
        http.Error(w, "Invalid signature", http.StatusUnauthorized)
        return
    }
    
    // Process webhook...
    w.WriteHeader(http.StatusOK)
}
```

```php PHP theme={"dark"}
<?php

function verifyWebhookSignature($payload, $signature, $secret) {
    $expectedSignature = hash_hmac('sha256', $payload, $secret);
    return hash_equals($signature, $expectedSignature);
}

// Handle webhook
$signature = $_SERVER['HTTP_X_DAYA_SIGNATURE'];
$payload = file_get_contents('php://input');

if (!verifyWebhookSignature($payload, $signature, $webhookSecret)) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid signature']);
    exit;
}

// Process webhook...
$event = json_decode($payload, true);
http_response_code(200);
echo json_encode(['status' => 'ok']);
```

## Important Notes

> [accordion] Use raw request body
>
> **Critical:** Compute HMAC on the **raw request body** before parsing JSON. Parsing changes whitespace and ordering, breaking the signature.
>
> ```javascript theme={"dark"}
> // ✅ Correct: Use raw body
> app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
>   const payload = req.body.toString('utf8');
>   verify(payload, signature, secret);
> });
>
> // ❌ Wrong: JSON.stringify changes format
> app.post('/webhooks', express.json(), (req, res) => {
>   const payload = JSON.stringify(req.body); // Wrong!
>   verify(payload, signature, secret);
> });
> ```

> [accordion] Use timing-safe comparison
>
> Regular string comparison (==) is vulnerable to timing attacks. Use constant-time comparison:
>
> * Node.js: `crypto.timingSafeEqual()`
> * Python: `hmac.compare_digest()`
> * Go: `hmac.Equal()`
> * PHP: `hash_equals()`

> [accordion] Keep secrets secure
>
> * Store webhook secret in environment variables
> * Never commit secrets to version control
> * Rotate secrets regularly
> * Use different secrets for sandbox and production

## Testing Verification

Generate test signatures for local testing:

```bash CLI theme={"dark"}
# Generate test signature
echo -n '{"event":"withdrawal.completed","timestamp":"2026-03-10T09:03:00Z","data":{"id":"550e8400-e29b-41d4-a716-446655440000"}}' | \
  openssl dgst -sha256 -hmac "your_webhook_secret" | \
  awk '{print $2}'
```

```javascript Node.js theme={"dark"}
const crypto = require('crypto');

function generateTestSignature(payload, secret) {
  return crypto
    .createHmac('sha256', secret)
    .update(payload, 'utf8')
    .digest('hex');
}

const payload = '{"event":"withdrawal.completed","timestamp":"2026-03-10T09:03:00Z","data":{"id":"550e8400-e29b-41d4-a716-446655440000"}}';
const signature = generateTestSignature(payload, 'your_webhook_secret');
console.log(signature);
```

## Common Issues

> [accordion] Signature always fails
>
> **Possible causes:**
>
> * Using wrong webhook secret
> * Not using raw request body
> * Character encoding issues
>
> **Debug:**
>
> ```javascript theme={"dark"}
> console.log('Received signature:', signature);
> console.log('Expected signature:', expectedSignature);
> console.log('Payload:', payload);
> console.log('Secret (first 4 chars):', secret.substring(0, 4));
> ```

> [accordion] Intermittent failures
>
> **Cause:** Parsing JSON before verification
>
> **Fix:** Always compute HMAC on raw body, then parse JSON

## Next Steps

> [card] [Webhook Overview](https://docs.daya.co/api-reference/webhooks/overview.md)
>
> Learn about webhook delivery and event types

> [card] [Webhook Events](https://docs.daya.co/api-reference/webhooks/events.md)
>
> Event schemas and payloads


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.