Vous pouvez signer tous vos webhooks avec une clé générée dans Easytools. Cela ne change en rien leur envoi ni leur contenu, mais cela permet au destinataire de vérifier la signature à l’aide de la clé.
Générer une clé de signature de webhook
Voici comment générer des clés de signature pour vos webhooks:
- Allez dans Store → Store settings
- Ouvrez l’onglet API & Webhooks
- Cliquez sur +Generate webhook signing key
- Copiez votre clé en cliquant sur Copy key
Important: pensez bien à copier et à enregistrer la clé de signature, car vous ne pourrez plus y accéder après sa création.
De retour sur le tableau de bord API & Webhooks, vous verrez les informations relatives à votre clé de signature. Vous pouvez aussi la supprimer avec Delete ou générer une nouvelle clé avec Change key.
Utiliser la clé de signature pour vérifier les webhooks
Désormais, chaque requête envoyée au webhook contient un en-tête X-Webhook-Signature. Le destinataire doit le calculer de son côté et comparer les valeurs pour s’assurer qu’elles correspondent.
Pour cela, calculez le SHA256 du contenu de la requête reçue à l’aide de la clé générée précédemment, puis comparez les valeurs.
Consultez les exemples suivants dans différents langages de programmation pour voir comment procéder.
JavaScript (Node.js/Express)
const crypto = require('crypto');
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhook', (req, res) => {
// Get the signature from the headers
const receivedSignature = req.headers['x-webhook-signature'];
// Your webhook signing key (should be stored securely)
const signingKey = 'your_secret_signing_key';
// Get the raw body data
const data = req.body;
const jsonData = JSON.stringify(data);
// Calculate signature using HMAC-SHA256
const calculatedSignature = crypto
.createHmac('sha256', signingKey)
.update(jsonData)
.digest('hex');
// Verify the signature
if (receivedSignature === calculatedSignature) {
console.log('Signature verified successfully!');
res.status(200).send('Webhook received and verified');
} else {
console.log('Signature verification failed!');
res.status(401).send('Invalid signature');
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
PHP
// Get the raw webhook payload without json_decode
$payload = file_get_contents('php://input');
// Get the signature from headers
$receivedSignature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
// Your webhook signing key (should be stored securely)
$signingKey = 'your_secret_signing_key';
// Calculate signature using HMAC-SHA256 directly on the raw payload
$calculatedSignature = hash_hmac('sha256', $payload, $signingKey);
// Verify the signature
if (hash_equals($receivedSignature, $calculatedSignature)) {
http_response_code(200);
echo "Webhook received and verified";
} else {
http_response_code(401);
echo "Invalid signature";
}
Python (Flask)
from flask import Flask, request, jsonify
import hmac
import hashlib
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
# Get the signature from headers
received_signature = request.headers.get('X-Webhook-Signature')
# Your webhook signing key (should be stored securely)
signing_key = 'your_secret_signing_key'
# Get the payload data
payload = request.get_data()
# Calculate signature using HMAC-SHA256
calculated_signature = hmac.new(
signing_key.encode('utf-8'),
payload,
hashlib.sha256
).hexdigest()
# Verify the signature
if hmac.compare_digest(received_signature, calculated_signature):
return jsonify({"message": "Webhook received and verified"}), 200
else:
return jsonify({"message": "Invalid signature"}), 401
if __name__ == '__main__':
app.run(debug=True, port=5000)
C# (.NET)
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseHttpsRedirection();
app.MapPost("/webhook", async context =>
{
// Read the request body
using var reader = new StreamReader(context.Request.Body);
var payload = await reader.ReadToEndAsync();
// Get the signature from headers
context.Request.Headers.TryGetValue("X-Webhook-Signature", out var receivedSignature);
// Your webhook signing key (should be stored securely)
string signingKey = "your_secret_signing_key";
// Calculate signature using HMAC-SHA256
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(signingKey));
var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));
var calculatedSignature = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
// Verify the signature
if (receivedSignature.Equals(calculatedSignature, StringComparison.OrdinalIgnoreCase))
{
context.Response.StatusCode = 200;
await context.Response.WriteAsync("Webhook received and verified");
}
else
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Invalid signature");
}
});
app.Run();