Skip to main content

SmartReports Webhook

概要​

SmartReports と SmartBatch は、Verifik 共通の Webhook および Smart Monitor 配信パイプライン(WebhookEvents)を通じてライフサイクル通知を配信します。バッチ行が完了したとき、バッチ全体が終了したとき、レポート PDF のレンダリングが成功(または失敗)したとき、あるいはメール配信が成功(またはバウンス)したときに、Verifik は型付きの smart_batch_* イベントを HTTP POST で送信します。

HTTP 配信形式とセキュリティ

各配信は、ターゲット URL への 5000 ms(5 秒) タイムアウトの HTTP POST リクエストであり、次の JSON エンベロープを使用します。

{
"type": "smart_batch_report_generated",
"object": { }
}
  • type — 正確な smart_batch_* イベント識別子(smart_batch_report_generated、smart_batch_report_sent など)。
  • object — イベント固有のペイロード。機密性の高い内部フィールド(encryptedOcr や prompt)が存在する場合は削除されます。
  • HMAC 署名ヘッダーなし: smart_batch_* プロダクトの配信では、現在 x-verifik-signature ヘッダーは送信されません。必ず HTTPS を使用し、設定する URL のパス内シークレットトークンやクエリ/ヘッダーシークレットでリスナー URL を保護し、取り消せない後続アクションを実行する前に GET https://api.verifik.co/v2/smart-reports/{id}(Authorization: Bearer <VERIFIK_JWT> を使用)に対して object.reportId / object.batchId および object.externalRefId を検証してください。

object に追加される新しい任意フィールドは追加的(additive)なものとして扱ってください。


ターゲット URL の決定方法​

ターゲット URL の解決方法は、イベントが SmartReport 操作と SmartBatch 実行のどちらから発生したかによって異なります。

ターゲット URL の解決順序
  1. レポートイベント(smart_batch_report_generated、smart_batch_report_generation_failed、smart_batch_report_sent、smart_batch_report_delivery_failed):
    1. レポート単位 / 実行単位の report.webhookUrl 上書き指定(POST /v2/smart-reports/run または POST /v2/smart-reports で指定)。
    2. バッチの BatchConfiguration 上の batchConfiguration.notification.webhookUrl。
    3. どちらも存在しない場合、Webhook は送信されません。
  2. バッチおよび行の実行イベント(smart_batch_row_completed、smart_batch_batch_completed):
    • 明示的に渡された場合は options.webhookUrl を使用し、それ以外は batchConfiguration.notification.webhook / batchConfiguration.notification.webhookUrl を使用します。
    • 注記: 非同期の FeatureRunner 実行(smart-batch-run-sync)では、batchConfiguration.notification.webhookUrl を使用して smart_batch_batch_completed を発行し、object に runId と creditsSpent を含めます。

webhookUrl が解決されると、Verifik は有効なクライアント Webhook レコード(Smart Batch — <name>)を自動的に検索または作成し、BatchConfiguration にリンクすることで、配信履歴が Smart Monitor に表示されるようにします。


配信保証とリトライスケジュール​

  • 成功基準: エンドポイントは 5000 ms 以内に HTTP 2xx レスポンスを返す必要があります。即座に 200 OK を返し、PDF のダウンロードやデータベースへの書き込みはバックグラウンドワーカーへオフロードしてください。
  • リトライスケジュール: 非 2xx レスポンス、タイムアウト、または接続エラーが発生した場合、Verifik はバックオフ間隔 [60, 60, 120, 120, 360, 720] 分(1時間、1時間、2時間、2時間、6時間、12時間、最も近い 10 分単位に丸められます)で最大 6 回の再試行 をスケジュールします。
  • 失敗/成功時の任意通知メール: リンクされた Webhook レコードに notification.email が設定されており、notification.success または notification.fail が有効になっている場合、Verifik は 1 回目の試行 時に Mailgun アラートを送信します。

イベントライフサイクル​

flowchart TD
B["バッチ実行中"] -->|"smart_batch_row_completed\n(行単位モード)"| R["行の処理完了"]
B -->|"smart_batch_batch_completed"| F["バッチ確定"]
R --> F
F -->|"PDF レンダリング + スコア計算"| G{"PDF 結果"}
G -->|"成功"| EV1["smart_batch_report_generated"]
G -->|"エラー"| EV2["smart_batch_report_generation_failed"]
EV1 -->|"任意の emailTo / send-email"| E{"メール送信結果"}
E -->|"送信済み"| EV3["smart_batch_report_sent"]
E -->|"失敗"| EV4["smart_batch_report_delivery_failed"]

イベントカタログ​

イベント typeobject.event発火タイミングobject の主要フィールド
smart_batch_report_generated"report.generated"レポート PDF のレンダリングが成功したとき(POST /v2/smart-reports/run、POST /v2/smart-reports/{id}/generate、または非同期バッチ完了時)。reportId, batchId, templateId, status, rowIndex, pdfSize, pdfEngine, generationDurationMs, downloadUrl, htmlUrl, verificationScore, externalRefId, generatedAt
smart_batch_report_generation_failed"report.generation_failed"レポート PDF のレンダリングに失敗したとき。reportId, batchId, templateId, status, error, externalRefId, failedAt
smart_batch_report_sent"report.sent"レポート PDF のメール配信が成功したとき(/run の emailTo または 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"レポート PDF のメール配信が失敗またはバウンスしたとき。reportId, batchId, templateId, status, recipients, subject, messageId, error, downloadUrl, htmlUrl, externalRefId, sentAt
smart_batch_batch_completed"batch.completed"SmartBatch 内のすべての行が終了状態(completed または failed)に達したとき。batchId, runId, status, creditsSpent, stats
smart_batch_row_completed"row.completed"SmartBatch 内の最終行以外の行が終了ステータス(completed、failed、または partial)に達したとき。batchId, rowIndex, status, results, errors

イベントスキーマとペイロード例​

1. smart_batch_report_generated​

SmartReport PDF のレンダリングが完了したとき(status: "generated")に発火します。

フィールド型説明
object.eventstring常に "report.generated"。
object.reportIdstringSmartReport の ObjectId。
object.batchIdstring関連付けられた SmartBatch の ObjectId。
object.templateIdstringPDF のレンダリングに使用された SmartReportTemplate の ObjectId。
object.statusstring"generated"。
object.rowIndexnumberレポートにレンダリングされた 0 始まりのバッチ行インデックス。
object.pdfSizenumberレンダリングされた PDF のファイルサイズ(バイト)。
object.pdfEnginestring使用されたエンジン("puppeteer" または "pdfkit")。
object.generationDurationMsnumberPDF レンダリングにかかった時間(ミリ秒)。
object.downloadUrlstringPDF バイナリを取得するための相対 API パス /v2/smart-reports/{reportId}/download。
object.htmlUrlstringHTML + 検証スコア JSON を取得するための相対 API パス /v2/smart-reports/{reportId}/html。
object.verificationScoreobject (任意)スコアリングが有効な場合のスコアサマリー(score、verdict、coverage、profile)。
object.externalRefIdstring (任意)/run またはレポート作成時に渡された呼び出し元の相関 ID。
object.generatedAtstring (ISO 8601)生成が完了したタイムスタンプ。
{
"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​

PDF 生成が失敗したとき(status: "failed")に発火します。

フィールド型説明
object.eventstring常に "report.generation_failed"。
object.reportIdstringSmartReport の ObjectId。
object.batchIdstring関連付けられた SmartBatch の ObjectId。
object.templateIdstringSmartReportTemplate の ObjectId。
object.statusstring"failed"。
object.errorstringレンダリングが中止された理由を示すエラーメッセージ。
object.externalRefIdstring (任意)レポートに存在する場合の呼び出し元相関 ID。
object.failedAtstring (ISO 8601)失敗が発生したタイムスタンプ。
{
"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​

レポートのメール配信が成功したとき(status: "sent")に発火します。

フィールド型説明
object.eventstring常に "report.sent"。
object.reportIdstringSmartReport の ObjectId。
object.batchIdstring関連付けられた SmartBatch の ObjectId。
object.templateIdstringSmartReportTemplate の ObjectId。
object.statusstring"sent"。
object.recipientsstring[]受信者のメールアドレス。
object.subjectstring送信されたメールの件名。
object.messageIdstringメールプロバイダのメッセージ ID。
object.downloadUrlstring相対 API パス /v2/smart-reports/{reportId}/download。
object.htmlUrlstring相対 API パス /v2/smart-reports/{reportId}/html。
object.externalRefIdstring (任意)レポートに存在する場合の呼び出し元相関 ID。
object.sentAtstring (ISO 8601)メール送信が完了したタイムスタンプ。
{
"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​

レポートのメール配信が失敗したとき(status: "failed")に発火します。これにより、統合システムは試行されなかった送信と失敗した送信を区別できます。

フィールド型説明
object.eventstring常に "report.delivery_failed"。
object.reportIdstringSmartReport の ObjectId。
object.batchIdstring関連付けられた SmartBatch の ObjectId。
object.templateIdstringSmartReportTemplate の ObjectId。
object.statusstring"failed"。
object.recipientsstring[]受信者のメールアドレス。
object.subjectstring送信を試みたメールの件名。
object.messageIdstring (任意)失敗前に発行されていた場合のメールプロバイダのメッセージ ID。
object.errorstringメール配信エラーメッセージ。
object.downloadUrlstring相対 API パス /v2/smart-reports/{reportId}/download。
object.htmlUrlstring相対 API パス /v2/smart-reports/{reportId}/html。
object.externalRefIdstring (任意)レポートに存在する場合の呼び出し元相関 ID。
object.sentAtstring (ISO 8601)失敗した送信試行が完了したタイムスタンプ。
{
"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​

SmartBatch が終了状態("completed" または "failed")に遷移したときに 1 回発火します。

フィールド型説明
object.eventstring常に "batch.completed"。
object.batchIdstringSmartBatch の ObjectId。
object.runIdstring (任意)FeatureRunner 実行の ObjectId(非同期 FeatureRunner 同期実行時に含まれます)。
object.statusstring"completed" または "failed"。
object.creditsSpentnumber (任意)実行によって消費された合計 Verifik クレジット数(非同期 FeatureRunner 同期実行時に含まれます)。
object.statsobject集計カウント: { 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​

バッチ内のすべての行が完了する前に、いずれかの行が終了状態("completed"、"failed"、または "partial")に達したときに、行単位バッチ更新フローで発火します。

フィールド型説明
object.eventstring常に "row.completed"。
object.batchIdstringSmartBatch の ObjectId。
object.rowIndexnumberバッチ内の 0 始まりの行インデックス。
object.statusstring"completed"、"failed"、または "partial"。
object.resultsobjectステップ番号(sequence)をキーとした検証ステップ出力のマップ。
object.errorsarray失敗したステップに対して記録された { step, message, code } エラーのリスト。
{
"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": []
}
}

Webhook レシーバーの実装例​

以下のレシーバー実装では、5 秒以内に即座にリクエストへ応答(200 OK)し、重複配信を冪等に排除し、GET /v2/smart-reports/{id} でレポートを検証したうえで、Authorization: Bearer <VERIFIK_JWT> を使用して PDF をダウンロードしています。

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;

// Replace with Redis or a unique DB index in production
const processedEvents = new Set();

async function verifyAndDownloadPdf(obj) {
// Verify the event directly against Verifik API before trusting payload fields
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);

// Acknowledge within 5 seconds before downloading PDFs or updating downstream systems
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'));

関連項目​