Aller au contenu
ChadPay
Menu
NOTIFICATIONS EN TEMPS RÉEL

Webhooks & Signatures Cryptographiques

Automatisez le traitement de vos commandes grâce aux webhooks ChadPay. Notifications temps réel, signature HMAC-SHA256 et protection contre les attaques par rejeu.

1. Types d'Événements

Type d'événement Description Propriétés clés du payload
payment.completed Déclenché dès que l'opérateur Mobile Money ou la banque confirme le débit de l'acheteur. paymentId, amount, currency, merchantReference, rail
payment.failed Déclenché en cas d'échec définitif (refus client, solde insuffisant, expiration USSD). paymentId, amount, reason, errorCode

2. Format du Payload Webhook

Chaque événement est envoyé en HTTP POST avec le corps JSON suivant :

{
  "id": "evt_01a17a...",
  "type": "payment.completed",
  "createdAt": "2026-10-26T22:20:00Z",
  "data": {
    "paymentId": "pay_01a17a04...",
    "reference": "PAY-01A17A",
    "merchantReference": "CMD-99482",
    "amount": 25000,
    "currency": "XAF",
    "status": "completed",
    "paymentMethod": "MOBILE_MONEY",
    "rail": "AIRTEL",
    "payerMsisdn": "+23591595839"
  }
}

3. En-têtes HTTP Canoniques & Vérification HMAC-SHA256

Toute requête webhook transmise par les passerelles ChadPay comprend les en-têtes HTTP suivants :

X-ChadPay-Signature: v1=9f83c1626f...
X-ChadPay-Timestamp: 1730000000
X-ChadPay-Event-Id: evt_01a17a049...

Note : Le format compact unifié X-ChadPay-Signature: t=1730000000,v1=... est également supporté de manière transparente.

Algorithme de validation cryptographique :

  1. Vérifiez que le timestamp t se situe dans une fenêtre tolérée de ± 300 secondes par rapport à l'heure serveur (protection anti-rejeu).
  2. Construisez la charge à signer au format canonique : ${timestamp}.${eventId}.${rawBody} (ou ${timestamp}.${rawBody} selon votre schéma de configuration).
  3. Calculez le code HMAC-SHA256 avec votre clé secrète webhook marchand (whsec_...).
  4. Comparez de manière sécurisée (temps constant / timingSafeEqual) la signature calculée avec le hash v1.

4. Exemples de Vérification avec les SDKs Officiels

TypeScript / Node.js (via @chadpay/sdk)

import { WebhooksService, ChadPayWebhookVerificationError } from '@chadpay/sdk';

const webhooks = new WebhooksService();

// Dans votre handler Express / Fastify / AdonisJS / Next.js API route :
export async function handleWebhook(req, res) {
  const rawBody = req.rawBody; // Chaîne brute avant parsing JSON
  const signature = req.headers['x-chadpay-signature'] ?? '';
  const timestamp = req.headers['x-chadpay-timestamp'] ?? '';
  const eventId = req.headers['x-chadpay-event-id'] ?? '';

  try {
    const event = webhooks.constructEvent({
      payload: rawBody,
      signatureHeader: signature,
      timestamp,
      eventId,
      secret: [process.env.CHADPAY_WEBHOOK_SECRET!],
      toleranceSeconds: 300,
    });

    if (event.type === 'payment.succeeded' || event.type === 'payment.completed') {
      console.log('Paiement confirmé :', event.data);
    }

    return res.status(200).json({ received: true });
  } catch (err) {
    if (err instanceof ChadPayWebhookVerificationError) {
      return res.status(401).json({ error: err.reason });
    }
    return res.status(401).json({ error: 'Signature invalide' });
  }
}

PHP 8.1+ (via chadpay/chadpay-php)

<?php
use ChadPay\Webhooks\Webhook;
use ChadPay\Exceptions\ChadPayWebhookVerificationException;

$rawBody = (string) file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_CHADPAY_SIGNATURE'] ?? '';
$timestamp = $_SERVER['HTTP_X_CHADPAY_TIMESTAMP'] ?? '';
$eventId = $_SERVER['HTTP_X_CHADPAY_EVENT_ID'] ?? '';

try {
    $event = Webhook::constructEvent(
        [$_ENV['CHADPAY_WEBHOOK_SECRET']],
        $signature,
        $timestamp,
        $eventId,
        $rawBody,
        300 // tolérance anti-rejeu en secondes
    );

    if (($event['type'] ?? '') === 'payment.succeeded') {
        // Validation sécurisée et idempotente de la commande
    }

    http_response_code(200);
    echo json_encode(['received' => true]);
} catch (ChadPayWebhookVerificationException $e) {
    http_response_code(401);
    echo json_encode(['error' => $e->getReason()]);
}

Python 3.10+ (chadpay-python) & Java 17+ (com.chadpay:chadpay-java)

# Python 3.10+ (chadpay-python)
from chadpay import Webhook

event = Webhook.construct_event(
    secret=[os.environ["CHADPAY_WEBHOOK_SECRET"]],
    signature_header=headers["X-ChadPay-Signature"],
    timestamp=headers.get("X-ChadPay-Timestamp", ""),
    event_id=headers["X-ChadPay-Event-Id"],
    body=raw_body,
    tolerance_seconds=300,
)

// Java 17+ (com.chadpay:chadpay-java)
WebhookEvent event = ChadPayWebhook.constructEvent(
    List.of(System.getenv("CHADPAY_WEBHOOK_SECRET")),
    signatureHeader,
    timestampHeader,
    eventIdHeader,
    rawBody
);