Skip to content

Blog · WhatsApp and channels

WhatsApp Cloud API with Node.js: send and receive messages step by step

Send your first message with the WhatsApp Cloud API from Node.js, verify Meta’s webhook and compare it with doing the same with the @meteor.ia/sdk SDK.

Equipo editorial de Meteor Published 5 min read

How do I send and receive WhatsApp messages with the Cloud API from Node.js?

With a POST to https://graph.facebook.com/v26.0/<PHONE_NUMBER_ID>/messages, with your token in the Authorization header and a JSON body with messaging_product “whatsapp”, the destination number and the text. You can only send free-form text within 24 hours of the person’s last message; outside that window, an approved template. To receive, you publish a webhook that answers Meta’s verification (hub.challenge) and checks the X-Hub-Signature-256 signature of each POST with the app secret. If you would rather not manage the Meta app or the webhook, Meteor IA’s @meteor.ia/sdk SDK sends in two calls and delivers messages to a signed webhook.

This tutorial does the same thing twice. First with Meta’s Cloud API directly, from Node.js: you send a text, see when a template is needed and receive messages on a webhook that verifies the signature. Then with Meteor IA’s @meteor.ia/sdk SDK. At the end, a table with what you have to run on each path.

Before you start, on Meta’s side

According to Meta’s getting started guide:

  1. In Meta’s app dashboard you create an app with the Connect with customers through WhatsApp use case and connect it to a WhatsApp Business account.
  2. In API Setup you generate a temporary token, pick the test number as the sender and add your phone as the recipient. The Send message button sends you the hello_world template.
  3. Reply from your phone. That message opens the 24-hour customer service window, and only inside it can you send free-form text.
  4. Save the test number’s Phone Number ID. The temporary token expires quickly: for development, create a system user in your business settings and generate its token with the business_management, whatsapp_business_messaging and whatsapp_business_management permissions.

1. Send a text from Node.js

The body is the one in Meta’s documentation for text messages. With Node’s fetch, in an ES module:

const VERSION = 'v26.0'; // the latest in Meta's version changelog
const { WHATSAPP_PHONE_NUMBER_ID, WHATSAPP_TOKEN } = process.env;

const respuesta = await fetch(
  `https://graph.facebook.com/${VERSION}/${WHATSAPP_PHONE_NUMBER_ID}/messages`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${WHATSAPP_TOKEN}`,
    },
    body: JSON.stringify({
      messaging_product: 'whatsapp',
      recipient_type: 'individual',
      to: '+573001234567',
      type: 'text',
      text: { body: 'Hello from the Cloud API' },
    }),
  },
);
if (!respuesta.ok) throw new Error(await respuesta.text());
const datos = await respuesta.json();
console.log(datos.messages[0].id); // wamid.…

The text allows up to 4,096 characters. If it includes a link and you want WhatsApp to try to show a preview, add preview_url: true inside text.

2. Messaging first: templates

Outside the 24-hour window, Meta only lets approved templates through. The request changes the type and the block, in the shape Meta’s template documentation shows:

body: JSON.stringify({
  messaging_product: 'whatsapp',
  recipient_type: 'individual',
  to: '+573001234567',
  type: 'template',
  template: {
    name: 'order_confirmation', // the exact name of your approved template
    language: { code: 'en_US' },     // the language code it was approved with
    components: [
      {
        type: 'body',
        parameters: [
          { type: 'text', text: 'Ana' },
          { type: 'text', text: 'PED-1042' },
        ],
      },
    ],
  },
}),

Parameters go in the order of the template’s variables.

3. Receive messages: the webhook

Meta talks to your server in two ways, according to its webhooks guide:

  • Verification GET. When you save the URL in the app settings, Meta calls with hub.mode=subscribe, a hub.challenge and the hub.verify_token you typed. If the token matches, you reply 200 with the hub.challenge.
  • POST with each event. It carries the X-Hub-Signature-256: sha256=… header, an HMAC-SHA256 of the body computed with your app’s app secret. If it does not match, you reply with a 400-range error.

With Express, and the raw body so the signature matches:

import crypto from 'node:crypto';
import express from 'express';

const app = express();
const { META_VERIFY_TOKEN, META_APP_SECRET } = process.env;

app.get('/webhook', (req, res) => {
  if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === META_VERIFY_TOKEN) {
    return res.status(200).send(req.query['hub.challenge']);
  }
  res.sendStatus(403);
});

app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
  const firma = Buffer.from(req.get('X-Hub-Signature-256') ?? '');
  const esperada = Buffer.from(
    'sha256=' + crypto.createHmac('sha256', META_APP_SECRET).update(req.body).digest('hex'),
  );
  if (firma.length !== esperada.length || !crypto.timingSafeEqual(firma, esperada)) {
    return res.sendStatus(401);
  }

  const datos = JSON.parse(req.body.toString('utf8'));
  for (const entrada of datos.entry ?? []) {
    for (const cambio of entrada.changes ?? []) {
      for (const mensaje of cambio.value.messages ?? []) {
        console.log(mensaje.from, mensaje.text?.body);
      }
    }
  }
  res.sendStatus(200);
});

app.listen(3000);

The message arrives in entry[].changes[].value.messages[], with from, type and, for text, text.body. Three things from Meta’s guide that people forget:

  1. The URL has to be public with a valid TLS certificate. Self-signed certificates do not work.
  2. Meta retries a failed POST for 7 days: deduplicate by the message id.
  3. There is no API to fetch old webhooks. Whatever you do not store when it arrives is lost.

4. The same with the Meteor IA SDK

With Meteor IA the line is connected once from the dashboard, and the Meta app, its token and Meta’s webhook verification stay out of your code. This is the first message with @meteor.ia/sdk, in TypeScript and in two calls:

  1. Connect WhatsApp to your Meteor IA workspace (dashboard → Canales → WhatsApp).
  2. Create a key in Ajustes → Desarrolladores → Crear API key, live environment, with the contacts:write and channels:send scopes. A met_test_ key does not send WhatsApp.
  3. From your phone, write “hola” to your WhatsApp business number, to open the 24-hour window.
  4. Install the SDK and run this:
npm install @meteor.ia/sdk
import Met from '@meteor.ia/sdk';

const met = new Met(process.env.MET_API_KEY!);

// Creates the contact or, if one already exists with that phone, returns it unchanged.
const contacto = await met.contacts.create({ phone: '+573001234567', name: 'Me' });
await met.contacts.sendMessage(contacto.id, 'Hello from the Meteor IA API 👋');

If the 24-hour window is closed, the API replies 409 with code === 'service_window_closed'. To message someone first, use an approved template with met.channels.whatsapp.sendTemplate: it is in the WhatsApp templates guide on the portal.

Receive messages on a signed webhook

You subscribe once, from a separate script, to the contact.message.received event. The key needs webhooks:manage, conversations:read, runs:execute and channels:send:

const met = new Met(process.env.MET_API_KEY!, {
  workspaceId: Number(process.env.MET_WORKSPACE_ID),
});

const sub = await met.webhooks.subscriptions.create({
  url: 'https://your-server.com/webhooks/met',
  enabled_events: ['contact.message.received'],
});

console.log(sub.secret); // whsec_… shown only once

And on your server, in a complete file, you verify the X-Met-Signature signature with constructEvent, over the raw body. You reply 200 before running the Met: Meteor retries if it does not see a 2xx, and replying after thinking duplicates your messages. This is the portal recipe’s code:

import express from 'express';
import Met from '@meteor.ia/sdk';

const app = express();
const met = new Met(process.env.MET_API_KEY!, {
  workspaceId: Number(process.env.MET_WORKSPACE_ID),
});

app.use('/webhooks/met', express.raw({ type: 'application/json' }));

app.post('/webhooks/met', async (req, res) => {
  let evento;
  try {
    evento = met.webhooks.constructEvent(
      req.body,
      req.headers['x-met-signature'] as string,
      process.env.MET_WEBHOOK_SECRET!,
    );
  } catch {
    return res.status(400).send('invalid signature');
  }

  res.sendStatus(200);

  if (evento.type !== 'contact.message.received') return;

  const { contact_id, content } = evento.data as { contact_id: number; content: string };
  const run = await met.runs.create({ input: content });
  if (run.output) await met.contacts.sendMessage(contact_id, run.output);
});

app.listen(3000);

Who answers. If the WhatsApp channel has a Met assigned and the contact’s autopilot is on, the Met answers on its own: you don’t need this webhook to reply, and if your code answers too, the contact gets two messages. This code is for when your logic sits in the middle and the channel has no Met assigned and no linked flow: the event still arrives and your code decides what to answer. Turning autopilot off doesn’t do that: with autopilot off or paused, a send with an API key returns 409 with code === 'autopilot_silenced' and nothing goes out. Turning it off (met.contacts.setAutopilot, scope handoff:manage) is for handing the conversation to a person, who answers from the inbox. There is more in the agent that answers WhatsApp recipe.

What you have to run on each path

Cloud API directlyMeteor IA SDK
Connecting the numberYour Meta app, its WhatsApp Business account and the Phone Number IDOnce, from the dashboard (Canales → WhatsApp)
CredentialMeta system user tokenMeteor IA key with scopes
Sending a textPOST to the Graph API with Meta’s bodymet.contacts.sendMessage
ReceivingWebhook with GET verification and X-Hub-Signature-256 signatureWebhook with X-Met-Signature signature and constructEvent
Answering with AIYou build itA Met assigned to the channel, with autopilot, or your code with met.runs.create
What you payThe messages Meta charges forThe Meteor IA plan, the Energy the AI uses and the messages Meta charges for

If you are still deciding, the Cloud API or Meteor guide on the portal compares both paths for builders. For the basics of the API, start with what the WhatsApp Business API is, and what Meta charges per message is in how much the API costs. If you write Python, the same tutorial is with Python.

The limits

What this article does NOT answer

We would rather say it here than leave you hunting for something that is not there.

Keep going

What this article mentions, in detail

The integrations, the Mets and the automations named above, each with its own page.

Where it comes from

Sources

Everything this article claims that we did not measure ourselves, with its origin.

Frequently asked

Questions on this topic

The latest in Meta’s version log: v26.0 on December 2, 2026. Some examples already use v27.0, which is not in the log yet; check it before pinning it.

No. Free-form text only goes through within 24 hours of the person’s last message. To message first you need an approved template, with type “template”.

For testing, the temporary token from your app’s API Setup page, which expires quickly. For development, a system user token with the business_management, whatsapp_business_messaging and whatsapp_business_management permissions.

Because the signature is computed over the raw body. If your framework parses the JSON and serializes it again before you verify, the bytes change. In Express, use express.raw on that route, both for Meta’s webhook and for Meteor IA’s.

No. met_test_ keys do not send WhatsApp. For the first message you need a live key with the contacts:write and channels:send scopes.

Keep reading

Other articles on the same thing

Want to see it running on your operation?

See the API, the SDK and the MCP server, or message us and we will help with your first key.