Download inbound WhatsApp media with the Hub

Download images, audio and documents from incoming WhatsApp messages: the Hub media route, the 5-minute URL Meta issues, expiry windows and size limits.

When a customer sends a photo, a voice note or a PDF, the webhook does not contain the file. It contains a media id, and your system has to fetch the bytes separately. Done well, this is a few lines of code; done badly, it loses files, because media ids and download URLs both expire. This tutorial downloads inbound media through the CRPRO Hub, shows what Meta does underneath and covers storage, size limits and failures.

What does the webhook contain for a media message?

Short answer: a content.media object with the media type, the media id, the MIME type, a sha256 hash and the caption, if there is one. There is no file and no download URL.

"content": { "available": true, "type": "image", "text": "Arrived like this", "media": { "type": "image", "id": "1234567890123456", "mime_type": "image/jpeg", "sha256": "EXAMPLE", "caption": "Arrived like this" }, "location": null, "interactive": null, "button": null, "order": null }

This is the shape in the Hub's message.received event, described in the webhooks reference. The id is what you need. The same field structure applies to images, audio, video, documents and stickers, with the type telling you which. Check content.type before reading content.media, because a text message has no media entry.

How is the file downloaded through the Hub?

Short answer: send a GET to /api/v1/channels/{channelId}/media/{mediaId} with your API key. The response body is the raw file, with its real Content-Type, and there is no JSON envelope.

The route needs the channels:read scope and a media id of 5 to 30 digits. Because the answer is binary, read it as bytes rather than parsing JSON. The Hub fetches the file from Meta on your behalf, so you do not handle Meta's access token or the temporary URL yourself.

curl https://crprohub.com/api/v1/channels/CHANNEL_UUID/media/1234567890123456 \ -H "Authorization: Bearer hub_pk_EXAMPLE_NOT_REAL" \ -o received-fileimport { writeFile } from 'node:fs/promises' const EXT = { 'image/jpeg': 'jpg', 'image/png': 'png', 'application/pdf': 'pdf', 'audio/ogg': 'ogg' } async function downloadMedia(channelId, mediaId) { const res = await fetch( `https://crprohub.com/api/v1/channels/${channelId}/media/${mediaId}`, { headers: { Authorization: `Bearer ${process.env.CRPRO_API_KEY}` } }, ) if (!res.ok) throw new Error(`media download failed: ${res.status}`) const type = (res.headers.get('content-type') ?? 'application/octet-stream').split(';')[0] const bytes = Buffer.from(await res.arrayBuffer()) const file = `./inbox/${mediaId}.${EXT[type] ?? 'bin'}` await writeFile(file, bytes) return { file, type, size: bytes.length } }

What happens on Meta's side?

Short answer: two requests. First a GET on the media id returns a JSON object with a temporary url, then a GET on that url with your token returns the bytes.

Meta's media reference describes the sequence: query the media id to get url, mime_type, sha256, file_size and id, then download from the url with the Authorization header. The URL expires 5 minutes after it is issued. If a download returns 404, ask for a new URL and retry; if that still fails, renew the access token. The Hub's route performs these steps, which is why it is the simpler option unless you use the Cloud API directly.

How long is the media available?

Short answer: do not count on more than 7 days from the webhook, and download immediately.

The two sources do not agree on a single figure, so use the stricter one. Meta's media reference states that media ids from webhooks expire after 7 days, while ids returned by the API expire after 30 days. The Hub's error guide mentions that media stays available at Meta for 30 days. For inbound files, a design that downloads as soon as the event is processed never meets either limit, and it is also the only design that keeps the customer's file if something breaks later.

  • Download inside the same job that records the message, or from a queue fed by it.
  • Store the bytes in your own storage and keep the media id only as a reference.
  • Record the sha256, size and MIME type with the file.
  • Retry failed downloads for a short time, then raise an alert while the id is still valid.

How can a downloaded file be validated?

Short answer: compare the size and, if you wish, the sha256 hash with the values from the webhook or the media lookup, and check the MIME type against what you expect.

import { createHash } from 'node:crypto' function matchesHash(bytes, expectedSha256) { const actual = createHash('sha256').update(bytes).digest('hex') return actual === String(expectedSha256).toLowerCase() }

Meta provides the sha256 so that you can verify the download. Compare a few real examples first to confirm the encoding of the value you receive before enforcing the check, because a mismatch in encoding would reject good files. Whatever you store, scan it before opening it: customers can send any file, and the sender is not trustworthy just because the message came through WhatsApp.

Where should the download happen in the receiving flow?

Short answer: after the webhook has been acknowledged, in a background job, with the message id as the deduplication key.

The webhook handler should verify the signature, store the event and answer with a 2xx well inside the Hub's 10-second wait. Fetching a file of several megabytes inside that request is a recipe for timeouts and duplicate deliveries. Instead, enqueue a job carrying the channel id, the media id and the message id. The job downloads the file, writes it to storage and marks the message as having its media attached. If the same event arrives twice, the job finds the existing record and exits. This also gives you one place to apply retries and one place to log failures, instead of burying download errors inside the webhook route.

// webhook handler: acknowledge fast, defer the heavy part const media = event.data.content?.media if (media?.id) { await queue.add('download-media', { channelId: event.channel_id, mediaId: media.id, messageId: event.data.message_id, }, { jobId: `media-${event.data.message_id}` }) // same id => no duplicate job } return res.sendStatus(200)

What size limits apply to inbound media?

Short answer: images 5 MB, audio and video 16 MB, documents 100 MB, and 500 KB for animated stickers or 100 KB for static ones.

Meta states that for inbound media the maximum supported size is 100 MB; a larger file produces a webhook with error code 131052 and no media to download. Plan storage and processing for the bigger end of the range if you accept documents. When Meta does not deliver a file, the Hub's error guide documents a 502 META_MEDIA_DOWNLOAD_FAILED response for its Meta-compatible media route, with the advice to try again in a few minutes; treat any 5xx on the download route the same way. Use backoff for that retry, covered in the retries tutorial of this series, and see the quickstart for the authenticated request.

How should downloaded media be stored?

Short answer: in private object storage, under a name that does not depend on the customer's filename, with the metadata kept in your database.

Customers can send anything, so never trust a filename or an extension, and never serve the stored object straight from a public path. Use a generated key such as the channel id plus the media id, keep the original MIME type and the hash in the database and serve files through a controlled route that checks who is allowed to see them. Apply the retention policy you need for the data: images and documents from customers are personal data in many jurisdictions, and keeping them forever is a choice with consequences.

  • Generate the storage key yourself.
  • Keep the MIME type, size and hash in the database.
  • Serve files through an authenticated route.
  • Scan uploads before they are opened by staff.
  • Define how long media is kept and delete it on schedule.

Frequently asked questions

Does the webhook include a download URL?

The Hub's normalized event gives the media id, MIME type, sha256 and caption. You download the file by calling the Hub's media route with that id. Meta's own webhooks can include a URL, but it expires quickly.

Which scope does the download need?

channels:read. Sending media requires messages:send, which is a different scope.

What if the download fails with 502?

The Hub's error guide documents META_MEDIA_DOWNLOAD_FAILED for the case where Meta did not deliver the file. Retry after a few minutes with backoff, and keep the attempt count bounded while the media id is still valid.

Can the same media id be downloaded twice?

Yes, while the id is valid. Still, store the file on the first download so you do not depend on the id staying available.

Fontes

Documentação oficial da Meta, conferida em 31 de outubro de 2026.