# Analysis Result Webhook

> This webhook delivers the **analysis verdict of a case**: overall trust score, signals per dimension, the result for each photo and, if documents were analysed, the detail of each document analysis.

It is **distinct** from the [webhook after certificate validation](/docs/api/webhook), which sends you the content of the case when it is closed. Both can coexist: they serve two different needs, at two different moments.

| | **Case webhook** | **Analysis webhook** |
|---|---|---|
| Trigger | case closing | end of the case analysis |
| Delay | immediate | from a few seconds to ~15 minutes |
| Content | uploaded items, media, certified PDF, your metadata | `trustScore`, verdict, detail of the analyses |
| Configured by | you ([`/company-options/api-settings`](/docs/api/webhook)) or Certificall | **Certificall only** |
| Answers | "what was collected?" | "can I trust what was collected?" |

---

## When exactly it is sent

The analysis of a case is **asynchronous** and is not finished when the case is closed:

1. You **upload** a document. The document analysis starts immediately in the background, and its completion is **awaited** for this case.
2. You **close** the case. The PDF is sealed, the response is immediate. The case switches to "analysis in progress".
3. Certificall **waits for all document analyses** of the case to come back.
4. As soon as the last one is back, the overall score is recalculated and **the webhook is sent**.

Only document analyses are awaited. Image analyses (photo of a photo, duplicate) and context analyses (geolocation, device, battery) do not delay the sending: they feed the score if they are back in time.

:::info A case without any document also receives this webhook
There is then no analysis to wait for: the webhook is sent **right after closing**, with the available fraud signals and an empty `documentAnalyses`.
:::

### Expected delays

| Situation | Delay before receipt |
|---|---|
| Case without any document | a few seconds after closing |
| Nominal document analysis | from a few seconds to about ten minutes |
| Analysis that never came back | **15 minutes**, then sent with `progress: "failed"` |
| Lost closing signal (incident) | caught up automatically, sent up to ~25 minutes after closing |

Design your screens around a "verification in progress" status updated on receipt, never around a blocking wait.

---

## Sending conditions

The webhook is only sent if **all three conditions** are met:

1. **The analysis option is active** for your company. It is a global switch: when disabled, it turns off all analyses and all notifications.
2. **An analysis webhook is configured** on your company (see below).
3. **A usable analysis could be produced.** If computing the verdict keeps failing, the case stops showing "analysis in progress" but **no notification is sent**: there would be nothing usable to deliver.

---

## Configuration

:::caution Configured by Certificall
Unlike the case webhook, this one **cannot be configured through the API**. Send your Certificall contact the URL of your endpoint and the token to present; they will register them on your company.
:::

### URL constraints

The URL is validated **before each sending**. The following are rejected:

- URLs whose scheme is not `http` or `https` — use **`https`**;
- literal IP addresses, and any domain name resolving to a **private, loopback or reserved** address (`10.x`, `172.16-31.x`, `192.168.x`, `127.x`, `169.254.x`, CGNAT and multicast ranges, IPv6 ULA and link-local);
- hosts that do not resolve.

Your endpoint must therefore be **publicly exposed**, on a resolvable domain name.

### Authentication

Three modes, as you choose, depending on what your endpoint can verify:

```http
# Bearer (default)
Authorization: Bearer <your_token>
Content-Type: application/json

# Dedicated header
security-token: <your_token>
Content-Type: application/json

# API key (Make-style integrations)
x-make-apikey: <your_key>
Content-Type: application/json
```

The token is never displayed again once registered: to change it, it is entered again.

:::note No HMAC signature on this webhook
The case webhook accepts an `HMAC-SHA256` signature; this one does not. If the authenticity of the caller matters to you, also filter by shared token and, if needed, by source IP address at network level.
:::

---

## Payload

```json
{
  "caseId": 12345,
  "cfRef": "CAS-12345_CMP-1",
  "progress": "completed",
  "trustScore": 86,
  "analyzeStatus": "GOOD",
  "analysis": {
    "caseId": 12345,
    "trustScore": 86,
    "trustLevel": "GOOD",
    "itemsAnalyzed": 3,
    "signals": [
      { "key": "gps",      "score": 95, "trustLevel": "GOOD" },
      { "key": "device",   "score": 90, "trustLevel": "GOOD" },
      { "key": "document", "score": 88, "trustLevel": "GOOD" }
    ],
    "documentAnalyses": [
      {
        "itemId": 67890,
        "expectedDocumentTypes": ["INVOICE"],
        "detectedDocumentType": "INVOICE",
        "typeMatchScore": 100,
        "crossCheckResults": [
          { "fieldCode": "totalAmount", "fieldLabel": "Total amount", "match": "MATCH" }
        ],
        "crossCheckScore": 100,
        "suspicionScore": 96,
        "suspicionLevel": "NONE",
        "evaluation": 96,
        "progressStatusLevel": "ANALYSIS_COMPLETED",
        "trustScore": 96,
        "analysisDetails": [
          {
            "code": "FONT_CONSISTENCY",
            "label": "Font consistency",
            "status": "VALID",
            "evaluation": 95,
            "suspicionLevel": "NONE",
            "weight": 2
          }
        ]
      }
    ],
    "imageAnalyses": [
      { "itemId": 67891, "trustScore": 92, "trustLevel": "GOOD", "status": "SAFE" }
    ]
  }
}
```

### Envelope

| Field | Type | Description |
|---|---|---|
| `caseId` | Number | Case identifier. **This is your matching key** (see below). |
| `cfRef` | String | Human-readable case reference (`CAS-<id>_CMP-<company>`). |
| `progress` | String | `completed`: full analysis. `failed`: finalised in degraded mode, an analysis did not come back in time. |
| `trustScore` | Number | Overall trust score of the case (0-100, 100 = maximum confidence). |
| `analyzeStatus` | String | `GOOD` (70-100) \| `SUSPICIOUS` (30-69) \| `CRITICAL` (0-29). |
| `analysis` | Object | Full analysis — **exactly the same content** as [`GET /cases/:caseId/analysis`](/docs/api/cases#case-analysis). |

The detail of `analysis` — signals, result of each photo (`imageAnalyses`), document analyses — is described in [API — Cases, case analysis](/docs/api/cases#case-analysis).

:::info The webhook is a snapshot
The content of `analysis` is the one at the time of sending. A photo synchronised afterwards (an app that stayed offline, for example) is not included, and no second webhook is sent: [`GET /cases/:caseId/analysis`](/docs/api/cases#case-analysis) always returns the up-to-date state.
:::

:::danger The webhook carries neither your metadata nor your `reportToken`
Unlike the case webhook, this one returns **only** `caseId` and `cfRef`. Store the `caseId → your record` mapping **when you create the case** (`POST /cases/create` returns the `id`): without it, you will not know what to attach the verdict to.
:::

### Handling `progress`

`progress: "failed"` means the verdict was settled before all analyses came back. The scores present remain readable, but they are **partial**: the `document` signal may be missing or computed on only some of the documents.

**Never validate automatically on a `failed`** — route to a manual review, or query [`GET /cases/:caseId/analysis`](/docs/api/cases#case-analysis) a little later: an analysis that arrives late updates the case.

---

## Delivery guarantees

Read this before designing your endpoint: this webhook is a **notification, not a transactional log**.

| | Behaviour |
|---|---|
| **Duplicates** | **Possible.** An incident during finalisation causes a replay, and a late analysis can **correct** a verdict already delivered: you then receive a second sending for the same `caseId`, with a different score. |
| **Loss** | **Possible.** If your endpoint is unreachable, in error, or takes more than **10 seconds** to respond, the notification is lost: it is **not** sent again. |
| **Order** | Not guaranteed across cases. For a given case, the most recent sending prevails. |

Three practical consequences:

1. **Treat each receipt as an update** of the `caseId` record, never as an insert. A second notification for the same case must overwrite the previous one, not create a new row.
2. **Respond fast and with a 2xx.** Acknowledge receipt immediately and run your business processing in the background; beyond 10 seconds, Certificall abandons the sending.
3. **Plan a safety net.** For critical cases, a periodic sweep of closed cases with no verdict received, via [`GET /cases/:caseId/analysis`](/docs/api/cases#case-analysis), catches lost notifications.

---

## Partner-side handling

```typescript
// POST /webhooks/certificall/analysis (your route)
app.post('/webhooks/certificall/analysis', verifyToken, async (req, res) => {
  const { caseId, progress, trustScore, analyzeStatus, analysis } = req.body;

  // 1) Acknowledge immediately — business processing comes after
  res.status(200).end();

  // 2) Find your record via the caseId stored at creation
  const record = await db.findByCaseId(caseId);
  if (!record) return; // unknown case: ignore, without error

  // 3) Route according to the verdict
  const document = analysis?.documentAnalyses?.[0];
  const suspectPhotos = (analysis?.imageAnalyses ?? []).filter(photo => photo.status === 'SUSPECT');
  const decision =
    progress !== 'completed'      ? 'manual_review' :
    suspectPhotos.length > 0      ? 'manual_review' :
    analyzeStatus === 'GOOD'      ? 'approved' :
                                    'manual_review';

  // 4) Update (never an insert: the webhook may be replayed)
  await db.update(record.id, {
    decision,
    trustScore,
    verdict: analyzeStatus,
    detectedType: document?.detectedDocumentType ?? null,
    tamperingScore: document?.suspicionScore ?? null,
    suspectPhotoIds: suspectPhotos.map(photo => photo.itemId),
    analysisReceivedAt: new Date(),
  });
});
```

---

## When no webhook arrives

| Cause | How to check |
|---|---|
| Analysis option inactive on your company | `GET /cases/:caseId/analysis` responds `403` |
| No analysis webhook registered | to be confirmed with your Certificall contact |
| Case never closed | `GET /cases?caseId=...` returns `closed: false` |
| Endpoint unreachable, in error, or too slow | your own access logs; the notification is not sent again |
| Verdict impossible to produce (lasting incident) | `GET /cases/:caseId/analysis` stays without a score |

In all these cases, [`GET /cases/:caseId/analysis`](/docs/api/cases#case-analysis) remains the source of truth: the webhook is only a notification of what this endpoint already knows.

---

## Checklist

- [ ] Endpoint publicly exposed over **HTTPS**, on a resolvable domain (no literal IP, no private address).
- [ ] URL and token sent to your Certificall contact.
- [ ] Authentication mode chosen and verified on receipt (Bearer, `security-token` or `x-make-apikey`).
- [ ] `caseId → your record` mapping written **when the case is created**.
- [ ] **Idempotent** processing: a second receipt updates, it does not insert.
- [ ] **2xx response in less than 10 seconds**, business processing decoupled.
- [ ] `progress: "failed"` handled explicitly, without automatic validation.
- [ ] Safety net on `GET /cases/:caseId/analysis` for sensitive cases.

---

## Going further

- [API — Cases, case analysis](/docs/api/cases#case-analysis) — full data model and on-demand reading of the result
- [API — Document analysis](/docs/api/analyse_documentaire) — upload a document and read its analysis (French page)
- [Webhook after certificate validation](/docs/api/webhook) — the case content webhook
