Skip to main content

Webhooks SmartReports

Vue d'ensemble​

SmartReports et SmartBatch livrent des notifications de cycle de vie via le pipeline partagé Webhook et Smart Monitor de Verifik (WebhookEvents). Dès qu'une ligne de lot se termine, qu'un lot s'achève, que le rendu PDF d'un rapport réussit (ou échoue) ou qu'un envoi par e-mail aboutit (ou rebondit), Verifik envoie un événement typé smart_batch_* via HTTP POST.

Format de livraison HTTP et sécurité

Chaque livraison est une requête HTTP POST vers votre URL cible avec un délai d'expiration de 5000 ms (5 secondes) et une enveloppe JSON :

{
"type": "smart_batch_report_generated",
"object": { }
}
  • type — Identifiant exact de l'événement smart_batch_* (smart_batch_report_generated, smart_batch_report_sent, etc.).
  • object — Payload spécifique à l'événement. Les champs internes sensibles (encryptedOcr et prompt) sont retirés s'ils sont présents.
  • Pas d'en-tête de signature HMAC : Les livraisons produit smart_batch_* n'envoient pas actuellement d'en-tête x-verifik-signature. Utilisez toujours HTTPS, protégez votre URL d'écoute avec un jeton secret dans le chemin ou un secret en paramètre de requête / en-tête sur votre URL configurée, et validez object.reportId / object.batchId ainsi que object.externalRefId auprès de GET https://api.verifik.co/v2/smart-reports/{id} (avec Authorization: Bearer <VERIFIK_JWT>) avant de déclencher des actions en aval irréversibles.

Traitez les nouveaux champs facultatifs ajoutés à object comme additifs.


Choix de l'URL cible​

La résolution de l'URL cible dépend de l'origine de l'événement, selon qu'il provient d'une opération SmartReport ou d'une exécution SmartBatch :

Ordre de résolution de l'URL cible
  1. Événements de rapport (smart_batch_report_generated, smart_batch_report_generation_failed, smart_batch_report_sent, smart_batch_report_delivery_failed) :
    1. Surcharge report.webhookUrl par rapport / par exécution (transmise dans POST /v2/smart-reports/run ou POST /v2/smart-reports).
    2. batchConfiguration.notification.webhookUrl sur la BatchConfiguration du lot.
    3. Si aucune des deux n'existe, aucun webhook n'est envoyé.
  2. Événements d'exécution de lot et de ligne (smart_batch_row_completed, smart_batch_batch_completed) :
    • Utilise options.webhookUrl lorsqu'il est transmis explicitement, ou batchConfiguration.notification.webhook / batchConfiguration.notification.webhookUrl.
    • Note : Les exécutions asynchrones FeatureRunner (smart-batch-run-sync) émettent smart_batch_batch_completed en utilisant batchConfiguration.notification.webhookUrl et incluent runId et creditsSpent dans object.

Lorsqu'une webhookUrl est résolue, Verifik recherche ou crée automatiquement un enregistrement Webhook client actif (Smart Batch — <name>) et y associe la BatchConfiguration afin que l'historique des livraisons apparaisse dans Smart Monitor.


Garanties de livraison et calendrier des tentatives​

  • Critère de succès : Votre point de terminaison doit renvoyer une réponse HTTP 2xx en moins de 5000 ms. Renvoyez 200 OK immédiatement et déportez les téléchargements de PDF ou les écritures en base de données vers un worker en arrière-plan.
  • Calendrier des tentatives : En cas de réponse non-2xx, de délai d'attente dépassé ou d'erreur de connexion, Verifik programme jusqu'à 6 nouvelles tentatives selon les intervalles de temporisation [60, 60, 120, 120, 360, 720] minutes (1 h, 1 h, 2 h, 2 h, 6 h, 12 h), arrondis au palier de 10 minutes le plus proche.
  • E-mails de notification facultatifs en cas d'échec/succès : Si l'enregistrement Webhook lié configure notification.email et active notification.success ou notification.fail, Verifik envoie une alerte Mailgun dès la tentative 1.

Cycle de vie des événements​

flowchart TD
B["Lot en cours"] -->|"smart_batch_row_completed\n(mode ligne par ligne)"| R["Lignes terminées"]
B -->|"smart_batch_batch_completed"| F["Lot finalisé"]
R --> F
F -->|"Rendu PDF + score"| G{"Résultat PDF"}
G -->|"succès"| EV1["smart_batch_report_generated"]
G -->|"erreur"| EV2["smart_batch_report_generation_failed"]
EV1 -->|"emailTo / send-email facultatif"| E{"Résultat e-mail"}
E -->|"envoyé"| EV3["smart_batch_report_sent"]
E -->|"échoué"| EV4["smart_batch_report_delivery_failed"]

Catalogue des événements​

type d'événementobject.eventDéclenchementChamps clés de object
smart_batch_report_generated"report.generated"Le rendu PDF du rapport réussit (POST /v2/smart-reports/run, POST /v2/smart-reports/{id}/generate ou finalisation asynchrone du lot).reportId, batchId, templateId, status, rowIndex, pdfSize, pdfEngine, generationDurationMs, downloadUrl, htmlUrl, verificationScore, externalRefId, generatedAt
smart_batch_report_generation_failed"report.generation_failed"Le rendu PDF du rapport échoue.reportId, batchId, templateId, status, error, externalRefId, failedAt
smart_batch_report_sent"report.sent"L'envoi par e-mail du rapport PDF réussit (emailTo sur /run ou POST /v2/smart-reports/{id}/send-email).reportId, batchId, templateId, status, recipients, subject, messageId, downloadUrl, htmlUrl, externalRefId, sentAt
smart_batch_report_delivery_failed"report.delivery_failed"L'envoi par e-mail du rapport PDF échoue ou rebondit.reportId, batchId, templateId, status, recipients, subject, messageId, error, downloadUrl, htmlUrl, externalRefId, sentAt
smart_batch_batch_completed"batch.completed"Toutes les lignes d'un SmartBatch atteignent un état terminal (completed ou failed).batchId, runId, status, creditsSpent, stats
smart_batch_row_completed"row.completed"Une ligne non finale d'un SmartBatch atteint un statut terminal (completed, failed ou partial).batchId, rowIndex, status, results, errors

Schémas d'événements et exemples de payload​

1. smart_batch_report_generated​

Déclenché lorsque le rendu PDF d'un SmartReport est terminé (status: "generated").

ChampTypeDescription
object.eventstringToujours "report.generated".
object.reportIdstringObjectId du SmartReport.
object.batchIdstringObjectId du SmartBatch associé.
object.templateIdstringObjectId du SmartReportTemplate utilisé pour le rendu PDF.
object.statusstring"generated".
object.rowIndexnumberIndex de ligne (base zéro) du lot rendu dans le rapport.
object.pdfSizenumberTaille du fichier PDF généré en octets.
object.pdfEnginestringMoteur utilisé ("puppeteer" ou "pdfkit").
object.generationDurationMsnumberDurée du rendu PDF en millisecondes.
object.downloadUrlstringChemin API relatif /v2/smart-reports/{reportId}/download pour récupérer le PDF binaire.
object.htmlUrlstringChemin API relatif /v2/smart-reports/{reportId}/html pour récupérer le JSON HTML + Verification Score.
object.verificationScoreobject (facultatif)Résumé du score (score, verdict, coverage, profile) lorsque le scoring est activé.
object.externalRefIdstring (facultatif)ID de corrélation de l'appelant transmis sur /run ou lors de la création du rapport.
object.generatedAtstring (ISO 8601)Horodatage de fin de génération.
{
"type": "smart_batch_report_generated",
"object": {
"event": "report.generated",
"reportId": "6740a1b2c3d4e5f678901234",
"batchId": "6740a1b2c3d4e5f678901111",
"templateId": "6740a1b2c3d4e5f678902222",
"status": "generated",
"rowIndex": 0,
"pdfSize": 184320,
"pdfEngine": "puppeteer",
"generationDurationMs": 1420,
"downloadUrl": "/v2/smart-reports/6740a1b2c3d4e5f678901234/download",
"htmlUrl": "/v2/smart-reports/6740a1b2c3d4e5f678901234/html",
"verificationScore": {
"score": 0.9625,
"verdict": "approve",
"coverage": 1,
"profile": "cabify_driver"
},
"externalRefId": "case-12345",
"generatedAt": "2026-11-24T20:15:30.120Z"
}
}

2. smart_batch_report_generation_failed​

Déclenché lorsque la génération du PDF échoue (status: "failed").

ChampTypeDescription
object.eventstringToujours "report.generation_failed".
object.reportIdstringObjectId du SmartReport.
object.batchIdstringObjectId du SmartBatch associé.
object.templateIdstringObjectId du SmartReportTemplate.
object.statusstring"failed".
object.errorstringMessage d'erreur décrivant la cause de l'interruption du rendu.
object.externalRefIdstring (facultatif)ID de corrélation de l'appelant s'il est présent sur le rapport.
object.failedAtstring (ISO 8601)Horodatage de l'échec.
{
"type": "smart_batch_report_generation_failed",
"object": {
"event": "report.generation_failed",
"reportId": "6740a1b2c3d4e5f678901234",
"batchId": "6740a1b2c3d4e5f678901111",
"templateId": "6740a1b2c3d4e5f678902222",
"status": "failed",
"error": "Chromium page timeout while rendering custom font asset",
"externalRefId": "case-12345",
"failedAt": "2026-11-24T20:16:02.450Z"
}
}

3. smart_batch_report_sent​

Déclenché lorsque l'envoi par e-mail du rapport réussit (status: "sent").

ChampTypeDescription
object.eventstringToujours "report.sent".
object.reportIdstringObjectId du SmartReport.
object.batchIdstringObjectId du SmartBatch associé.
object.templateIdstringObjectId du SmartReportTemplate.
object.statusstring"sent".
object.recipientsstring[]Adresses e-mail des destinataires.
object.subjectstringObjet de l'e-mail envoyé.
object.messageIdstringIdentifiant du message chez le fournisseur d'e-mail.
object.downloadUrlstringChemin API relatif /v2/smart-reports/{reportId}/download.
object.htmlUrlstringChemin API relatif /v2/smart-reports/{reportId}/html.
object.externalRefIdstring (facultatif)ID de corrélation de l'appelant s'il est présent sur le rapport.
object.sentAtstring (ISO 8601)Horodatage de fin d'envoi de l'e-mail.
{
"type": "smart_batch_report_sent",
"object": {
"event": "report.sent",
"reportId": "6740a1b2c3d4e5f678901234",
"batchId": "6740a1b2c3d4e5f678901111",
"templateId": "6740a1b2c3d4e5f678902222",
"status": "sent",
"recipients": ["compliance@yourcompany.com"],
"subject": "SmartReport: Colombia Citizen Comprehensive — 2026-11-24",
"messageId": "<20261124201535.1.abc123@mg.verifik.co>",
"downloadUrl": "/v2/smart-reports/6740a1b2c3d4e5f678901234/download",
"htmlUrl": "/v2/smart-reports/6740a1b2c3d4e5f678901234/html",
"externalRefId": "case-12345",
"sentAt": "2026-11-24T20:15:35.800Z"
}
}

4. smart_batch_report_delivery_failed​

Déclenché lorsque l'envoi par e-mail du rapport échoue (status: "failed"), afin que votre intégration puisse distinguer un envoi échoué d'un envoi jamais tenté.

ChampTypeDescription
object.eventstringToujours "report.delivery_failed".
object.reportIdstringObjectId du SmartReport.
object.batchIdstringObjectId du SmartBatch associé.
object.templateIdstringObjectId du SmartReportTemplate.
object.statusstring"failed".
object.recipientsstring[]Adresses e-mail des destinataires.
object.subjectstringObjet de l'e-mail tenté.
object.messageIdstring (facultatif)Identifiant du message chez le fournisseur d'e-mail s'il a été émis avant l'échec.
object.errorstringMessage d'erreur de livraison de l'e-mail.
object.downloadUrlstringChemin API relatif /v2/smart-reports/{reportId}/download.
object.htmlUrlstringChemin API relatif /v2/smart-reports/{reportId}/html.
object.externalRefIdstring (facultatif)ID de corrélation de l'appelant s'il est présent sur le rapport.
object.sentAtstring (ISO 8601)Horodatage de fin de la tentative d'envoi échouée.
{
"type": "smart_batch_report_delivery_failed",
"object": {
"event": "report.delivery_failed",
"reportId": "6740a1b2c3d4e5f678901234",
"batchId": "6740a1b2c3d4e5f678901111",
"templateId": "6740a1b2c3d4e5f678902222",
"status": "failed",
"recipients": ["invalid@nonexistent-domain.test"],
"subject": "SmartReport: Colombia Citizen Comprehensive — 2026-11-24",
"messageId": null,
"error": "Mailgun 400: invalid recipient domain",
"downloadUrl": "/v2/smart-reports/6740a1b2c3d4e5f678901234/download",
"htmlUrl": "/v2/smart-reports/6740a1b2c3d4e5f678901234/html",
"externalRefId": "case-12345",
"sentAt": "2026-11-24T20:15:36.210Z"
}
}

5. smart_batch_batch_completed​

Déclenché une fois lorsqu'un SmartBatch passe à un état terminal ("completed" ou "failed").

ChampTypeDescription
object.eventstringToujours "batch.completed".
object.batchIdstringObjectId du SmartBatch.
object.runIdstring (facultatif)ObjectId de l'exécution FeatureRunner (présent sur les synchronisations FeatureRunner asynchrones).
object.statusstring"completed" ou "failed".
object.creditsSpentnumber (facultatif)Total des crédits Verifik consommés par l'exécution (présent sur les synchronisations FeatureRunner asynchrones).
object.statsobjectCompteurs agrégés : { totalRows, completedRows, failedRows, partialRows }.
{
"type": "smart_batch_batch_completed",
"object": {
"event": "batch.completed",
"batchId": "6740a1b2c3d4e5f678901111",
"runId": "6740a1b2c3d4e5f678903333",
"status": "completed",
"creditsSpent": 12,
"stats": {
"totalRows": 2,
"completedRows": 2,
"failedRows": 0,
"partialRows": 0
}
}
}

6. smart_batch_row_completed​

Déclenché dans les flux de mise à jour de lot ligne par ligne lorsqu'une ligne atteint un état terminal ("completed", "failed" ou "partial") avant que toutes les lignes du lot soient terminées.

ChampTypeDescription
object.eventstringToujours "row.completed".
object.batchIdstringObjectId du SmartBatch.
object.rowIndexnumberIndex de ligne (base zéro) au sein du lot.
object.statusstring"completed", "failed" ou "partial".
object.resultsobjectTable de correspondance des sorties d'étapes de vérification indexée par numéro de séquence.
object.errorsarrayListe des erreurs { step, message, code } enregistrées pour les étapes échouées.
{
"type": "smart_batch_row_completed",
"object": {
"event": "row.completed",
"batchId": "6740a1b2c3d4e5f678901111",
"rowIndex": 0,
"status": "completed",
"results": {
"1": {
"fullName": "JUAN CARLOS PEREZ GOMEZ",
"documentNumber": "123456789"
}
},
"errors": []
}
}

Exemples de récepteurs webhook​

Les implémentations de récepteurs ci-dessous acquittent immédiatement les requêtes en moins de 5 secondes (200 OK), dédupliquent les livraisons répétées de manière idempotente, vérifient le rapport via GET /v2/smart-reports/{id} et téléchargent le PDF à l'aide de Authorization: Bearer <VERIFIK_JWT>.

import express from 'express';
import fs from 'node:fs/promises';

const app = express();
app.use(express.json({ limit: '2mb' }));

const VERIFIK_API_URL = 'https://api.verifik.co';
const VERIFIK_JWT = process.env.VERIFIK_JWT;

// À remplacer par Redis ou un index unique en base de données en production
const processedEvents = new Set();

async function verifyAndDownloadPdf(obj) {
// Vérifier l'événement directement auprès de l'API Verifik avant de faire confiance aux champs du payload
const metaRes = await fetch(`${VERIFIK_API_URL}/v2/smart-reports/${obj.reportId}`, {
headers: { Authorization: `Bearer ${VERIFIK_JWT}` },
});
if (!metaRes.ok) {
throw new Error(`Report lookup failed: HTTP ${metaRes.status}`);
}
const { data: report } = await metaRes.json();

const pdfRes = await fetch(`${VERIFIK_API_URL}${obj.downloadUrl}`, {
headers: { Authorization: `Bearer ${VERIFIK_JWT}` },
});
if (!pdfRes.ok) {
throw new Error(`PDF download failed: HTTP ${pdfRes.status}`);
}

const pdfBuffer = Buffer.from(await pdfRes.arrayBuffer());
const outPath = `./reports/${report.externalRefId || obj.reportId}.pdf`;
await fs.mkdir('./reports', { recursive: true });
await fs.writeFile(outPath, pdfBuffer);
console.log(`Saved ${outPath} (${pdfBuffer.length} bytes), score:`, report.verificationScoreSummary);
}

app.post('/webhooks/verifik-reports', (req, res) => {
const { type, object: obj } = req.body ?? {};
if (!type || !obj) {
return res.status(400).json({ error: 'Invalid webhook payload' });
}

const idempotencyKey = `${type}:${obj.reportId || obj.batchId}:${obj.rowIndex ?? ''}:${obj.status || ''}`;
if (processedEvents.has(idempotencyKey)) {
return res.status(200).json({ received: true, duplicate: true });
}
processedEvents.add(idempotencyKey);

// Acquitter en moins de 5 secondes avant de télécharger les PDF ou de mettre à jour les systèmes en aval
res.status(200).json({ received: true });

setImmediate(async () => {
try {
switch (type) {
case 'smart_batch_report_generated':
await verifyAndDownloadPdf(obj);
break;
case 'smart_batch_report_generation_failed':
console.error('Report generation failed:', obj.reportId, obj.externalRefId, obj.error);
break;
case 'smart_batch_report_sent':
console.log('Report emailed:', obj.reportId, obj.recipients, obj.messageId);
break;
case 'smart_batch_report_delivery_failed':
console.error('Email delivery failed:', obj.reportId, obj.recipients, obj.error);
break;
case 'smart_batch_batch_completed':
console.log('Batch settled:', obj.batchId, obj.status, obj.stats, 'credits:', obj.creditsSpent);
break;
case 'smart_batch_row_completed':
console.log('Row completed:', obj.batchId, obj.rowIndex, obj.status);
break;
default:
console.log('Unhandled SmartBatch event:', type);
}
} catch (err) {
console.error('Async webhook handler failed:', err);
}
});
});

app.listen(3000, () => console.log('SmartReports webhook listener on :3000'));

Voir aussi​