Use cases
Facebook and Instagram lead ads follow-up over WhatsApp
Meta posts a leadgen webhook to your server when someone submits a lead form. Verify its signature, fetch the lead with the Graph API, and send one WhatsApp message through HelloHop while the lead is still warm. Send it only when the form told the person you would contact them on WhatsApp.
Facts (as of October 2026, API v1)
- A Page subscribed to the leadgen field sends a webhook with a leadgen_id and a form_id. The lead itself is fetched with GET on the leadgen_id, and its answers are in field_data.
- Meta signs each webhook delivery with an X-Hub-Signature-256 header: sha256= followed by the hex HMAC-SHA256 of the raw body, keyed with your app secret.
- Meta verifies your URL once with a GET carrying hub.mode, hub.verify_token and hub.challenge. You echo hub.challenge when the token matches.
- The unified POST
/v1/sessions/{channel}/messagesroute accepts an Idempotency-Key of up to 255 characters. Repeating the same key and body within 24 hours returns the first result without another send, with the response header Idempotent-Replayed: true. - A 504 send_unconfirmed, a timeout, a 409 idempotency_uncertain or a 503 with ambiguous true means the message may have gone out. Treat it as possibly delivered and look at the chat before you send it again.
- The free sandbox channel allows 180 messages sent a day and 10 new chats a month, counted in Bangkok time. That is enough to build and test the whole flow before you pay.
- Prices: from $20 USD per number per month, billed annually, with a free sandbox and no per-message fees.
Steps
- Add a phone field and a consent line to the form. The lead form should ask for the phone number and say the person agrees to be contacted on WhatsApp about their inquiry.
- Subscribe your Page to leadgen. In your Meta app add a webhook for the Page object with the leadgen field. Verify the URL when Meta calls it with a GET.
- Verify and fetch. Check X-Hub-Signature-256 on the raw body, then fetch the lead by leadgen_id and read the phone answer.
- Send one first message. Save the lead id, answer 200, then call HelloHop with the lead id in the Idempotency-Key. If there is no number with a country code, hand the lead to a person.
The job: answer while they are still looking
A person who has just submitted a lead form has asked to hear from you. A first WhatsApp message within a minute reaches them while the request is fresh. Everything after the first message is a human conversation, so this page sends one message and stops.
The flow in your own code
| Step | Where it runs | Call |
|---|---|---|
| Form submitted | Meta | Webhook with leadgen_id and form_id to your receiver |
| Fetch the answers | Your receiver | Graph API GET on the leadgen_id, with a Page token |
| First message | Your receiver | POST /v1/sessions/{channel}/messages |
The receiver (Node.js)
The Graph API call needs a Page access token that can read leads, and the webhook needs a Page subscribed to leadgen. The sample reads the token, the app secret, the verify token and the Graph API version (GRAPH_VERSION) from the environment. The formAllowsWhatsApp hook is yours: return true only for forms whose consent line mentions WhatsApp. Implement the event database helpers and a timer that calls recoverAbandonedClaims before retrying pending leads. A crash after claiming leaves an unknown send outcome for review, not an automatic resend. Conditional finish writes preserve recovered unknown rows. The wording is an example, so write your own before you use it.
// Meta: https://developers.facebook.com/docs/marketing-api/guides/lead-ads/retrieving
// Webhook: leadgen field on a Page subscription; signature in X-Hub-Signature-256
// (sha256= plus hex HMAC-SHA256 of the raw body with the app secret).
import crypto from 'node:crypto';
import express from 'express';
const API = 'https://api.hellohop.app/v1';
const { CHANNEL_ID, CHANNEL_TOKEN } = process.env;
// One send. Repeating the same key with the same body returns the first result.
async function sendWhatsApp(key, message) {
try {
const res = await fetch(`${API}/sessions/${CHANNEL_ID}/messages`, {
method: 'POST',
headers: {
Authorization: `Bearer ${CHANNEL_TOKEN}`,
'Content-Type': 'application/json',
'Idempotency-Key': key,
},
body: JSON.stringify(message),
signal: AbortSignal.timeout(15000),
});
const data = await res.json().catch(() => ({}));
const result = { status: res.status, code: data.code, ambiguous: data.ambiguous, id: data.id };
if (classify(result) === 'retry') {
// 429 whatsapp_rate_limited carries no Retry-After, so it falls back to 1 second. This helper waits at most 30 seconds;
// a longer Retry-After is not slept through: result.retryAt (Unix ms) says when the row is due, and your sweep or timer retries then.
const h = res.headers.get('Retry-After');
const ms = Math.max(0, (h ? (/^\d+$/.test(h) ? Number(h) * 1000 : Date.parse(h) - Date.now()) : 1000) || 1000);
result.retryAt = Date.now() + ms;
await new Promise((resolve) => setTimeout(resolve, Math.min(30000, ms)));
}
return result;
} catch {
return { status: 0 }; // timeout or lost connection: the message may have gone out
}
}
// One answer per send: sent (server_ack), queued, retry, unknown or failed.
function classify({ status, code, ambiguous }) {
if (status === 200) return 'sent'; // server_ack, not delivered
if (status === 202) return 'queued'; // observe webhooks, do not resend
// Refused before sending: repeat the same key and body later.
const refused = ['upstream_unavailable', 'hopsmart_settings_unavailable', 'operator_unresolved'];
if (status === 429 || (status === 503 && (ambiguous === false || refused.includes(code)))) return 'retry';
// Possibly sent: look at the chat, never resend.
if (status === 0 || status >= 500 || code === 'idempotency_uncertain') return 'unknown';
return 'failed'; // an unlinked channel, idempotency_conflict, a bad request: fix it, do not retry
}
// Your events table: unique key, payload, state, claimed_at (Unix ms), message_id. Helpers:
// saveEvent(key, payload) insert a pending row once; a repeat changes nothing
// claimSend(key) atomic pending -> claimed, sets claimed_at; true for one caller only
// finish(key, expected, state, id) UPDATE only WHERE state = expected; save the message id
// retry returns to pending with the SAME saved message body; all others stop automatic sends
// skipPending(key) UPDATE pending -> skipped only; never overwrites a claim/outcome
// Your timer must call this first, then re-run pending payloads. Never re-send unknown rows.
// db.run(sql, params) executes SQL in your database; claimed_at is Unix milliseconds.
async function recoverAbandonedClaims() {
await db.run("UPDATE events SET state = 'unknown' WHERE state = 'claimed' AND (claimed_at IS NULL OR claimed_at < ?)",
[Date.now() - 5 * 60 * 1000]);
}
const app = express();
const { META_APP_SECRET, META_VERIFY_TOKEN, META_PAGE_TOKEN, GRAPH_VERSION } = process.env;
// Meta checks your URL once with a GET. Echo hub.challenge when the verify token matches.
app.get('/webhooks/meta', (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);
});
function validMeta(raw, header) {
const expected = 'sha256=' + crypto.createHmac('sha256', META_APP_SECRET).update(raw).digest('hex');
return typeof header === 'string' && header.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(header), Buffer.from(expected));
}
async function fetchLead(leadgenId) {
const url = `https://graph.facebook.com/${GRAPH_VERSION}/${leadgenId}?access_token=${META_PAGE_TOKEN}`;
const res = await fetch(url);
if (!res.ok) throw new Error(`graph ${res.status}`); // the row stays pending; a timer retries
const lead = await res.json();
const field = (name) => lead.field_data?.find((f) => f.name === name)?.values?.[0];
// Question names are the keys set on your form. Rename these two to match it.
return { phone: field('phone_number'), name: field('full_name') };
}
async function processLead(key, leadgenId, formId) {
const { phone, name } = await fetchLead(leadgenId);
// Send only if the form told the person you would message them on WhatsApp.
if (!phone?.startsWith('+') || !(await formAllowsWhatsApp(formId))) return skipPending(key);
if (!(await claimSend(key))) return; // one send per lead, even when Meta delivers it again
const result = await sendWhatsApp(key, {
type: 'text',
to: phone.replace(/\D/g, ''),
text: `Hi ${name || 'there'}, thanks for your interest. How can we help? Reply here and a person will answer.`,
});
await finish(key, 'claimed', classify(result), result.id);
}
app.post('/webhooks/meta', express.raw({ type: 'application/json' }), async (req, res) => {
if (!validMeta(req.body, req.get('X-Hub-Signature-256'))) return res.sendStatus(401);
const body = JSON.parse(req.body.toString('utf8'));
const leads = (body.entry || []).flatMap((e) => e.changes || []).filter((c) => c.field === 'leadgen');
try {
for (const { value } of leads) await saveEvent(`lead-${value.leadgen_id}`, JSON.stringify(value)); // durable first
} catch {
return res.sendStatus(500); // Meta delivers the update again
}
res.sendStatus(200);
for (const { value } of leads) {
processLead(`lead-${value.leadgen_id}`, value.leadgen_id, value.form_id).catch(console.error);
}
});
app.listen(3002);The send call by hand
API=https://api.hellohop.app/v1
curl -s -X POST "https://api.hellohop.app/v1/sessions/$CHANNEL_ID/messages" \
-H "Authorization: Bearer $CHANNEL_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: lead-LEADGEN_ID" \
-d '{"type":"text","to":"66XXXXXXXXX","text":"Hi Anna, thanks for your interest. How can we help? Reply here and a person will answer."}'What the handler does with each send result
| Send result | What your handler does |
|---|---|
| 200 server_ack | WhatsApp acknowledged the send. Mark it sent and save id; this is not a delivery receipt. |
| 202 queued | Persisted in the queue, not delivered. A channel that queues its sends (for example while accepted sends drain) answers every text send this way, with id, status queued, position and expires_at. Mark it queued and save id. Observe the result through webhooks without resending. |
| 429, or 503 with ambiguous false or code upstream_unavailable, hopsmart_settings_unavailable or operator_unresolved | Refused before sending. Honor Retry-After, keep the same key and body, and retry later. The Node helper waits at most 30 seconds before returning retry with a retryAt time, and the pages that keep a due time skip the row until then; the other Node timer pages retry on their next run. The Flask, Python reminder and PHP samples return the time to retry instead of waiting; the Sheets helper saves next_attempt_at and skips the row until then. |
| 504 send_unconfirmed, 409 idempotency_uncertain, 503 with ambiguous true, a timeout or a lost response | Possibly delivered. Mark it unknown and look at the chat before any resend. Never force a resend of an uncertain key with a new key. |
| 409 idempotency_conflict | The same key was used for a different message. Fix how you build the key. The first message is unchanged. |
| Any other 409 | Mark it failed. Fix the channel before scheduling another attempt. |
| Other 4xx | The request is wrong and a retry will not fix it. Log it and move on. |
Subscribe to message and message.status webhooks and verify their signatures. The result of a queued send arrives as a message event: match the saved response id to payload.id. message.status reports delivered or read for each id in payload.ids. A send held by HopSmart™ expires 72 hours after acceptance, and the 202 carries expires_at. If no event arrives, read the job with GET /hopsmart/jobs/{id}. Save event ids to deduplicate. Do not resend queued work while waiting for a result.
Send only to people who agreed
Submitting a form is not the same as agreeing to WhatsApp. Put the agreement in the form, store which forms carry it, and message only people from those forms. Keep to the inquiry they made.
Common mistakes
- Verifying the signature on parsed JSON. Use the raw bytes.
- Answering slowly. Save the lead id, answer 200, and fetch the lead after.
- Assuming the phone answer has a country code. Check for it and skip the send when it is missing.
- Messaging leads from forms that never mentioned WhatsApp.
Questions
- Does Meta send the lead answers in the webhook?
- No. The webhook carries ids. Your receiver fetches the lead with the Graph API using the leadgen_id, then reads field_data.
- What if the phone number has no country code?
- Skip the message and hand the lead to a person. Do not guess a country.
- How do I avoid messaging a lead twice?
- Use the leadgen_id as the Idempotency-Key and as a unique key in your own table, and claim it before you send. Meta can deliver a lead again later than the 24-hour key window, and the claim still stops the second message.
- Can n8n or Make do this instead of code?
- Yes. Any tool that can receive the webhook, call the Graph API and call an HTTPS API can run the same steps.
- Can I try it without paying?
- Yes. Every account has one free sandbox channel that allows 10 new chats a month, which is enough to test with your own number.
Free sandbox, forever. Upgrade when you're ready.
Start freeKeep going
HelloHop is an independent WhatsApp API for developers: send and receive messages, automate groups and communities, and get signed webhooks. Not affiliated with WhatsApp or Meta. You link your own number.