Create a drip sequence of approved templates with waits between them, enrol new customers, stop it when they reply or opt out, and follow the report for every step.
In this guide you build a three-message welcome series: a welcome on the day a customer signs up, a care tip two days later, and a discount offer on day 7. You make it once. After that, each customer you enrol gets the messages on their own schedule.
What the customer sees: a WhatsApp message from your business right after they sign up: "Hi Jane, welcome to Green Leaf Plants!" Two days later a link to your plant care guide. On day 7 a 10% code for their next order. If they reply at any point, the series stops and your team takes the chat. If they reply STOP, they get no more marketing from you.
What you see: for every step, how many messages were posted, sent, delivered, read, failed and clicked. For every customer, which steps they got, when the next one is due and why they stopped. Webhook events tell your system when a customer clicks a link and when they leave the sequence.
POST /sequences: 1 to 20 steps, each a template with its values and a wait.POST /sequences/{id}/enrolments, or let app2email enrol everyone who gets a tag.sequence.finished each time.Nobody gets anything until you enrol them. Creating a sequence sends nothing.
sequences_not_enabled. A personal WhatsApp number linked by QR code cannot send templates, so it has no sequences (403 sequence_personal_number).| Scope | What it is for in this guide |
|---|---|
templates:manage | Create the three templates (POST /templates) |
messages:send | Create, change, pause and delete the sequence, enrol contacts and take them out (POST /sequences, PUT /sequences/{id}, DELETE /sequences/{id}, POST /sequences/{id}/enrolments, DELETE /sequences/{id}/enrolments/{contact}) |
messages:read | Template status, the sequence's report, who is in it (GET /templates, GET /sequences/{id}, GET /sequences/{id}/enrolments, GET /broadcasts/{code}) |
contacts:manage | Only if you enrol by tag: give contacts the tag (PATCH /contacts/{identity}) |
webhooks:manage | Add the webhook that receives the events (POST /webhooks). You can also add it on the API key page, without code |
GET /v1/YOUR_NUMBER/me shows the scopes of the key you have.
Trying it first. A sandbox key on your own number (a key with the sandbox flag, made on the API key page) can read your sequences, their reports and their enrolments, and POST /sequences/{id}/enrolments with "dry_run": true counts who would be enrolled without enrolling anyone. Creating, changing and deleting sequences, and real enrolments, answer 403 sandbox_key: use a normal key for those. The instant sandbox (the demo number 12025550100 from POST https://api.app2email.com/v1/account/sandbox) has no sequences; it answers 403 not_in_instant_sandbox. Details: Sandbox.
Every step is a template, and Meta charges each template by its category and the customer's country. Pick the category that matches what the message says:
| Day | Step | Template | Category |
|---|---|---|---|
| 0 | Welcome | welcome_new_customer | MARKETING. A welcome can be UTILITY only when it is strictly about the account or order the customer just made, with nothing promotional in it |
| 2 | Care tip | plant_care_tips | MARKETING. Tips and content are not about a transaction |
| 7 | Offer | welcome_offer | MARKETING. Any discount or promotion is marketing |
Meta reviews the category with the template, and a promotion sent as UTILITY gets rejected or moved to MARKETING. MARKETING templates go only to people who are not on your Do Not Call list, and with the opt-in rule on only to people with an opt-in record. Estimate what the series costs with the WhatsApp pricing calculator: three marketing templates per customer, times the number of customers you expect per month.
Every call goes to https://api.app2email.com/v1/YOUR_NUMBER with Authorization: Bearer YOUR_API_KEY. YOUR_NUMBER is your WhatsApp number: country code first, digits only.
Write each message with numbered placeholders, give a sample value for each in example, and add a footer that says how to stop. STOP and its translations are opt-out words app2email knows already. Put every link in a placeholder, not in the fixed text: app2email can then give each customer their own tracked link (see step 2).
| Template | Body | Values |
|---|---|---|
welcome_new_customer | Hi {{1}}, welcome to Green Leaf Plants! We are happy you are here. Reply to this message any time if you have a question. | name |
plant_care_tips | Hi {{1}}, here is our quick guide to keeping your new plants happy: {{2}} Happy growing! | name, link |
welcome_offer | Hi {{1}}, thanks for being with us this week. Use the code {{2}} for 10% off your next order: {{3}} The code is valid for 7 days. | name, code, link |
The offer, as one request (the other two are the same with their own text and samples):
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/templates \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "welcome_offer",
"language": "en",
"category": "MARKETING",
"components": [
{
"type": "BODY",
"text": "Hi {{1}}, thanks for being with us this week. Use the code {{2}} for 10% off your next order: {{3}} The code is valid for 7 days.",
"example": { "body_text": [["Jane", "WELCOME10", "https://www.example.com/shop"]] }
},
{ "type": "FOOTER", "text": "Reply STOP to opt out" }
]
}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/templates", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({
name: "welcome_offer",
language: "en",
category: "MARKETING",
components: [
{
type: "BODY",
text: "Hi {{1}}, thanks for being with us this week. Use the code {{2}} for 10% off your next order: {{3}} The code is valid for 7 days.",
example: { body_text: [["Jane", "WELCOME10", "https://www.example.com/shop"]] },
},
{ type: "FOOTER", text: "Reply STOP to opt out" },
],
}),
});
console.log(res.status, await res.json());import os, requests
res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/templates",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
json={
"name": "welcome_offer",
"language": "en",
"category": "MARKETING",
"components": [
{
"type": "BODY",
"text": "Hi {{1}}, thanks for being with us this week. Use the code {{2}} for 10% off your next order: {{3}} The code is valid for 7 days.",
"example": {"body_text": [["Jane", "WELCOME10", "https://www.example.com/shop"]]},
},
{"type": "FOOTER", "text": "Reply STOP to opt out"},
],
},
timeout=10,
)
print(res.status_code, res.json())What you get back (201 Created): the template is with Meta for review.
{
"success": true,
"request_id": "c3ppl",
"template": {
"id": "2234567890",
"name": "welcome_offer",
"language": "en",
"category": "MARKETING",
"status": "PENDING"
},
"note": "Submitted to WhatsApp for review (minutes to a day). You get a template.status_changed webhook event with the result, or GET https://api.app2email.com/v1/4976659348270/templates/welcome_offer."
}Review takes minutes to a day. The template.status_changed event tells you the result (status APPROVED with can_send: true, or REJECTED with a reason), or ask GET /templates/welcome_offer. Wait until all three are APPROVED before you enrol anyone. The template review in more depth: Send order and appointment notifications with templates.
One call with the three steps. The waits count from the step before, so day 7 is 5 days after the tip on day 2:
| Step | Wait | Sent on |
|---|---|---|
welcome_new_customer | wait_days: 0 | day 0, right after enrolling |
plant_care_tips | wait_days: 2 | day 2 |
welcome_offer | wait_days: 5 | day 7 |
A wait can be given as wait_minutes, wait_hours or wait_days; sent together they add up. Each wait is 0 to 90 days.
In the step values, {name} is the contact's name. When it is not known, name_fallback is used instead (default "there"). track_clicks is on by default: every address in the values becomes a tracked link of its own for each contact, so you see who clicked.
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/sequences \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Welcome series",
"stop_on_reply": true,
"steps": [
{ "wait_days": 0, "template_name": "welcome_new_customer", "language": "en",
"parameters": { "body": ["{name}"], "name_fallback": "there" } },
{ "wait_days": 2, "template_name": "plant_care_tips", "language": "en",
"parameters": { "body": ["{name}", "https://www.example.com/plant-care"], "name_fallback": "there" } },
{ "wait_days": 5, "template_name": "welcome_offer", "language": "en",
"parameters": { "body": ["{name}", "WELCOME10", "https://www.example.com/shop"], "name_fallback": "there" } }
]
}'const step = (wait_days, template_name, body) => ({
wait_days, template_name, language: "en", parameters: { body, name_fallback: "there" },
});
const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/sequences", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({
name: "Welcome series",
stop_on_reply: true,
steps: [
step(0, "welcome_new_customer", ["{name}"]),
step(2, "plant_care_tips", ["{name}", "https://www.example.com/plant-care"]),
step(5, "welcome_offer", ["{name}", "WELCOME10", "https://www.example.com/shop"]),
],
}),
});
const { sequence } = await res.json();
console.log(res.status, sequence.id, sequence.steps.map((s) => s.id));def step(wait_days, template_name, body):
return {"wait_days": wait_days, "template_name": template_name, "language": "en",
"parameters": {"body": body, "name_fallback": "there"}}
res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/sequences",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
json={
"name": "Welcome series",
"stop_on_reply": True,
"steps": [
step(0, "welcome_new_customer", ["{name}"]),
step(2, "plant_care_tips", ["{name}", "https://www.example.com/plant-care"]),
step(5, "welcome_offer", ["{name}", "WELCOME10", "https://www.example.com/shop"]),
],
},
timeout=10,
)
sequence = res.json()["sequence"]
print(res.status_code, sequence["id"], [s["id"] for s in sequence["steps"]])What you get back (201 Created; shortened to the first step in steps and report):
{
"success": true,
"request_id": "s2new",
"sequence": {
"id": 12,
"name": "Welcome series",
"status": "active",
"stop_on_reply": true,
"enrol_tag": "",
"enrol_tag_since": null,
"created_by": "api",
"created_at": "2026-11-19T01:00:00.000Z",
"updated_at": "2026-11-19T01:00:00.000Z",
"steps": [
{
"id": 31,
"position": 0,
"wait_days": 0,
"wait_minutes": 0,
"template_name": "welcome_new_customer",
"language": "en",
"parameters": { "body": ["{name}"], "name_fallback": "there" },
"track_clicks": true,
"report_code": null
}
],
"counts": { "enrolled": 0, "active": 0, "finished": 0, "stopped": 0, "stopped_by_reply": 0, "opted_out": 0 },
"report": [
{ "step_id": 31, "position": 0, "template_name": "welcome_new_customer", "posted": 0, "sent": 0, "delivered": 0, "read": 0, "failed": 0, "clicked": 0, "clicks": 0, "report_url": null }
]
}
}Keep sequence.id and the step ids: you need the step ids to change the steps later without losing their reports. The other two steps come back the same way, with wait_minutes 2880 and 7200. stop_on_reply is true by default; opting out always stops a contact, whatever it says. A number can have up to 100 sequences.
POST /sequences takes no Idempotency-Key. If the answer is lost, look at GET /sequences before you create it again, so you do not end up with two.
Send numbers (numbers), numbers with names (contacts), every contact of a saved segment (segment_id) or every contact with a tag (tag), up to 5000 per call. Start with "dry_run": true: it counts who would be enrolled and enrols nobody.
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/sequences/12/enrolments \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contacts": [
{ "number": "61412345678", "name": "Jane" },
{ "number": "61498765432", "name": "Tom" }
],
"dry_run": true
}'async function enrol(sequenceId, contacts, dryRun = false) {
const res = await fetch(`https://api.app2email.com/v1/YOUR_NUMBER/sequences/${sequenceId}/enrolments`, {
method: "POST",
headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ contacts, dry_run: dryRun }),
});
return res.json();
}
const contacts = [{ number: "61412345678", name: "Jane" }, { number: "61498765432", name: "Tom" }];
console.log(await enrol(12, contacts, true)); // count only
console.log(await enrol(12, contacts)); // for realdef enrol(sequence_id, contacts, dry_run=False):
res = requests.post(
f"https://api.app2email.com/v1/YOUR_NUMBER/sequences/{sequence_id}/enrolments",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
json={"contacts": contacts, "dry_run": dry_run},
timeout=10,
)
return res.json()
contacts = [{"number": "61412345678", "name": "Jane"}, {"number": "61498765432", "name": "Tom"}]
print(enrol(12, contacts, dry_run=True)) # count only
print(enrol(12, contacts)) # for realWhat you get back (200, the same shape with and without dry_run):
{
"success": true,
"request_id": "s7enr",
"sequence_id": 12,
"enrolled": 2,
"already_in_it": 0,
"on_do_not_call_list": 0,
"not_a_number": 0,
"first_step_at": "2026-11-19T01:00:00.000Z",
"note": null
}Then send the same body without dry_run. Contacts on the Do Not Call list, contacts already in this sequence and anything that is not a phone number are skipped and counted. That makes the call safe to repeat: a contact is never enrolled twice. first_step_at is when the first step goes out.
In your sign-up code, enrol each new customer as they sign up, with their name, so the welcome arrives at once.
One call (or add it on the API key page under Webhooks). Keep the whsec_... secret from the answer: it signs every event.
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://www.example.com/whatsapp/webhook"}'Every webhook gets every event type; your code picks sequence.finished, link.clicked and the others below by type and answers 2xx to the rest within 10 seconds. How to set it up and check the signature, with a tunnel for your own computer: Build a WhatsApp chatbot with the API.
No public address? GET /events?wait=25&types=sequence.finished (scope messages:read) fetches the same events.
GET /sequences/{id} has the counts and a report per step. GET /sequences/{id}/enrolments has each contact.
curl https://api.app2email.com/v1/YOUR_NUMBER/sequences/12 \
-H "Authorization: Bearer YOUR_API_KEY"
# who is still in it, with the next step and when it is due
curl "https://api.app2email.com/v1/YOUR_NUMBER/sequences/12/enrolments?status=active&limit=100" \
-H "Authorization: Bearer YOUR_API_KEY"const headers = { Authorization: `Bearer ${process.env.API_KEY}` };
const { sequence } = await (await fetch("https://api.app2email.com/v1/YOUR_NUMBER/sequences/12", { headers })).json();
console.log(sequence.counts);
for (const row of sequence.report) console.log(row.template_name, row.delivered, row.read, row.clicked);
const { enrolments } = await (await fetch(
"https://api.app2email.com/v1/YOUR_NUMBER/sequences/12/enrolments?status=active&limit=100", { headers })).json();
for (const e of enrolments) console.log(e.contact, e.steps_sent, e.next_at);headers = {"Authorization": f"Bearer {os.environ['API_KEY']}"}
sequence = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/sequences/12", headers=headers, timeout=10).json()["sequence"]
print(sequence["counts"])
for row in sequence["report"]:
print(row["template_name"], row["delivered"], row["read"], row["clicked"])
enrolments = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/sequences/12/enrolments",
params={"status": "active", "limit": 100}, headers=headers, timeout=10).json()["enrolments"]
for e in enrolments:
print(e["contact"], e["steps_sent"], e["next_at"])What you get back from GET /sequences/12 a week later (shortened: steps left out):
{
"success": true,
"request_id": "s3get",
"sequence": {
"id": 12,
"name": "Welcome series",
"status": "active",
"stop_on_reply": true,
"enrol_tag": "",
"counts": { "enrolled": 120, "active": 64, "finished": 31, "stopped": 25, "stopped_by_reply": 21, "opted_out": 3 },
"report": [
{ "step_id": 31, "position": 0, "template_name": "welcome_new_customer", "posted": 120, "sent": 120, "delivered": 118, "read": 97, "failed": 2, "clicked": 0, "clicks": 0,
"report_url": "https://www.app2email.com/dashboard/log/broadcast/k3XbQ9rTzP2mWv7a1c9e" },
{ "step_id": 32, "position": 1, "template_name": "plant_care_tips", "posted": 81, "sent": 81, "delivered": 80, "read": 66, "failed": 0, "clicked": 29, "clicks": 41,
"report_url": "https://www.app2email.com/dashboard/log/broadcast/m7TqW2xRb9LpZc4d8e1f" },
{ "step_id": 33, "position": 2, "template_name": "welcome_offer", "posted": 34, "sent": 34, "delivered": 34, "read": 30, "failed": 0, "clicked": 12, "clicks": 15,
"report_url": "https://www.app2email.com/dashboard/log/broadcast/p2HsK8vYc3NwQf6g9h2j" }
]
}
}counts: how many were enrolled, are still in it, got every step (finished), or left early (stopped, of which stopped_by_reply replied and opted_out opted out).report, per step: posted, sent, delivered, read, failed, and clicked (contacts who clicked a tracked link of the step; clicks counts every click).report_code in steps after its first send. GET /broadcasts/{code} with it gives that step's result per number, the same as a broadcast report; report_url opens it in the dashboard.One enrolment from GET /sequences/12/enrolments:
{
"success": true,
"request_id": "s6enl",
"sequence_id": 12,
"enrolments": [
{
"id": 501,
"contact": "61412345678",
"name": "Jane",
"status": "active",
"stop_reason": null,
"steps_sent": 1,
"next_step": 2,
"next_at": "2026-11-21T01:00:00.000Z",
"last_sent_at": "2026-11-19T01:00:00.000Z",
"enrolled_at": "2026-11-19T01:00:00.000Z",
"enrolled_by": "api",
"finished_at": null,
"history": [
{ "step": 31, "position": 0, "at": "2026-11-19T01:00:00.000Z", "ok": true, "error": "" }
]
}
]
}status is active, finished or stopped; stop_reason says why a contact stopped. history has every try of every step: ok: false with an error when a step could not go out. limit is 1 to 500 (default 100), the latest first.
For Jane, enrolled on 19 November:
Day 0: "Hi Jane, welcome to Green Leaf Plants!" arrives a moment after she signs up. Your webhook gets message.status events for it (sent, delivered, read), as for any message.
Day 2: the care tip arrives. Its link is her own tracked link (https://www.app2email.com/l/...). When she opens it, your webhook gets link.clicked with the sequence and the step:
{
"id": "evt_Cmp3k9m2Lw8Rt5Yp1Zs03",
"type": "link.clicked",
"created": "2026-11-21T08:12:00.000Z",
"number": "4976659348270",
"data": {
"contact": "61412345678",
"url": "https://www.example.com/plant-care",
"broadcast_code": null,
"sequence_id": 12,
"step_id": 32,
"first_click": true,
"clicks": 1,
"browser": "Safari",
"timestamp": "2026-11-21T08:12:00.000Z"
}
}link.clicked comes for every click; first_click is true only for her first one. Link previews and crawlers are not counted.
Day 7: the offer arrives. When it was the last step, your webhook gets sequence.finished with result completed:
{
"id": "evt_Cmp3k9m2Lw8Rt5Yp1Zs02",
"type": "sequence.finished",
"created": "2026-11-26T01:00:00.000Z",
"number": "4976659348270",
"data": {
"sequence_id": 12,
"sequence": "Welcome series",
"contact": "61412345678",
"result": "completed",
"reason": null,
"steps_sent": 3,
"steps": 3,
"enrolled_at": "2026-11-19T01:00:00.000Z",
"by": "api",
"timestamp": "2026-11-26T01:00:00.000Z"
}
}When she replies on day 3 ("Do you deliver on Saturdays?"), your webhook gets message.received, her chat shows in the Inbox, and the offer is not sent. sequence.finished arrives with result stopped, reason replied and steps_sent 2. A person (or your bot) answers her inside the 24 hour window that her message opened. See Hand a chat from your bot to a person and back.
When she replies STOP (or taps "Stop promotions"), she goes on the Do Not Call list at once. Your webhook gets contact.opted_out, and sequence.finished with reason opted_out.
All the reasons for result stopped:
reason | What happened |
|---|---|
replied | The contact wrote back (only while stop_on_reply is true) |
opted_out | The contact opted out |
removed | You took them out with DELETE /sequences/{id}/enrolments/{contact} |
sequence_deleted | You deleted the sequence |
failed, not_allowed | A step could not go out to this contact. The enrolment's history has the error of the step |
Pause everyone where they are with PUT /sequences/{id} and {"status": "paused"}; {"status": "active"} carries on. Send only what changes. The answer is the whole sequence.
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/sequences/12 \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"status": "paused"}'Change the steps with steps in the same call. It replaces the whole list, in order: send a step's id to keep it and its report, a step without id is new, and a step you leave out is deleted. Contacts who are already past the last step finish. Here the offer moves from day 7 to day 10:
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/sequences/12 \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"steps": [
{ "id": 31, "wait_days": 0, "template_name": "welcome_new_customer", "language": "en", "parameters": { "body": ["{name}"] } },
{ "id": 32, "wait_days": 2, "template_name": "plant_care_tips", "language": "en", "parameters": { "body": ["{name}", "https://www.example.com/plant-care"] } },
{ "id": 33, "wait_days": 8, "template_name": "welcome_offer", "language": "en", "parameters": { "body": ["{name}", "WELCOME10", "https://www.example.com/shop"] } }
]
}'Take one contact out, for example when they buy before the offer arrives:
curl -X DELETE https://api.app2email.com/v1/YOUR_NUMBER/sequences/12/enrolments/61412345678 \
-H "Authorization: Bearer YOUR_API_KEY"{
"success": true,
"request_id": "s8rem",
"sequence_id": 12,
"contact": "61412345678",
"status": "stopped",
"stop_reason": "removed"
}sequence.finished with reason removed follows. A contact who is not in the sequence right now answers 404 enrolment_not_found.
Archive the sequence with DELETE /sequences/{id}. Everyone still in it stops (sequence.finished with reason sequence_deleted for each), and the report stays: GET /sequences?all=true still lists it.
{
"success": true,
"request_id": "s5del",
"id": 12,
"status": "archived",
"stopped": 4
}Instead of calling POST /sequences/{id}/enrolments from your sign-up code, give the sequence an enrol_tag. Contacts who get that tag from now on are enrolled by app2email, each one once. "" switches it off. Contacts who had the tag before are not enrolled; enrol them once with {"tag": "new-customer"} if you want them too.
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/sequences/12 \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"enrol_tag": "new-customer"}'Then tag a contact when they sign up (scope contacts:manage). The tags you send replace the contact's tags, so send the full list:
curl -X PATCH https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678 \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "Jane", "tags": ["new-customer"]}'enrol_tag_since in the sequence shows from when the tag counts. Contacts can also be enrolled from the dashboard or by an automation.
A small handler that checks the signature, ignores events it has seen, and records who finished and who clicked. Set WEBHOOK_SECRET to the whsec_... value of your webhook.
// Node.js 18 or newer. npm install express then node drip-events.mjs
import crypto from "node:crypto";
import express from "express";
const { WEBHOOK_SECRET, PORT = 3000 } = process.env;
const done = new Set(); // handled event ids: use a database table or Redis in production
function verify(raw, header, secret) {
const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]);
if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
const expected = crypto.createHmac("sha256", secret).update(t + ".").update(raw).digest("hex");
return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
}
const app = express();
app.post("/whatsapp/webhook", express.raw({ type: "application/json" }), (req, res) => {
if (!verify(req.body, req.get("X-App2email-Signature"), WEBHOOK_SECRET)) return res.sendStatus(401);
const event = JSON.parse(req.body);
if (event.test || done.has(event.id)) return res.sendStatus(200);
const d = event.data;
if (event.type === "sequence.finished") {
// result completed, or stopped with reason replied | opted_out | removed | failed | not_allowed | sequence_deleted
console.log(`sequence ${d.sequence_id}: ${d.contact} ${d.result} ${d.reason ?? ""} after ${d.steps_sent}/${d.steps} steps`);
} else if (event.type === "link.clicked" && d.sequence_id && d.first_click) {
console.log(`sequence ${d.sequence_id} step ${d.step_id}: ${d.contact} opened ${d.url}`);
} else if (event.type === "contact.opted_out") {
console.log(`${d.number} opted out (${d.source}): mark it in your CRM too`);
}
done.add(event.id);
res.sendStatus(200);
});
app.listen(PORT, () => console.log(`listening on http://localhost:${PORT}/whatsapp/webhook`));# Python 3.9 or newer. pip install flask then flask --app drip_events run --port 3000
import hashlib, hmac, json, os, re, time
from flask import Flask, request
SECRET = os.environ["WEBHOOK_SECRET"]
done = set() # handled event ids: use a database table or Redis in production
def verify(raw: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
t = re.search(r"(?:^|,)\s*t=(\d+)", header or "")
v1 = re.findall(r"(?:^|,)\s*v1=([0-9a-f]+)", header or "")
if not t or not v1 or abs(time.time() - int(t.group(1))) > tolerance:
return False
expected = hmac.new(secret.encode(), t.group(1).encode() + b"." + raw, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(v, expected) for v in v1)
app = Flask(__name__)
@app.post("/whatsapp/webhook")
def webhook():
raw = request.get_data()
if not verify(raw, request.headers.get("X-App2email-Signature"), SECRET):
return "bad signature", 401
event = json.loads(raw)
if event.get("test") or event["id"] in done:
return "", 200
d = event["data"]
if event["type"] == "sequence.finished":
# result completed, or stopped with reason replied | opted_out | removed | failed | not_allowed | sequence_deleted
print(f"sequence {d['sequence_id']}: {d['contact']} {d['result']} {d.get('reason') or ''} after {d.get('steps_sent')}/{d.get('steps')} steps")
elif event["type"] == "link.clicked" and d.get("sequence_id") and d.get("first_click"):
print(f"sequence {d['sequence_id']} step {d['step_id']}: {d['contact']} opened {d['url']}")
elif event["type"] == "contact.opted_out":
print(f"{d['number']} opted out ({d['source']}): mark it in your CRM too")
done.add(event["id"])
return "", 200Estimate it with the WhatsApp pricing calculator. Afterwards, meta_pricing in GET /usage counts the billing month's messages by Meta's category with an indicative cost, and the pricing object in message.status events shows how Meta counted each message.
Approve first, enrol second. Every step's template must be APPROVED in the language of the step. A step whose template cannot be sent shows ok: false with an error in the enrolment's history, and the contact can stop with reason failed. Watch template.status_changed: a template that Meta pauses or disables later cannot be sent either.
Only people who agreed. Enrol customers who gave you consent for WhatsApp marketing. Contacts on the Do Not Call list are skipped at enrolment, and an opt-out during the sequence stops it at once. With the opt-in rule on (PUT /settings/optin), MARKETING steps go only to numbers with an opt-in record; record them with POST /optins.
Keep STOP in the footer. Every marketing template says how to stop. Many blocks and reports lower your quality rating, and a low rating can pause a template and lower your messaging limit. GET /health shows quality_rating.
Leave stop_on_reply on. A customer who writes back wants an answer, not the next step. Answer them in the Inbox or from your bot, inside the 24 hour window their message opened.
Verify every event. Check X-App2email-Signature over the raw body with the webhook's whsec_... secret, in constant time, and refuse a t older than 5 minutes. The code above does this.
Dedupe on the event id. Keep the id of every handled event (also in the header X-App2email-Delivery) for at least two days: a webhook that did not answer 2xx gets the same event again later, with the same id. For your own records, a contact's place in a sequence is the pair sequence_id and contact; each click is step_id, contact and clicks.
Retry enrolments safely. The sequence calls take no Idempotency-Key. POST /sequences/{id}/enrolments is safe to send again: contacts already in the sequence are skipped and counted in already_in_it. Do not repeat POST /sequences blindly; check GET /sequences first.
Respect the limits. Up to 5000 contacts per enrolment call (400 sequence_too_many_contacts above that), 20 steps per sequence, 100 sequences per number. Every answer has X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset; over the limit you get 429 rate_limited with Retry-After. See Limits.
Least access. The code that enrols new customers needs only messages:send. Keep the key on your server, never in a web page or a log.
| What you see | Why | Fix |
|---|---|---|
403 sequences_not_enabled | The number's plan does not include drip sequences | They come with the Standard and Professional plans and the trial: change the plan on the billing page |
403 sequence_personal_number | The number is a personal WhatsApp number linked by QR code, which cannot send templates | Use a WhatsApp Business API number |
403 plan_not_allowed, service_not_live | No plan with the API, or the service is paused | Choose a plan; a paused service goes live with "Go Live" on the Settings page |
403 insufficient_scope | The key lacks a permission (the message names it) | Use a key with messages:send (and messages:read for the reports) |
403 sandbox_key | A sandbox key cannot create, change or delete sequences or enrol for real | Use a normal key; with a sandbox key only reads and dry_run enrolments work |
403 not_in_instant_sandbox | The demo number has no sequences | Use a key for your own connected number |
400 invalid_sequence | The sequence or a step is not valid (a missing template_name, a wait over 90 days, more than 20 steps ...) | Fix what the message names; error.details.problems lists every problem |
409 sequence_limit | The number has 100 sequences | Delete the ones you no longer use |
409 sequence_empty | The sequence has no steps | Add steps with PUT /sequences/{id} before you enrol |
400 sequence_no_contacts | Nobody to enrol: no numbers, contacts, segment or tag with contacts in it | Send numbers, contacts, a segment_id or a tag that has contacts |
400 sequence_too_many_contacts | More than 5000 contacts in one call | Send them in smaller groups |
404 sequence_not_found | No such sequence on this number, or it was deleted | GET /sequences lists them |
404 enrolment_not_found | The contact is not in the sequence right now | GET /sequences/{id}/enrolments?status=active lists who is |
enrolled is 0, on_do_not_call_list or already_in_it is not | The contacts opted out, or are already in this sequence | Nothing to fix: a contact is never enrolled twice, and never against an opt-out |
history shows ok: false, or sequence.finished with reason failed or not_allowed | A step could not go out to this contact, for example a template that is not approved, or no opt-in record while the opt-in rule is on | Read the error in history; approve or fix the template, or record the opt-in |
429 rate_limited | Too many calls for this key | Wait Retry-After seconds, then retry |
503 sequences_not_ready | Drip sequences are not available right now | Try again later; if it keeps happening, contact support@app2email.com with the request_id |
Every answer has a request_id. GET /requests/{id} shows what was logged for it, and support@app2email.com can find it too. All codes: Errors.
The MCP server https://api.app2email.com/mcp/sequences has the same calls as tools: list_sequences, get_sequence, create_sequence, update_sequence, delete_sequence, enrol_in_sequence, list_sequence_enrolments and remove_from_sequence. An agent can then answer "how is the welcome series doing?" or "take Jane out of it, she already bought". See Let an AI agent run your WhatsApp with MCP and MCP.
One marketing template to a list or a segment, with consent records and the Do Not Call list.
Create a template, get it approved, and send it when an order ships.
Contacts with names, tags and consent, kept up to date from your own system.
When a customer replies to a step, let your team take the chat.