Segurança de Webhooks
Para garantir a autenticidade dos webhooks, utilizamos assinatura HMAC-SHA256.
Validação de Assinatura
Cada webhook inclui um header X-ApexPy-Signature com a assinatura HMAC do payload.
Formato do Header
X-ApexPy-Signature: t=1234567890,v1=abc123def456...
t- Timestamp do eventov1- Assinatura HMAC-SHA256
Exemplo de Validação (PHP)
$secret = 'seu_webhook_secret';
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_APEXPY_SIGNATURE'];
// Extrair timestamp e assinatura
preg_match('/t=(\d+),v1=(.+)/', $signature, $matches);
$timestamp = $matches[1];
$receivedSignature = $matches[2];
// Calcular assinatura esperada
$expectedSignature = hash_hmac('sha256', $timestamp . '.' . $payload, $secret);
// Validar
if (hash_equals($expectedSignature, $receivedSignature)) {
// Webhook autêntico
$event = json_decode($payload, true);
// Processar evento
} else {
// Webhook inválido
http_response_code(401);
}
Exemplo de Validação (Node.js)
const crypto = require('crypto');
function validateWebhook(payload, signature, secret) {
const match = signature.match(/t=(\d+),v1=(.+)/);
const timestamp = match[1];
const receivedSignature = match[2];
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(timestamp + '.' + payload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(receivedSignature),
Buffer.from(expectedSignature)
);
}
Boas Práticas
- Sempre valide a assinatura antes de processar o webhook
- Verifique o timestamp para evitar replay attacks
- Use HTTPS para receber webhooks
- Retorne 200 OK rapidamente e processe assincronamente