# Receive a photo or a document from the customer and download it

_Yes — a photo, PDF, audio or video reaches your webhook (type image, document, audio, video) and is downloaded with GET /v1/media/{id} (redirect to a URL valid for 1 h); receiving: 1,000 free messages a month, then 1 credit per 20._

Keywords: receive photo, receive document, receive PDF, attachment, ID document, proof, payment receipt, screenshot, received image, download media, media_id, media_url, audio, video, voice note, customer file

## Scenario

You asked for a document: "Send me a photo of your receipt". The customer sends it. Your server receives a `message.inbound` of type `image` (or `document`), downloads the file and files it with the record.

**Yes, you can receive photos and documents** (1,000 received messages free a month, then 1 credit per 20). There is no window to respect to receive: it only exists to **reply**. Media types received: `image`, `audio`, `video`, `document`, `sticker`.

## Conversation

```text
You      : To validate, send me a photo of your receipt.
Customer : (sends a photo with the caption "payment receipt")
Webhook  : message.inbound  type=image  text="payment receipt"
           media_id="1234…"  media_mime="image/jpeg"
           media_url="https://wa-api.geskap.com/v1/media/9d3e…"
You      : Received, thank you Awa. We are checking and will get back to you.
```

## Code

What reaches your webhook: the handler verifies the signature then calls `onInbound`.

```js
// Node.js
// Express — receive the webhook, verify it, then react.
import express from "express";
import crypto from "node:crypto";

const app = express();
const SECRET = process.env.GESKAP_WEBHOOK_SECRET; // shown once when you register the webhook

// Keep the RAW bytes: the signature covers them, not a re-serialized JSON.
app.post("/webhooks/whatsapp", express.raw({ type: "application/json" }), (req, res) => {
  const expected = "sha256=" + crypto.createHmac("sha256", SECRET).update(req.body).digest("hex");
  const got = req.get("X-Camairetech-Signature") || "";
  if (got.length !== expected.length ||
      !crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected))) {
    return res.sendStatus(401);
  }
  res.sendStatus(200); // answer fast: one attempt, 8 s timeout, no retry
  const { event, data } = JSON.parse(req.body.toString("utf8"));
  if (event === "message.inbound") onInbound(data); // your code
});

app.listen(3000);
```

```php
// PHP
<?php
// Receive the webhook, verify it, then react.
$raw = file_get_contents("php://input"); // raw bytes, before json_decode
$expected = "sha256=" . hash_hmac("sha256", $raw, getenv("GESKAP_WEBHOOK_SECRET"));
$got = $_SERVER["HTTP_X_CAMAIRETECH_SIGNATURE"] ?? "";
if (!hash_equals($expected, $got)) {
    http_response_code(401);
    exit;
}
http_response_code(200);
$payload = json_decode($raw, true);
if ($payload["event"] === "message.inbound") {
    on_inbound($payload["data"]); // your code
}
```

```python
# Python
# Flask — receive the webhook, verify it, then react.
import hashlib, hmac, json, os
from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["GESKAP_WEBHOOK_SECRET"].encode()

@app.post("/webhooks/whatsapp")
def whatsapp_webhook():
    raw = request.get_data()  # raw bytes, before any JSON parsing
    expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, request.headers.get("X-Camairetech-Signature", "")):
        abort(401)
    payload = json.loads(raw)
    if payload["event"] == "message.inbound":
        on_inbound(payload["data"])  # your code
    return "", 200
```

In `onInbound`, download the file (the API key must be allowed to read messages):

```js
async function onInbound(data) {
  if (!["image", "document", "audio", "video", "sticker"].includes(data.type)) return;
  // data.message_id is the storage id; data.wa_message_id (wamid.…) works too
  const res = await fetch(`https://wa-api.geskap.com/v1/media/${data.message_id}`, {
    headers: { Authorization: `Bearer ${process.env.GESKAP_API_KEY}` },
    redirect: "follow",                       // 302 to a signed URL valid for 1 h
  });
  if (res.status === 404) return markMissing(data);  // nothing hosted: see the pitfall
  const bytes = Buffer.from(await res.arrayBuffer());
  await storage.save(`${data.from}/${data.message_id}`, bytes, data.media_mime); // on your side
}
```

From the command line: `curl -L -H "Authorization: Bearer $GESKAP_API_KEY" https://wa-api.geskap.com/v1/media/<id> -o file`. The caption the customer wrote under the photo is in `text`. Acknowledge with [a free-text reply](https://console.geskap.com/docs/repondre-texte-libre?lang=en).

## Exact limits

| Item | Limit |
|---|---|
| Types received | `image`, `audio`, `video`, `document`, `sticker` |
| Download | `GET /v1/media/{id}`: internal `id` (`message_id`) or `wamid.…` |
| Signed URL | `302` redirect, valid 1 h: download right away |
| Nothing hosted | `404` "Aucun média hébergé pour ce message." |
| Cost | receiving: 1,000 free messages a month, then 1 credit per 20 (default) |

> **Pitfall:** download and **store on your side** without waiting. The signed URL expires after 1 h, and the file is not hosted forever: `media_url` is `null` (and `GET /v1/media/…` returns `404`) when no file was kept (storage not enabled, or the account's storage quota reached). In that case only `media_id` and the metadata remain. See [Archive messages and media](https://console.geskap.com/docs/archiver-messages-medias?lang=en).

> **Pitfall:** do not trust a file because it comes from WhatsApp: check the type (`media_mime`) and size before opening it, and never execute it. A received ID document is sensitive data: store it encrypted, with a retention period.

_Proof — verified in the API source: public_api.py, webhooks.py._

---

# Recevoir une photo ou un document du client et le télécharger

_Oui — une photo, un PDF, un audio ou une vidéo arrive sur votre webhook (type image, document, audio, video) et se télécharge par GET /v1/media/{id} (redirection vers une URL valable 1 h) ; réception : 1 000 messages gratuits par mois, puis 1 crédit pour 20._

Mots-clés: recevoir photo, recevoir document, recevoir PDF, pièce jointe, pièce d'identité, justificatif, reçu de paiement, capture d'écran, image reçue, télécharger média, media_id, media_url, audio, vidéo, vocal, fichier client

## Scénario

Vous avez demandé une pièce : « Envoyez-moi la photo de votre reçu ». Le client l'envoie. Votre serveur reçoit un message `message.inbound` de type `image` (ou `document`), télécharge le fichier et le range avec le dossier.

**Oui, vous pouvez recevoir photos et documents** (1 000 messages reçus gratuits par mois, puis 1 crédit pour 20). Il n'y a pas de fenêtre à respecter pour recevoir : elle n'existe que pour **répondre**. Types de média reçus : `image`, `audio`, `video`, `document`, `sticker`.

## Conversation

```text
Vous    : Pour valider, envoyez-moi la photo de votre reçu.
Client  : (envoie une photo avec la légende « reçu de paiement »)
Webhook : message.inbound  type=image  text="reçu de paiement"
          media_id="1234…"  media_mime="image/jpeg"
          media_url="https://wa-api.geskap.com/v1/media/9d3e…"
Vous    : Bien reçu, merci Awa. Nous vérifions et revenons vers vous.
```

## Code

Ce qui arrive sur votre webhook : le gestionnaire vérifie la signature puis appelle `onInbound`.

```js
// Node.js
// Express — receive the webhook, verify it, then react.
import express from "express";
import crypto from "node:crypto";

const app = express();
const SECRET = process.env.GESKAP_WEBHOOK_SECRET; // shown once when you register the webhook

// Keep the RAW bytes: the signature covers them, not a re-serialized JSON.
app.post("/webhooks/whatsapp", express.raw({ type: "application/json" }), (req, res) => {
  const expected = "sha256=" + crypto.createHmac("sha256", SECRET).update(req.body).digest("hex");
  const got = req.get("X-Camairetech-Signature") || "";
  if (got.length !== expected.length ||
      !crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected))) {
    return res.sendStatus(401);
  }
  res.sendStatus(200); // answer fast: one attempt, 8 s timeout, no retry
  const { event, data } = JSON.parse(req.body.toString("utf8"));
  if (event === "message.inbound") onInbound(data); // your code
});

app.listen(3000);
```

```php
// PHP
<?php
// Receive the webhook, verify it, then react.
$raw = file_get_contents("php://input"); // raw bytes, before json_decode
$expected = "sha256=" . hash_hmac("sha256", $raw, getenv("GESKAP_WEBHOOK_SECRET"));
$got = $_SERVER["HTTP_X_CAMAIRETECH_SIGNATURE"] ?? "";
if (!hash_equals($expected, $got)) {
    http_response_code(401);
    exit;
}
http_response_code(200);
$payload = json_decode($raw, true);
if ($payload["event"] === "message.inbound") {
    on_inbound($payload["data"]); // your code
}
```

```python
# Python
# Flask — receive the webhook, verify it, then react.
import hashlib, hmac, json, os
from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["GESKAP_WEBHOOK_SECRET"].encode()

@app.post("/webhooks/whatsapp")
def whatsapp_webhook():
    raw = request.get_data()  # raw bytes, before any JSON parsing
    expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, request.headers.get("X-Camairetech-Signature", "")):
        abort(401)
    payload = json.loads(raw)
    if payload["event"] == "message.inbound":
        on_inbound(payload["data"])  # your code
    return "", 200
```

Dans `onInbound`, téléchargez le fichier (la clé API doit avoir le droit de lecture des messages) :

```js
async function onInbound(data) {
  if (!["image", "document", "audio", "video", "sticker"].includes(data.type)) return;
  // data.message_id est l'identifiant de stockage ; data.wa_message_id (wamid.…) fonctionne aussi
  const res = await fetch(`https://wa-api.geskap.com/v1/media/${data.message_id}`, {
    headers: { Authorization: `Bearer ${process.env.GESKAP_API_KEY}` },
    redirect: "follow",                       // 302 vers une URL signée valable 1 h
  });
  if (res.status === 404) return markMissing(data);  // rien d'hébergé : voir le piège
  const bytes = Buffer.from(await res.arrayBuffer());
  await storage.save(`${data.from}/${data.message_id}`, bytes, data.media_mime); // chez vous
}
```

En ligne de commande : `curl -L -H "Authorization: Bearer $GESKAP_API_KEY" https://wa-api.geskap.com/v1/media/<id> -o fichier`. La légende que le client a écrite sous la photo est dans `text`. Accusez réception avec [une réponse en texte libre](https://console.geskap.com/docs/repondre-texte-libre).

## Limites exactes

| Élément | Limite |
|---|---|
| Types reçus | `image`, `audio`, `video`, `document`, `sticker` |
| Téléchargement | `GET /v1/media/{id}` : `id` interne (`message_id`) ou `wamid.…` |
| URL signée | redirection `302`, valable 1 h : téléchargez tout de suite |
| Rien d'hébergé | `404` « Aucun média hébergé pour ce message. » |
| Coût | recevoir : 1 000 messages gratuits par mois, puis 1 crédit pour 20 (par défaut) |

> **Piège :** téléchargez et **rangez chez vous** sans attendre. L'URL signée expire au bout d'1 h, et le fichier n'est pas hébergé indéfiniment : `media_url` vaut `null` (et `GET /v1/media/…` répond `404`) quand aucun fichier n'a été conservé (stockage non activé, ou quota de stockage du compte atteint). Dans ce cas il ne reste que `media_id` et les métadonnées. Voir [Archiver messages et médias](https://console.geskap.com/docs/archiver-messages-medias).

> **Piège :** ne faites pas confiance au fichier parce qu'il vient de WhatsApp : contrôlez le type (`media_mime`) et la taille avant de l'ouvrir, et ne l'exécutez jamais. Une pièce d'identité reçue est une donnée sensible : stockez-la chiffrée, avec une durée de conservation.

_Preuve — vérifié dans le code de l'API : public_api.py, webhooks.py._

Support: WhatsApp +237 6 56 09 88 31 · All recipes: https://wa-api.geskap.com/llms.txt
