Use cases
Ask for a review over WhatsApp after delivery
When your order system marks an order delivered, save one review request row, wait two days, claim the row at send time and send one WhatsApp message with the review link through HelloHop. A STOP reply arrives as a message event, and your receiver cancels that customer's pending requests. Message only customers who agreed to order messages.
Facts (as of October 2026, API v1)
- The request is one POST
/v1/sessions/{channel}/messagescall. Package delivery status comes from your own order or courier system, because HelloHop reports only WhatsApp message receipts. - An inbound reply arrives as a message event with chat_jid, text, from_me and is_group. When chat_pn_resolved is false the chat_jid is a LID, so look up the stored phone before you act.
- 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
- Receive the delivered notice. Your order system calls your endpoint with the order id, phone, name, review link and whether the customer agreed to WhatsApp messages. Save one row per order.
- Wait. Set send_after to two days after the delivered notice. The sample keeps the delay in DELAY_MS.
- Claim at send time. A timer claims due rows with a condition that excludes anyone who opted out since the order.
- Send once. Save the text, send it with the row key as the Idempotency-Key and record the outcome.
- Handle STOP. Subscribe a receiver to message events. A reply that is only STOP records an opt-out and skips pending rows.
The job: reviews without nagging
Ask once, two days after the package arrives, with a link and an easy way to say no. The sample sends exactly one request per order and none to anyone who replied STOP before the send.
Receiver, timer and opt-out (Node.js)
The sample refuses to start without a nonempty ORDERS_TOKEN. It has two receivers: your own order endpoint, protected by that shared bearer token, and the signed WhatsApp webhook for STOP replies. A repeated delivered notice changes nothing, because the order id is the row key. A STOP that arrives after a claim has won cannot recall that message. The webhook PUT under Subscribe to replies replaces the whole receiver list for the channel, so include any receivers you keep. The text is an example: write your own.
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
}
const { WEBHOOK_SECRET } = process.env;
if (!WEBHOOK_SECRET || WEBHOOK_SECRET.length < 24) throw new Error('Set WEBHOOK_SECRET to the receiver secret (24 characters or more) before you start');
function validSignature(raw, header) {
const expected = crypto.createHmac('sha256', WEBHOOK_SECRET).update(raw).digest('hex');
return typeof header === 'string' && header.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(header), Buffer.from(expected));
}
// Your tables (SQLite examples: db.run returns { changes }, db.all returns rows, db.get one row). Times are Unix ms.
// review_requests: key (unique), phone (digits with country code), name, order_id, review_url, send_after, state, claimed_at, body, message_id
// optouts: phone (unique)
// resolvePhone(chatJid) looks up the stored phone, including its LID alias; never guess a LID.
const { ORDERS_TOKEN } = process.env;
if (!ORDERS_TOKEN?.trim()) throw new Error('Set a nonempty ORDERS_TOKEN before starting');
const DELAY_MS = 2 * 24 * 60 * 60 * 1000; // ask two days after delivery
const app = express();
// Your order system calls this when an order is marked delivered. Set ORDERS_TOKEN and send it as a bearer token.
app.post('/orders/delivered', express.json(), async (req, res) => {
const given = Buffer.from(req.get('Authorization') ?? '');
const want = Buffer.from(`Bearer ${ORDERS_TOKEN}`);
if (given.length !== want.length || !crypto.timingSafeEqual(given, want)) return res.sendStatus(401);
const o = req.body;
const phone = String(o.phone ?? '').replace(/\D/g, '');
// Only customers who agreed to WhatsApp messages about their order.
if (!o.order_id || !phone || o.whatsapp_ok !== true) return res.sendStatus(200);
try {
// One row per order. A repeated delivered notice changes nothing, even after the request was sent.
await db.run("INSERT INTO review_requests (key, phone, name, order_id, review_url, send_after, state) VALUES (?, ?, ?, ?, ?, ?, 'pending') ON CONFLICT(key) DO NOTHING",
[`review-${o.order_id}`, phone, o.name ?? 'there', o.order_id, o.review_url, Date.now() + DELAY_MS]);
} catch {
return res.sendStatus(500); // your order system retries
}
res.sendStatus(200);
});
// Run every 15 minutes.
async function runReviews() {
await db.run("UPDATE review_requests SET state = 'unknown' WHERE state = 'claimed' AND (claimed_at IS NULL OR claimed_at < ?)", [Date.now() - 5 * 60 * 1000]);
// Anyone who opted out since the row was saved gets nothing.
await db.run("UPDATE review_requests SET state = 'skipped' WHERE state = 'pending' AND EXISTS (SELECT 1 FROM optouts o WHERE o.phone = review_requests.phone)", []);
const due = await db.all("SELECT key, phone, name, order_id, review_url FROM review_requests WHERE state = 'pending' AND send_after <= ? ORDER BY send_after LIMIT 200", [Date.now()]);
for (const d of due) {
// Claim at send time. A STOP that arrived since the order stops it here; one that lands after the claim is in flight.
const claim = await db.run("UPDATE review_requests SET state = 'claimed', claimed_at = ? WHERE key = ? AND state = 'pending' AND NOT EXISTS (SELECT 1 FROM optouts o WHERE o.phone = review_requests.phone)", [Date.now(), d.key]);
if (claim.changes !== 1) continue;
const text = `Hi ${d.name}, your order ${d.order_id} was delivered. If you have a minute, a review helps us a lot: ${d.review_url} Reply STOP and we will not ask again.`;
await db.run('UPDATE review_requests SET body = ? WHERE key = ? AND body IS NULL', [text, d.key]);
const { body } = await db.get('SELECT body FROM review_requests WHERE key = ?', [d.key]);
const result = await sendWhatsApp(d.key, { type: 'text', to: d.phone, text: body });
const outcome = classify(result);
await db.run("UPDATE review_requests SET state = ?, message_id = ? WHERE key = ? AND state = 'claimed'", [outcome === 'retry' ? 'pending' : outcome, result.id ?? null, d.key]);
if (outcome === 'retry') break; // the helper waited at most 30 seconds; the next run resumes with the same key
}
}
setInterval(() => runReviews().catch(console.error), 15 * 60 * 1000);
// The opt-out reply arrives as a message event. Subscribe the receiver to message.
async function onEvent(event) {
const m = event.payload;
if (event.type !== 'message' || m.from_me || m.is_group || !/^\s*stop\s*$/i.test(m.text || '')) return;
const phone = await resolvePhone(m.chat_jid); // a phone JID, or a LID when chat_pn_resolved is false
if (!phone) throw new Error('Resolve this sender before acknowledging STOP');
await db.run('INSERT INTO optouts (phone) VALUES (?) ON CONFLICT(phone) DO NOTHING', [phone]);
await db.run("UPDATE review_requests SET state = 'skipped' WHERE phone = ? AND state = 'pending'", [phone]);
}
app.post('/webhooks/whatsapp', express.raw({ type: 'application/json' }), async (req, res) => {
if (!validSignature(req.body, req.get('X-HelloHop-Signature'))) return res.sendStatus(401);
try {
await onEvent(JSON.parse(req.body.toString('utf8'))); // both writes are repeat-safe, so record first, then answer
} catch {
return res.sendStatus(500); // the webhook is delivered again
}
res.sendStatus(200);
});
app.listen(3006);Subscribe to replies
API=https://api.hellohop.app/v1
curl -s -X PUT "$API/sessions/$CHANNEL_ID/webhooks" \
-H "Authorization: Bearer $CHANNEL_TOKEN" \
-H "Content-Type: application/json" \
-d '{"receivers":[{"url":"https://example.com/webhooks/whatsapp","events":["message"],"secret":"REPLACE_WITH_24_PLUS_CHARACTERS"}]}'What the timer 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.
Who may be messaged
Ask for a review only from customers who agreed to WhatsApp messages about their order. Ask once per order and say how to stop.
Questions
- How does the delivered notice reach the code?
- HelloHop does not track packages. Your order or courier system calls your endpoint. The sample accepts it at POST /orders/delivered behind a bearer token.
- How do I make sure a customer gets one request per order?
- The row key is the order id, and the insert does nothing on a repeat. The claim and the Idempotency-Key add protection against overlapping runs and resends.
- How does the opt-out work?
- A reply that is only STOP arrives as a message event. The receiver records the number and skips its pending rows. The claim condition checks the opt-out again at send time.
- What if the send times out?
- Treat it as possibly delivered, record it as unknown and look at the chat before any resend.
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.