# Archive received messages and download photos and documents (backup, proof, retention)

_Received messages are stored on the API side for your plan's duration, then purged; to keep them, copy every message.inbound and download the media right away. Messages you send through the API are not in GET /v1/messages/inbound._

Keywords: archive, archiving, message backup, history, keep messages, retention, how long are messages kept, purge, download a photo, download a document, media, media_url, GET /v1/media, GET /v1/messages/inbound, since, backup, proof, storage, storage plan

## Scenario

A customer sends you a photo of a purchase order. You want to keep the message and the photo for good: in your database, for a dispute or an audit. Or a customer disputes a message received three months ago. **The API keeps a copy, but not forever.** To keep beyond that, you must copy.

## What the API keeps

Every received message is stored automatically, **even if you have no webhook**. You read it back with `GET /v1/messages/inbound`. Storage lasts according to your **storage plan**; past that, a daily purge permanently deletes the messages (and their hosted media).

```bash
# curl
curl -X GET "https://wa-api.geskap.com/v1/storage" \
  -H "Authorization: Bearer $GESKAP_API_KEY"
```

```js
// Node.js
const res = await fetch("https://wa-api.geskap.com/v1/storage", {
  method: "GET",
  headers: {
    Authorization: `Bearer ${process.env.GESKAP_API_KEY}`,
  },
});
console.log(res.status, await res.json());
```

```php
// PHP
$ch = curl_init("https://wa-api.geskap.com/v1/storage");
curl_setopt_array($ch, [
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("GESKAP_API_KEY"),
  ],
]);
$res = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), " ", $res;
```

```python
# Python
import os, requests

res = requests.request(
    "GET",
    "https://wa-api.geskap.com/v1/storage",
    headers={"Authorization": f"Bearer {os.environ['GESKAP_API_KEY']}"},
    timeout=15,
)
print(res.status_code, res.json())
```

The response gives `retention_days`, the number of messages, the space used and the oldest message kept. The plans and their durations are settings: read them in `GET /v1/public/pricing` (storage plans section) rather than hard-coding them.

## The safe path: copy as you go

```text
message.inbound on your webhook
   │
   ├─► write the message to your database (key: wa_message_id)
   └─► if media_url is not null: download the file now into your storage
```

Fill gaps (your server was down) with `GET /v1/messages/inbound?since=<last received_at>`: with `since`, messages come back **oldest first**, strictly after that cursor. Advance the cursor to the `received_at` of the last message handled. The `limit` parameter goes from 1 to 200 (50 by default).

```js
// Node.js
// Copy a received message, then its media, into YOUR storage.
import fs from "node:fs/promises";
const API = "https://wa-api.geskap.com";
const auth = { Authorization: `Bearer ${process.env.GESKAP_API_KEY}` };

export async function archive(msg) {            // msg = webhook data, or one item of GET /v1/messages/inbound
  await saveMessage(msg);                       // your DB, unique on msg.wa_message_id
  if (!msg.media_url) return;
  // The API answers 302 to a signed address valid 1 h: do not send your key to it.
  const hop = await fetch(msg.media_url, { headers: auth, redirect: "manual" });
  const signed = hop.headers.get("location");
  if (!signed) return;                          // nothing hosted for this message
  const file = await fetch(signed);
  await fs.writeFile(`archive/${msg.wa_message_id}`, Buffer.from(await file.arrayBuffer()));
}

// Catch-up after an outage: oldest first, strictly after the cursor.
export async function catchUp(cursor) {
  for (;;) {
    const res = await fetch(`${API}/v1/messages/inbound?since=${encodeURIComponent(cursor)}&limit=200`, { headers: auth });
    const { messages } = await res.json();
    if (!messages.length) return cursor;
    for (const m of messages) await archive(m);
    cursor = messages[messages.length - 1].received_at;
  }
}
```

```php
// PHP
<?php
// Copy a received message, then its media, into YOUR storage.
const API = "https://wa-api.geskap.com";

function api_get(string $url, bool $follow = false) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => $follow,
        CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("GESKAP_API_KEY")],
    ]);
    $body = curl_exec($ch);
    $redirect = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
    return [$body, $redirect];
}

function archive(array $msg): void {            // $msg = webhook data, or one item of GET /v1/messages/inbound
    save_message($msg);                         // your DB, unique on wa_message_id
    if (empty($msg["media_url"])) return;
    // The API answers 302 to a signed address valid 1 h: do not send your key to it.
    [, $signed] = api_get($msg["media_url"]);
    if (!$signed) return;                       // nothing hosted for this message
    file_put_contents("archive/" . $msg["wa_message_id"], file_get_contents($signed));
}

// Catch-up after an outage: oldest first, strictly after the cursor.
function catch_up(string $cursor): string {
    while (true) {
        [$body] = api_get(API . "/v1/messages/inbound?since=" . urlencode($cursor) . "&limit=200");
        $messages = json_decode($body, true)["messages"];
        if (!$messages) return $cursor;
        foreach ($messages as $m) archive($m);
        $cursor = end($messages)["received_at"];
    }
}
```

```python
# Python
# Copy a received message, then its media, into YOUR storage.
import os, requests

API = "https://wa-api.geskap.com"
AUTH = {"Authorization": f"Bearer {os.environ['GESKAP_API_KEY']}"}

def archive(msg):            # msg = webhook data, or one item of GET /v1/messages/inbound
    save_message(msg)        # your DB, unique on msg["wa_message_id"]
    if not msg.get("media_url"):
        return
    # The API answers 302 to a signed address valid 1 h: do not send your key to it.
    hop = requests.get(msg["media_url"], headers=AUTH, allow_redirects=False, timeout=15)
    signed = hop.headers.get("Location")
    if not signed:
        return               # nothing hosted for this message
    with open(f"archive/{msg['wa_message_id']}", "wb") as f:
        f.write(requests.get(signed, timeout=60).content)

def catch_up(cursor):
    """After an outage: oldest first, strictly after the cursor."""
    while True:
        r = requests.get(f"{API}/v1/messages/inbound", headers=AUTH,
                         params={"since": cursor, "limit": 200}, timeout=15)
        messages = r.json()["messages"]
        if not messages:
            return cursor
        for m in messages:
            archive(m)
        cursor = messages[-1]["received_at"]
```

```bash
# curl
# 1) Read messages after a cursor (oldest first).
curl "https://wa-api.geskap.com/v1/messages/inbound?since=2026-10-30T09:00:00%2B00:00&limit=200" \
  -H "Authorization: Bearer $GESKAP_API_KEY"

# 2) Get the signed address of a media (302, do not follow with your key).
SIGNED=$(curl -s -o /dev/null -w '%{redirect_url}' \
  "https://wa-api.geskap.com/v1/media/9d3e0000-0000-0000-0000-000000000000" \
  -H "Authorization: Bearer $GESKAP_API_KEY")

# 3) Download it right away (valid 1 h).
curl -o photo.jpg "$SIGNED"
```

## Media

- `media_url` (in the webhook and in `GET /v1/messages/inbound`) is `https://wa-api.geskap.com/v1/media/<id>`. Call it with your key: the response is a `302` redirect to a signed address **valid for 1 hour**. Download right away, do not store the signed address.
- `GET /v1/media/{id}` accepts the stored identifier (`message_id`) or the `wa_message_id` (`wamid.…`).
- `media_url` is `null` when the API did not keep the file: then there is only `media_id` and `media_mime`, and the file cannot be retrieved through the API. This happens for an echo-type media (sent from the phone), if hosting is unavailable, or if your storage plan is full with no overage possible.
- Hosted media is deleted with its message at the end of retention.

## And the messages I send?

**They are not in `GET /v1/messages/inbound`.** That route only lists received messages (`direction: "in"`) and those sent from the phone under Coexistence (`"echo"`). For your API sends, the API only keeps the send trace: `GET /v1/messages/{id}` (status) and `GET /v1/logs?category=sends` (template, masked recipient, status, credits). **Not the text sent.** So keep your own send journal: record, at call time, the text or template, the variables, and the returned `id`.

> **Pitfall:** without a copy on your side, anything past your plan's retention is lost for good. The purge is permanent.

> **Pitfall:** the media's signed address expires after 1 hour. An address kept in your database will not work tomorrow: download the file, or call `GET /v1/media/{id}` again to get a new one as long as the message exists.

> **Pitfall:** to avoid handling the same message twice (catch-up after a webhook already received), de-duplicate on `wa_message_id`.

For the webhook, see [Verify a webhook signature](https://console.geskap.com/docs/webhook-verifier-signature?lang=en). To receive a photo in a conversation, see [Receive a photo or a document](https://console.geskap.com/docs/recevoir-photo-document?lang=en).

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

---

# Archiver les messages reçus et télécharger les photos et documents (sauvegarde, preuve, rétention)

_Les messages reçus sont stockés côté API pour la durée de votre plan puis purgés ; pour les garder, copiez chaque message.inbound et téléchargez le média tout de suite. Les messages que vous envoyez par l'API ne sont pas dans GET /v1/messages/inbound._

Mots-clés: archiver, archivage, sauvegarde des messages, historique, conserver les messages, rétention, durée de conservation, purge, télécharger une photo, télécharger un document, média, media_url, GET /v1/media, GET /v1/messages/inbound, since, backup, preuve, stockage, plan de stockage

## Scénario

Un client vous envoie la photo d'un bon de commande. Vous voulez garder le message et la photo pour de bon : dans votre base, pour un litige ou un audit. Ou un client conteste un message reçu il y a trois mois. **L'API garde une copie, mais pas indéfiniment.** Pour conserver au-delà, vous devez copier.

## Ce que l'API conserve

Chaque message reçu est stocké automatiquement, **même si vous n'avez pas de webhook**. Vous le relisez avec `GET /v1/messages/inbound`. Le stockage dure selon votre **plan de stockage** ; passé ce délai, une purge quotidienne supprime définitivement les messages (et leurs médias hébergés).

```bash
# curl
curl -X GET "https://wa-api.geskap.com/v1/storage" \
  -H "Authorization: Bearer $GESKAP_API_KEY"
```

```js
// Node.js
const res = await fetch("https://wa-api.geskap.com/v1/storage", {
  method: "GET",
  headers: {
    Authorization: `Bearer ${process.env.GESKAP_API_KEY}`,
  },
});
console.log(res.status, await res.json());
```

```php
// PHP
$ch = curl_init("https://wa-api.geskap.com/v1/storage");
curl_setopt_array($ch, [
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("GESKAP_API_KEY"),
  ],
]);
$res = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), " ", $res;
```

```python
# Python
import os, requests

res = requests.request(
    "GET",
    "https://wa-api.geskap.com/v1/storage",
    headers={"Authorization": f"Bearer {os.environ['GESKAP_API_KEY']}"},
    timeout=15,
)
print(res.status_code, res.json())
```

La réponse donne `retention_days`, le nombre de messages, la place utilisée et le plus ancien message conservé. Les plans et leurs durées sont des réglages : lisez-les dans `GET /v1/public/pricing` (rubrique plans de stockage) plutôt que de les écrire en dur.

## Le chemin sûr : copier au fil de l'eau

```text
message.inbound sur votre webhook
   │
   ├─► écrire le message dans votre base (clé : wa_message_id)
   └─► si media_url n'est pas null : télécharger le fichier maintenant dans votre stockage
```

Rattrapez les trous (panne de votre serveur) avec `GET /v1/messages/inbound?since=<dernier received_at>` : avec `since`, les messages reviennent **du plus ancien au plus récent**, strictement après ce curseur. Avancez le curseur au `received_at` du dernier message traité. Le paramètre `limit` va de 1 à 200 (50 par défaut).

```js
// Node.js
// Copy a received message, then its media, into YOUR storage.
import fs from "node:fs/promises";
const API = "https://wa-api.geskap.com";
const auth = { Authorization: `Bearer ${process.env.GESKAP_API_KEY}` };

export async function archive(msg) {            // msg = webhook data, or one item of GET /v1/messages/inbound
  await saveMessage(msg);                       // your DB, unique on msg.wa_message_id
  if (!msg.media_url) return;
  // The API answers 302 to a signed address valid 1 h: do not send your key to it.
  const hop = await fetch(msg.media_url, { headers: auth, redirect: "manual" });
  const signed = hop.headers.get("location");
  if (!signed) return;                          // nothing hosted for this message
  const file = await fetch(signed);
  await fs.writeFile(`archive/${msg.wa_message_id}`, Buffer.from(await file.arrayBuffer()));
}

// Catch-up after an outage: oldest first, strictly after the cursor.
export async function catchUp(cursor) {
  for (;;) {
    const res = await fetch(`${API}/v1/messages/inbound?since=${encodeURIComponent(cursor)}&limit=200`, { headers: auth });
    const { messages } = await res.json();
    if (!messages.length) return cursor;
    for (const m of messages) await archive(m);
    cursor = messages[messages.length - 1].received_at;
  }
}
```

```php
// PHP
<?php
// Copy a received message, then its media, into YOUR storage.
const API = "https://wa-api.geskap.com";

function api_get(string $url, bool $follow = false) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => $follow,
        CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("GESKAP_API_KEY")],
    ]);
    $body = curl_exec($ch);
    $redirect = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
    return [$body, $redirect];
}

function archive(array $msg): void {            // $msg = webhook data, or one item of GET /v1/messages/inbound
    save_message($msg);                         // your DB, unique on wa_message_id
    if (empty($msg["media_url"])) return;
    // The API answers 302 to a signed address valid 1 h: do not send your key to it.
    [, $signed] = api_get($msg["media_url"]);
    if (!$signed) return;                       // nothing hosted for this message
    file_put_contents("archive/" . $msg["wa_message_id"], file_get_contents($signed));
}

// Catch-up after an outage: oldest first, strictly after the cursor.
function catch_up(string $cursor): string {
    while (true) {
        [$body] = api_get(API . "/v1/messages/inbound?since=" . urlencode($cursor) . "&limit=200");
        $messages = json_decode($body, true)["messages"];
        if (!$messages) return $cursor;
        foreach ($messages as $m) archive($m);
        $cursor = end($messages)["received_at"];
    }
}
```

```python
# Python
# Copy a received message, then its media, into YOUR storage.
import os, requests

API = "https://wa-api.geskap.com"
AUTH = {"Authorization": f"Bearer {os.environ['GESKAP_API_KEY']}"}

def archive(msg):            # msg = webhook data, or one item of GET /v1/messages/inbound
    save_message(msg)        # your DB, unique on msg["wa_message_id"]
    if not msg.get("media_url"):
        return
    # The API answers 302 to a signed address valid 1 h: do not send your key to it.
    hop = requests.get(msg["media_url"], headers=AUTH, allow_redirects=False, timeout=15)
    signed = hop.headers.get("Location")
    if not signed:
        return               # nothing hosted for this message
    with open(f"archive/{msg['wa_message_id']}", "wb") as f:
        f.write(requests.get(signed, timeout=60).content)

def catch_up(cursor):
    """After an outage: oldest first, strictly after the cursor."""
    while True:
        r = requests.get(f"{API}/v1/messages/inbound", headers=AUTH,
                         params={"since": cursor, "limit": 200}, timeout=15)
        messages = r.json()["messages"]
        if not messages:
            return cursor
        for m in messages:
            archive(m)
        cursor = messages[-1]["received_at"]
```

```bash
# curl
# 1) Read messages after a cursor (oldest first).
curl "https://wa-api.geskap.com/v1/messages/inbound?since=2026-10-30T09:00:00%2B00:00&limit=200" \
  -H "Authorization: Bearer $GESKAP_API_KEY"

# 2) Get the signed address of a media (302, do not follow with your key).
SIGNED=$(curl -s -o /dev/null -w '%{redirect_url}' \
  "https://wa-api.geskap.com/v1/media/9d3e0000-0000-0000-0000-000000000000" \
  -H "Authorization: Bearer $GESKAP_API_KEY")

# 3) Download it right away (valid 1 h).
curl -o photo.jpg "$SIGNED"
```

## Les médias

- `media_url` (dans le webhook et dans `GET /v1/messages/inbound`) vaut `https://wa-api.geskap.com/v1/media/<id>`. Appelez-la avec votre clé : la réponse est une redirection `302` vers une adresse signée **valable 1 heure**. Téléchargez tout de suite, ne stockez pas l'adresse signée.
- `GET /v1/media/{id}` accepte l'identifiant stocké (`message_id`) ou le `wa_message_id` (`wamid.…`).
- `media_url` vaut `null` quand l'API n'a pas gardé le fichier : dans ce cas il n'y a que `media_id` et `media_mime`, et le fichier n'est pas récupérable par l'API. Cela arrive pour un média de type écho (envoyé depuis le téléphone), si l'hébergement est indisponible, ou si votre plan de stockage est plein sans dépassement possible.
- Les médias hébergés sont supprimés avec leur message à la fin de la rétention.

## Et les messages que j'envoie ?

**Ils ne sont pas dans `GET /v1/messages/inbound`.** Cette route ne liste que les messages reçus (`direction: "in"`) et ceux envoyés depuis le téléphone en Coexistence (`"echo"`). Pour vos envois par l'API, l'API ne garde que la trace d'envoi : `GET /v1/messages/{id}` (statut) et `GET /v1/logs?category=sends` (modèle, destinataire masqué, statut, crédits). **Pas le texte envoyé.** Tenez donc votre propre journal d'envoi : enregistrez, au moment de l'appel, le texte ou le template, les variables, et l'`id` renvoyé.

> **Piège :** sans copie de votre côté, tout ce qui dépasse la rétention de votre plan est perdu pour de bon. La purge est définitive.

> **Piège :** l'adresse signée du média expire au bout d'1 heure. Une adresse conservée dans votre base ne marchera plus demain : téléchargez le fichier, ou rappelez `GET /v1/media/{id}` pour en obtenir une nouvelle tant que le message existe.

> **Piège :** pour ne pas traiter deux fois le même message (rattrapage après un webhook déjà reçu), dédoublonnez sur `wa_message_id`.

Pour le webhook, voir [Vérifier la signature d'un webhook](https://console.geskap.com/docs/webhook-verifier-signature). Pour recevoir une photo dans une conversation, voir [Recevoir une photo ou un document](https://console.geskap.com/docs/recevoir-photo-document).

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

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