← Blog

·

How to Save and Export WhatsApp Business API Chat History

Updated on November 4, 2026

The official WhatsApp Business API has no endpoint for retrieving past conversations: your chat history is whatever your system saves from webhooks and send responses. Meta keeps messages for at most 30 days, only to run the service (for example, retransmissions), and doesn’t hand that content back to you. If you want history, you need to store every inbound message, every outbound message and every status in your own database, and download media before its ID expires.

This guide covers what to capture, a ready-made database schema, how to handle media, retention and privacy law, and how to export a single customer’s conversation.

Why Meta doesn’t keep your history for you

In the WhatsApp Business app, conversations live on the phone. With the Cloud API there’s no phone: Meta delivers each event to your webhook and that’s it. The API’s messages reference covers sending and marking as read, but no method to list or search past messages.

The Cloud API data privacy and security page says messages have a maximum retention period of 30 days to provide the service’s base features, such as retransmissions, and that Meta acts as a data processor on behalf of the business. Cloud API customers remain responsible for their own data protection obligations.

In practice:

  • Inbound message: arrives once on the messages webhook. If your endpoint fails, Meta retries for up to 7 days (webhooks overview). After that, it’s gone.
  • Outbound message: the content lives in the request your system made. The response only returns the wamid. If you didn’t save the body before sending, there’s nowhere to get it.
  • Media: the webhook carries a media ID valid for 7 days, and the download URL lasts 5 minutes (media docs).

What to capture

Four streams feed your history:

SourceWebhook field or callWhat to store
Inbound messagesmessages → value.messages[]Sender, type, content, wamid, timestamp, context (which message it replies to)
Outbound messages via APIYour POST /messages request + responseRecipient, body sent, template and variables, wamid from the response
Statusesmessages → value.statuses[]sent, delivered, read, failed, with timestamp and error
Messages sent from the app (coexistence)smb_message_echoesSame as outbound, flagged with source “app”

If the number uses coexistence (WhatsApp Business app and API at the same time), Meta can also sync up to six months of prior one-to-one chats through the history webhook, if the business allows it. Details in coexistence: what syncs. The format of every inbound message type is in our WhatsApp API webhooks guide.

Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →

Suggested database schema

A PostgreSQL model with three core tables (contacts, messages and statuses) plus one for media:

CREATE TABLE contacts (
  id              BIGSERIAL PRIMARY KEY,
  phone_number_id TEXT NOT NULL,        -- your API number
  wa_id           TEXT,                 -- customer phone (may be missing with usernames)
  bsuid           TEXT,                 -- business-scoped user ID
  profile_name    TEXT,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
  UNIQUE (phone_number_id, wa_id),
  UNIQUE (phone_number_id, bsuid)
);

CREATE TABLE messages (
  id            BIGSERIAL PRIMARY KEY,
  wamid         TEXT NOT NULL UNIQUE,   -- idempotency key
  contact_id    BIGINT NOT NULL REFERENCES contacts(id),
  direction     TEXT NOT NULL CHECK (direction IN ('in','out')),
  source        TEXT NOT NULL DEFAULT 'api', -- api, app (echo), history
  type          TEXT NOT NULL,          -- text, image, template, interactive...
  body          TEXT,                   -- text or caption, for search
  payload       JSONB NOT NULL,         -- full original object
  reply_to      TEXT,                   -- context.id (quoted wamid)
  sent_at       TIMESTAMPTZ NOT NULL,
  current_status TEXT                   -- latest status (outbound only)
);
CREATE INDEX ON messages (contact_id, sent_at);

CREATE TABLE message_statuses (
  id            BIGSERIAL PRIMARY KEY,
  wamid         TEXT NOT NULL,
  status        TEXT NOT NULL,          -- sent, delivered, read, failed
  occurred_at   TIMESTAMPTZ NOT NULL,
  error_code    INT,
  error_title   TEXT,
  UNIQUE (wamid, status)
);

CREATE TABLE media (
  id            BIGSERIAL PRIMARY KEY,
  wamid         TEXT NOT NULL REFERENCES messages(wamid),
  media_id      TEXT NOT NULL,
  mime_type     TEXT,
  sha256        TEXT,
  storage_key   TEXT,                   -- key in your storage
  downloaded_at TIMESTAMPTZ
);

Why this shape:

  • A unique wamid makes writes idempotent. Meta retries and duplicate events become ON CONFLICT DO NOTHING. Queues and idempotency are covered in depth in integration architecture.
  • payload as JSONB keeps the original object. New message types won’t break the schema, and you can reprocess later.
  • A separate body lets you search and export readable text without opening the JSON.
  • wa_id and bsuid: with WhatsApp usernames, the phone number may not come in the webhook, and the customer is identified by the BSUID instead. Store both. See usernames and BSUID.
  • Statuses in their own table: with retries and queues, one status may be processed after a newer one. Storing each with Meta’s timestamp stops a late-processed delivered from overwriting a read.

Writing from the webhook

The Node.js handler below, using pg, saves inbound messages and statuses. It assumes a webhook that’s already been validated (X-Hub-Signature-256 signature) and a contact that’s already resolved:

async function saveInbound(db, value) {
  const phoneNumberId = value.metadata.phone_number_id;

  for (const msg of value.messages ?? []) {
    const contactId = await resolveContact(db, phoneNumberId, value.contacts?.[0], msg);
    const body = msg.text?.body ?? msg[msg.type]?.caption ?? null;
    await db.query(
      `INSERT INTO messages (wamid, contact_id, direction, type, body, payload, reply_to, sent_at)
       VALUES ($1, $2, 'in', $3, $4, $5, $6, to_timestamp($7))
       ON CONFLICT (wamid) DO NOTHING`,
      [msg.id, contactId, msg.type, body, msg, msg.context?.id ?? null, Number(msg.timestamp)]
    );
    const media = msg[msg.type]?.id && msg[msg.type];
    if (media) await downloadQueue.add({ wamid: msg.id, mediaId: media.id, mime: media.mime_type });
  }

  for (const st of value.statuses ?? []) {
    await db.query(
      `INSERT INTO message_statuses (wamid, status, occurred_at, error_code, error_title)
       VALUES ($1, $2, to_timestamp($3), $4, $5)
       ON CONFLICT (wamid, status) DO NOTHING`,
      [st.id, st.status, Number(st.timestamp), st.errors?.[0]?.code ?? null, st.errors?.[0]?.title ?? null]
    );
  }
}

For outbound messages, write the row before calling the API (with a temporary ID) and update it with the wamid from the response. That way, if the call fails, you still have a record of what you tried to send. For templates, store the name, language and variables: Meta assembles the final text, so a readable history has to rebuild it from the approved template.

Media: download it before it expires

Media is the most fragile part of your history. A media ID received by webhook expires in 7 days and the download URL in 5 minutes. The flow is: webhook → queue → GET /{media-id} → download with your token → your storage (S3, GCS, disk) → save the key in the media table. Never store Meta’s URL as if it were permanent. Step-by-step code is in how to download media from the webhook.

Receipts, documents and photos often hold personal data. Use a private bucket and signed links for whoever needs to see them.

Retention and privacy law (Brazil’s LGPD)

Keeping everything forever isn’t good practice. Brazil’s General Data Protection Law, the LGPD (Law 13,709/2018), is similar in spirit to Europe’s GDPR, and several of its principles affect chat history:

  • Purpose and necessity (art. 6): keep what serves a defined purpose, such as customer support, proof of a contract or auditing.
  • End of processing (arts. 15 and 16): once the purpose ends, data should be deleted, with exceptions in the law, such as compliance with a legal obligation.
  • Data subject rights (art. 18): the customer can request access, correction, deletion and portability. Your system has to find and export everything for a contact.
  • Security (art. 46): technical measures to protect data, such as encryption and access control.

A common technical policy is to set retention periods per data type (text, media, statuses) and run a job that deletes or anonymizes anything past its period. Which periods apply depends on your industry, your country and your legal obligations: that’s a call for your company’s legal team. This article explains the law but is not legal advice. For consent and opt-out, see LGPD and WhatsApp.

-- sample retention job (period set by your legal team)
DELETE FROM media WHERE downloaded_at < now() - interval '180 days';

Remember to delete the file in storage too, not just the row.

How to export the history

Three formats cover most requests:

  1. JSON per contact, for portability or a data subject request:
SELECT json_agg(json_build_object(
  'at', m.sent_at, 'direction', m.direction,
  'type', m.type, 'body', m.body, 'status', m.current_status
) ORDER BY m.sent_at)
FROM messages m JOIN contacts c ON c.id = m.contact_id
WHERE c.wa_id = '5511999999999';
  1. CSV for analysis or audits, with COPY (SELECT ...) TO STDOUT WITH CSV HEADER.
  2. Readable text, chat-style (“[11/04/2026 10:02] Customer: …”), to attach to a ticket or a legal case.

Include statuses when exporting outbound messages: “delivered at” and “read at” are often exactly what the request needs to prove.

How to do this with Vectalk

Vectalk is a proxy for the official WhatsApp Business API and forwards Meta’s webhooks with the same payload, so the schema and handler above work unchanged. On top of that, the Vectalk API has a List Messages endpoint, GET https://apis.vectalk.com.br/api/messages, with filters for date range (from, to), status, direction (inbound or outbound) and messageId, paginated. It returns metadata such as waMessageId, recipient, type, status and date, which helps you reconcile your database and spot gaps. For full content and media, keep saving from the webhook. If you’d like a ready-made database, see webhooks with Supabase. Create your account to get started.

Frequently asked questions

Can I retrieve old conversations through the WhatsApp API?

No. The Cloud API has no endpoint for listing past messages. The exception is coexistence: when you connect a WhatsApp Business app number, the business can allow up to six months of one-to-one chats to sync through the history webhook.

How long does Meta keep messages?

At most 30 days, according to the Cloud API privacy page, and only for service features such as retransmissions. That content isn’t available for you to query.

I lost webhooks because my server was down. Now what?

Meta retries for up to 7 days. If your server comes back within that window, the events arrive. After that, inbound message content can’t be recovered through the API.

Do I have to keep chat history for compliance?

Laws like the LGPD don’t require keeping everything; they require a purpose, necessity and deletion when processing ends, with legal exceptions. Your legal team sets the right periods for your case.

A customer asked for a copy of their chats. How do I deliver it?

Export per contact (JSON or readable text) from your database, including media and statuses, and send it through a secure channel.


Official sources checked on November 4, 2026: Cloud API data privacy and security, Webhooks overview, Media, Law 13,709/2018 (LGPD), Vectalk List Messages API, Vectalk webhooks.

Put your business on the official WhatsApp

Create your account, connect your number to the official API (you can keep the app with coexistence) and start serving customers and sending messages.