# Have a document analyzed via API (end-to-end flow)

> This guide describes the **end-to-end flow** for having a supporting document analyzed from your system, with no mobile app and no human intervention:

# Document analysis via API — from upload to verdict

1. **Once** — in the Certificall admin, you configure a template containing an *Upload document* step, and you choose how the file is handled: **certified and retained** (digital vault) or **deleted after analysis** (GDPR data minimization).
2. **For each document received** — your backend creates a case, uploads the document to it, then closes the case. Three calls.
3. **A few moments later** — Certificall notifies your webhook with the **trust score** and the analysis details: tampering detection, document type compliance, data cross-checking.

All of this without ever exposing a value extracted from the document: you receive **verdicts and scores**, not personal data.

:::info Required option
Document analysis is an **option in your contract**, enabled by your Certificall contact. See [Document analysis — administration](/docs/admin/analyse_documentaire).
:::

---

## Flow overview

```mermaid
sequenceDiagram
    participant P as Partner backend
    participant C as Certificall backend
    Note over P,C: Once, in the admin: template with an "Upload document" step, configuration and webhooks → frameId, stepId
    Note over P,C: Then for each document
    P->>C: (1) POST /cases/create
    C-->>P: caseId, to store
    P->>C: (2) POST /v2/.../items/:caseId/document
    Note right of C: Document analysis, asynchronous
    P->>C: (3) GET /cases/close/:caseId
    C-->>P: Immediate response + pdfUrl
    Note right of C: Sealed PDF + timestamp
    C->>P: "Case" webhook, immediate
    C->>P: "Analysis" webhook with trustScore and details, from a few seconds to 15 min
```

Two distinct moments, hence **two webhooks**: the case content is sent at closing, the verdict is sent when the analysis is complete. This is the point not to confuse.

---

## Prerequisites

| Prerequisite | How to obtain it |
|------------|-------------------|
| **Document analysis option** | Enabled on your company by your Certificall contact. Without it, no result is produced and no analysis webhook is sent. |
| **Active API account** | Ask your Certificall administrator for an API-type user. The **API > Case > Create** permission is enough for this whole flow. |
| **Configured template** | A template with at least one *Upload document* step, with document analysis enabled. See step 1 below, and [Template and Steps](/docs/admin/trame_etape). |
| **Webhook URL** | An **HTTPS** URL on your side, able to receive a `POST` and authenticate the caller. Literal IP addresses are rejected. Accepted authentication modes: [Webhook after certificate validation](/docs/api/webhook). |
| **Webhook credentials** | The token Certificall will present to your endpoint (`Authorization: Bearer …` or `security-token` header). |

---

## Step 1 — Prepare the template (in the admin, once)

- **References**: [Template and Steps](/docs/admin/trame_etape) — [Document analysis — administration](/docs/admin/analyse_documentaire)

:::caution This step does not go through the API
The API exposes `GET /frames` as read-only: **there is no template creation endpoint**. The template, its steps and the analysis configuration are set up in the admin interface. This is a one-time setup task, not an operation to repeat for each case.
:::

### 1.1 — Add an *Upload document* step

In the template editor, add a step of type **Upload document**. The role of a template and its steps is described in [Template and Steps](/docs/admin/trame_etape). This step type is what opens the simplest upload endpoint (**API > Case > Create** permission, with no additional media permission).

Document analysis also works on a **Photo** step — for a photographed rather than uploaded document — but the upload then goes through `POST /v2/certificall/api/items/:caseId`, which requires the **API > Item > Create** permission. If your flow is a file upload, stick with *Upload document*.

### 1.2 — Enable analysis in the "Config +" tab

- **Reference, with screenshots**: [Configure a template with document analysis](/docs/admin/analyse_documentaire#configure-a-template-with-document-analysis)

Select the step, open **Config +**, then:

- enable **"Enable document analysis"**;
- check the **accepted document types** (invoice, KBIS, tax notice, ID document…). An alert is raised if the detected document does not match any checked type. If the expected type is not in the list, check **"Other document"**: the document then benefits from the general forensic analysis, without the type-specific content checks;
- leave **"Enable cross-check of entered data"** disabled for a first flow (see [Going further](#going-further--enabling-cross-check)).

### 1.3 — The key choice: certify or delete

- **Reference**: [Additional options](/docs/admin/analyse_documentaire#3-additional-options)

Two settings, in two different places in the editor, decide what happens to the file:

| Setting | Where | Effect |
|---|---|---|
| **"Timestamp the document (timestamp + signature)"** | on the step, right-hand panel | The source file is timestamped (eIDAS) and signed. It is retained and its integrity remains verifiable over time: **digital vault use**. Enabled by default. |
| **"Delete the document after analysis (GDPR)"** | Config + tab | The source file is purged from storage as soon as the analysis is complete. Only the result is kept: **data minimization use**. |

:::warning The two cannot be combined
Checking deletion **cancels** timestamping, even if it is enabled on the step: you cannot seal a file you are about to destroy. The admin also displays a warning to that effect. Choose according to your main requirement — evidential value on one side, non-retention on the other.
:::

### 1.4 — Have the webhooks configured

- **References**: [Analysis result webhook](/docs/api/webhook_analyse) — [Webhook after certificate validation](/docs/api/webhook)

Send your Certificall contact the URL and token of your two webhooks. The **analysis result webhook** cannot be configured through the API: it is set by Certificall in your company settings.

The **case reception webhook**, on the other hand, can be changed from your backend:

```bash
curl -X POST https://admin.certificall.app/certificall/api/company-options/api-settings \
  -H "Authorization: Bearer <your_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "endpoint": "https://votre-domaine.fr/webhooks/certificall/dossier",
    "authToken": "<the token we will present to you>",
    "authorizationHeader": "authorization"
  }'
```

---

## Step 2 — Authentication

- **Endpoint**: `POST /certificall/api/auth/token`
- **Reference**: [Public Authentication](/docs/api/token)

```bash
curl -X POST https://admin.certificall.app/certificall/api/auth/token \
  -H "Content-Type: application/json" \
  -d '{ "username": "votre_compte_api", "password": "votre_mot_de_passe" }'
```

```json
{ "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." }
```

Put this token in `Authorization: Bearer <token>` for **all subsequent calls**.

:::tip Best practices
**Cache the token on the backend side** and refresh it before it expires. **Never** expose it to the browser: all the calls described here are made from your server.
:::

---

## Step 3 — Retrieve the `frameId` and `stepId`

- **Endpoint**: `GET /certificall/api/frames`
- **Reference**: [List frames](/docs/api/frames#list-frames)

```bash
curl https://admin.certificall.app/certificall/api/frames \
  -H "Authorization: Bearer <your_token>"
```

```json
[
  {
    "id": 42,
    "name": "Vérification de justificatif",
    "steps": [
      {
        "id": 305,
        "title": "Justificatif de domicile",
        "description": "PDF ou photo lisible",
        "stepAction": "DOCUMENT_UPLOAD",
        "isMandatory": true
      }
    ]
  }
]
```

The `stepAction` field identifies the upload step: look for `DOCUMENT_UPLOAD`.

:::info Only once
`frameId` and `stepId` are stable. Retrieve them **when your integration starts up**, store them on your side, and do not call this endpoint again for each document.
:::

---

## Step 4 — Create the case

- **Endpoint**: `POST /certificall/api/cases/create`
- **Reference**: [Case Management](/docs/api/cases#case-creation)

Only `frameId` is required. Without `userId`, `userMail` or Certilink, the case is attached to your API account: this is the expected mode for a fully server-side flow.

```bash
curl -X POST https://admin.certificall.app/certificall/api/cases/create \
  -H "Authorization: Bearer <your_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "frameId": 42,
    "title": "Justificatif — dossier 2026-000871",
    "metadata": {
      "dossierInterne": "2026-000871",
      "typeAttendu": "justificatif_domicile"
    }
  }'
```

```json
{
  "id": 12345,
  "cfRef": "CAS-12345_CMP-1",
  "frameId": 42,
  "title": "Justificatif — dossier 2026-000871",
  "createdAt": "2026-09-01T10:30:00Z",
  "closed": false
}
```

:::danger Store the `caseId` — it is your only matching key
The analysis result webhook carries `caseId` and `cfRef`, **but neither your `metadata` nor your `reportToken`**. Without a `caseId → your case` mapping table written now, you will not know what to attach the verdict to.
:::

:::note About the `reportToken`
The `reportToken` is used to **group several cases under a single report** (several documents from the same customer, several visits to the same property). It is not a case identifier: generating one per case defeats its purpose. To carry your internal reference, use the case's `metadata` field. See [Report identifier](/docs/admin/reportId).
:::

---

## Step 5 — Upload the document

- **Endpoint**: `POST /v2/certificall/api/items/:caseId/document`
- **Required permission**: **API > Case > Create** — the same as for creating the case
- **Reference**: [Item Management](/docs/api/items)

A single call creates the item, carries the file and triggers the analysis. There is no item to create beforehand.

```bash
curl -X POST https://admin.certificall.app/v2/certificall/api/items/12345/document \
  -H "Authorization: Bearer <your_token>" \
  -F "file=@/path/to/justificatif.pdf" \
  -F 'createItemDto={
    "companyId": 1,
    "stepId": 305,
    "data": "justificatif.pdf",
    "clientAppName": "Portail Souscription",
    "clientAppVersion": "4.2.0",
    "frontCreatedAt": "2026-09-01T10:31:12+02:00",
    "userDeviceManufacturer": "Serveur",
    "userDeviceModel": "API",
    "userDeviceName": "integration-souscription",
    "userDevicePlatform": "Server",
    "userDeviceOs": "Linux",
    "userDeviceOsVersion": "1.0"
  }'
```

```json
{
  "companyId": 1,
  "caseId": 12345,
  "itemId": 98765,
  "documentUrl": "https://admin.certificall.app/certificall/documents/company-1/..."
}
```

### What these fields become on the certificate

`clientAppName`, `clientAppVersion` and `frontCreatedAt` are **required** in v2. When a file is captured by your application and then uploaded via the API, Certificall sees neither the device nor the actual moment of capture: the certificate therefore carries a **"Capture origin"** box that names your application and splits the responsibilities. A missing field returns a `400` that names it.

### File constraints

| Constraint | Value |
|---|---|
| Analyzed formats | **PDF, JPEG, PNG** |
| Maximum size | **~10 MB** |
| Type check | The **actual type** is checked (binary signature), not the extension |

### Error responses

| Code | Cause |
|---|---|
| `400` | Missing v2 contract field, malformed `frontCreatedAt`, file too large, unsupported type, malformed `createItemDto` |
| `403` | The targeted step is not of type *Upload document*, or the case does not belong to your company |
| `404` | No step matches this `stepId` |

:::note The analysis does not respond here
This response confirms the **upload**, not the analysis. The analysis starts asynchronously upon receipt: its result arrives by webhook (step 7).
:::

---

## Step 6 — Close the case

- **Endpoint**: `GET /certificall/api/cases/close/:caseId`
- **Reference**: [Closing a Case](/docs/api/cases#closing-a-case)

Closing seals the case, produces the certified PDF and **arms the delivery of the analysis result**. Without it, no analysis webhook is sent.

```bash
curl https://admin.certificall.app/certificall/api/cases/close/12345 \
  -H "Authorization: Bearer <your_token>"
```

```json
{
  "status": "Success",
  "message": "Case closed successfully",
  "caseId": 12345,
  "pdfUrl": "https://admin.certificall.app/certificall/share/..."
}
```

:::info Closing does not wait for the analysis
This call responds **immediately**, as soon as the PDF is sealed. Document analysis continues in the background. Do not wait for anything here: your interface can hand control back to the user right away, the verdict will arrive by webhook.
:::

---

## Step 7 — Receive the result

### 7.1 — The two webhooks, not to be confused

| | **Case reception webhook** | **Analysis result webhook** |
|---|---|---|
| Triggered | at closing, immediately | when the analysis is complete |
| Content | uploaded items, `documentUrl`, `caseUrl` (PDF), your `metadata` | `caseId`, `cfRef`, `trustScore`, `analyzeStatus`, detailed analysis |
| Configurable by you | yes, `POST /company-options/api-settings` | no — set by Certificall |
| Useful for | archiving the document and the certificate | deciding: automatic validation or manual review |

For a document analysis flow, **the second one is the one that carries the value**. The first remains useful if you archive the PDF or the document on your side: its content and authentication modes are detailed in [Webhook after certificate validation](/docs/api/webhook).

### 7.2 — Analysis result webhook payload

- **Detailed reference**: [Analysis result webhook](/docs/api/webhook_analyse) — sending conditions, authentication, delivery guarantees

```json
{
  "caseId": 12345,
  "cfRef": "CAS-12345_CMP-1",
  "progress": "completed",
  "trustScore": 86,
  "analyzeStatus": "GOOD",
  "analysis": {
    "caseId": 12345,
    "trustScore": 86,
    "trustLevel": "GOOD",
    "itemsAnalyzed": 1,
    "signals": [
      { "key": "document", "score": 88, "trustLevel": "GOOD" }
    ],
    "documentAnalyses": [
      {
        "itemId": 98765,
        "expectedDocumentTypes": ["DOT-JUST_DOMICILE"],
        "detectedDocumentType": "DOT-JUST_DOMICILE",
        "typeMatchScore": 100,
        "crossCheckResults": null,
        "crossCheckScore": null,
        "suspicionScore": 96,
        "suspicionLevel": "NONE",
        "evaluation": 96,
        "progressStatusLevel": "ANALYSIS_COMPLETED",
        "trustScore": 96,
        "analysisDetails": [
          {
            "code": "FONT_CONSISTENCY",
            "label": "Cohérence des polices",
            "status": "VALID",
            "evaluation": 95,
            "suspicionLevel": "NONE",
            "weight": 2
          }
        ]
      }
    ]
  }
}
```

Two fields drive your decision:

- **`progress`** — `"completed"`: full analysis. `"failed"`: finalized in degraded mode, an analysis did not come back in time. The scores present remain usable, but they are partial: do not validate automatically on a `failed`.
- **`analyzeStatus`** — `GOOD` (70-100), `SUSPICIOUS` (30-69), `CRITICAL` (0-29).

The content of `analysis` is **identical** to the one returned by `GET /cases/:caseId/analysis`, whose full model is detailed in [API — Document analysis](/docs/api/analyse_documentaire).

### 7.3 — Partner-side processing

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

  // 1) Find your case — via the caseId stored in step 4
  const dossier = await db.findByCaseId(caseId);
  if (!dossier) return res.status(200).end(); // never return an error for an unknown case

  // 2) Route according to the verdict
  const documentaire = analysis?.documentAnalyses?.[0];
  const decision =
    progress !== 'completed'      ? 'revue_manuelle' :
    analyzeStatus === 'GOOD'      ? 'valide' :
                                    'revue_manuelle';

  await db.update(dossier.id, {
    decision,
    trustScore,
    typeDetecte: documentaire?.detectedDocumentType ?? null,
    scoreFalsification: documentaire?.suspicionScore ?? null,
  });

  res.status(200).end();
});
```

:::warning Idempotency
The webhook may be re-sent: a late analysis may correct a verdict already delivered. Treat each receipt as an **update** of case `caseId`, never as an insert.
:::

### 7.4 — Fallback: query the result yourself

If you cannot expose a public URL, the same content is available for reading:

- **Endpoint**: `GET /certificall/api/cases/:caseId/analysis`

```bash
curl https://admin.certificall.app/certificall/api/cases/12345/analysis \
  -H "Authorization: Bearer <your_token>"
```

As long as the analysis is not complete, the `documentAnalyses` block may be partial: rely on `progressStatusLevel` — `ANALYSIS_COMPLETED` signals the end.

:::caution Polling has a cost
Your API calls are subject to [rate limits](/docs/api/rate_limits), and an analysis can take several minutes: a tight loop quickly hits these limits without speeding up the result. Space out your queries (30 s then 1 min, for example) and set a cap. The webhook remains the recommended mode.
:::

---

## How long it takes

| Step | Order of magnitude |
|---|---|
| Document upload | immediate |
| Case closing | immediate |
| **Document analysis** | from a few seconds to **about ten minutes** depending on the document |
| Analysis webhook sent | as soon as all analyses of the case have come back |
| Maximum delay before degraded finalization | **15 minutes** — beyond that, the webhook is sent with `progress: "failed"` and the partial analysis |

Design your screens accordingly: a "verification in progress" status that updates when the webhook is received, never a blocking wait.

---

## Step 8 — Retrieve the certified PDF

In **certification** mode (deletion after analysis disabled), the uploaded document is timestamped and signed, and the case produces a certified PDF:

- via the `pdfUrl` field returned by the closing call;
- via `caseUrl` in the case reception webhook;
- via a **Share Token** if you need to expose the PDF to a third party without passing on your token — see [Certificate via a Share Token](/docs/api/share_token);
- via [reports](/docs/api/reports), if you group several cases under the same `reportToken`.

In **deletion after analysis** mode, the source file no longer exists and is therefore not certified: only the analysis result remains.

---

## Going further — enabling cross-check

The document score is the lowest of **three scores out of 100**: tampering analysis, document type compliance, and **cross-consistency** — cross-checking what the document says against what the case declares elsewhere.

The minimal flow described above only uses the first two: with a single step in the template, there is nothing to cross-check, and `crossCheckScore` stays `null`.

To enable the third, add **data entry steps** to the template before the document step (name, address, amount…), then in **Config +**:

1. enable **"Enable cross-check of entered data"**;
2. select the steps whose values must be cross-checked against the document.

On the API side, these entries are submitted before the document:

```bash
curl -X POST https://admin.certificall.app/v2/certificall/api/items/create \
  -H "Authorization: Bearer <your_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "caseId": 12345,
    "stepId": 303,
    "data": "12 rue des Lilas, 75011 Paris",
    "clientAppName": "Portail Souscription",
    "clientAppVersion": "4.2.0",
    "frontCreatedAt": "2026-09-01T10:30:45+02:00"
  }'
```

The webhook then returns a verdict per cross-checked field, **without ever delivering the compared values**:

```json
"crossCheckResults": [
  { "fieldCode": "address", "fieldLabel": "Adresse", "match": "MATCH" },
  { "fieldCode": "lastName", "fieldLabel": "Nom", "match": "MISMATCH" }
],
"crossCheckScore": 50
```

---

## Privacy: zero personal data returned

Neither the webhook nor the analysis API returns the **values extracted** from the document (names, amounts, addresses, dates). You only receive **facts**: `MATCH` / `MISMATCH` / `MISSING` verdicts, scores and control criteria.

Combined with the **"Delete the document after analysis"** option, this enables an integration where your system never stores or receives the document: only the result.

---

## Endpoint summary

| Step | Method | Endpoint | Documentation |
|-------|---------|----------|---------------|
| 2. Authentication | `POST` | `/certificall/api/auth/token` | [`/docs/api/token`](/docs/api/token) |
| 3. List templates | `GET` | `/certificall/api/frames` | [`/docs/api/frames`](/docs/api/frames#list-frames) |
| 4. Create the case | `POST` | `/certificall/api/cases/create` | [`/docs/api/cases`](/docs/api/cases#case-creation) |
| 5. Upload the document | `POST` | `/v2/certificall/api/items/:caseId/document` | [`/docs/api/items`](/docs/api/items) |
| 5 bis. Submit a data entry | `POST` | `/v2/certificall/api/items/create` | [`/docs/api/items`](/docs/api/items) |
| 6. Close | `GET` | `/certificall/api/cases/close/:caseId` | [`/docs/api/cases`](/docs/api/cases#closing-a-case) |
| 7. Analysis webhook | `POST` | `<your URL>` | [`/docs/api/webhook_analyse`](/docs/api/webhook_analyse) |
| 7 bis. Read the result | `GET` | `/certificall/api/cases/:caseId/analysis` | [`/docs/api/analyse_documentaire`](/docs/api/analyse_documentaire) |
| 1.4. Configure the case webhook | `POST` | `/certificall/api/company-options/api-settings` | [`/docs/api/webhook`](/docs/api/webhook) |

**Full Swagger**: [admin.certificall.app/certificall/public/swagger](https://admin.certificall.app/certificall/public/swagger)

---

## Go-live checklist

- [ ] Document analysis option enabled on your company.
- [ ] Template created, *Upload document* step configured, document types checked.
- [ ] File handling decided: **timestamping** (vault) **or** **deletion after analysis** (GDPR).
- [ ] `frameId` and `stepId` retrieved once and stored on the partner side.
- [ ] `caseId → your case` mapping table written **when the case is created**.
- [ ] API token cached on the backend side, never exposed to the browser.
- [ ] Analysis webhook sent to Certificall and tested end to end.
- [ ] Webhook processing is **idempotent** (a re-send updates, it does not insert).
- [ ] `progress: "failed"` case handled explicitly — never automatically validated.
- [ ] Interface designed around an asynchronous status, with no blocking wait.
- [ ] Full test: creation → upload → closing → verdict received.

---

## Further reading

- [API — Document analysis](/docs/api/analyse_documentaire) — full data model, triple scoring
- [Document analysis — administration](/docs/admin/analyse_documentaire) — detailed template configuration
- [Item Management](/docs/api/items) — v2 upload contract and media endpoints
- [Analysis result webhook](/docs/api/webhook_analyse) — full reference for the webhook that carries the verdict
- [Webhook after certificate validation](/docs/api/webhook) — case reception webhook
- [Template and Steps](/docs/admin/trame_etape) — what a template is, which step types exist
- [Report identifier](/docs/admin/reportId) — group several cases under a single report
- [Rate limits](/docs/api/rate_limits) — number of calls allowed per minute
- [Integrating a "Certify" button](/docs/use-case/integration-bouton-certilink) — the equivalent flow with capture by the end user
