A technician on-the-way message is a utility template sent when a field technician starts driving to a booked job, carrying the technician’s name and an ETA. Trigger it when your job record moves to en_route. Offer three quick replies: “Gate code / access info”, “Running late” and “Need to reschedule”. Write every reply into job_notes, and push it to the assigned technician over Telegram or an opted-in WhatsApp number. Give the template a short TTL, because an “on my way” notice is useless an hour later.
The runnable core below is your own jobs table, because you control it whichever dispatch tool you run. A Housecall Pro adapter maps its job.on_my_way webhook onto the same status, with its unverified parts marked. The sibling pattern for parcels is failed delivery notice with reschedule buttons.
The event: a job moves to en_route
Your dispatch app already knows when a technician leaves. Make that one state change the trigger, and keep the phone, the opt-in and the technician’s contact on rows you own:
CREATE TABLE jobs (
id text PRIMARY KEY,
external_id text UNIQUE, -- the job id in Housecall Pro, if you use it
customer_name text NOT NULL,
phone text NOT NULL, -- digits with country code
whatsapp_opt_in boolean NOT NULL DEFAULT false,
time_zone text NOT NULL DEFAULT 'UTC',
scheduled_start timestamptz NOT NULL,
status text NOT NULL DEFAULT 'scheduled', -- scheduled, en_route, in_progress, done, canceled, reschedule_requested
eta timestamptz,
eta_updates int NOT NULL DEFAULT 0,
tech_name text NOT NULL,
tech_telegram_chat_id bigint
);
CREATE TABLE job_notes (
id bigserial PRIMARY KEY,
job_id text NOT NULL REFERENCES jobs(id),
kind text NOT NULL, -- access_info, running_late, reschedule, message
body text NOT NULL,
sensitive boolean NOT NULL DEFAULT false,
source_wamid text UNIQUE, -- the inbound WhatsApp message id, so a retry inserts nothing
created_at timestamptz NOT NULL DEFAULT now()
);
Move scheduled to en_route with a conditional update, and send only when a row changed. A repeated en-route event for the same job then changes nothing, which is your dedupe. The one exception is a new ETA, covered below under When something fails.
Housecall Pro as the source
Housecall Pro’s help center lists job.on_my_way among its webhook events, alongside job.started, job.completed, job.canceled and job.appointment.rescheduled (How to Enable Webhooks, accessed 2026-11-27). You enable them under My Apps > All Apps > Webhooks, enter the URL and pick events. The article adds that “after saving, Housecall Pro returns a signing secret”. It also says “Webhooks is only available on the MAX plan”, and the API overview (accessed 2026-11-27) says the same of the API.
The adapter treats three parts as unknowns, because none could be verified. The signature scheme comes first. The developer docs at docs.housecallpro.com render as a single-page app that returned no readable text. A search snippet of its webhooks page describes Api-Timestamp and Api-Signature headers, with HMAC-SHA256 over the timestamp and the payload. Other sources cite a different header.
The payload shape and the retry policy are not documented in readable form either. The adapter assumes { event, job: { id } } and uses nothing else from the body. No job-note endpoint was verifiable, so the note stays in your job_notes table.
The adapter logs every header on the first delivery, so you can read the real scheme. Enforcement is on by default. Set HCP_ENFORCE_SIGNATURE=0 only in a test window with test jobs.
The message: a utility template with an ETA
A visit the customer booked fits Meta’s utility test. The content must be “non-promotional” and “specific to or requested by the user (clearly related to their order, account, services, or transactions)” (template categorization, accessed 2026-11-27). Meta’s page doesn’t name field technicians, but “services” covers a booked visit. Keep offers out of it: a maintenance-plan upsell in the same message makes it marketing.
No Template Library type fits. DELIVERY_UPDATE is for shipments, so write a custom template. Named parameters keep the technician and the ETA from swapping places. Keep variables away from the very start and end of the body. Meta’s review rejects a template that starts or ends with a parameter, as template rejected reasons explains.
Set message_send_ttl_seconds to a short value. Utility templates default to 30 days, and the field accepts 30 to 43,200 seconds. Meta “drops messages that cannot be delivered within the default or customized TTL” (time-to-live, accessed 2026-11-27). The 1,800 seconds below is our choice. Meta recommends no value.
curl -X POST "https://graph.facebook.com/v26.0/$WABA_ID/message_templates" \
-H "Authorization: Bearer $WA_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "tech_en_route",
"category": "UTILITY",
"language": "en_US",
"parameter_format": "NAMED",
"message_send_ttl_seconds": 1800,
"components": [
{
"type": "BODY",
"text": "Hi {{customer_name}}, {{tech_name}} is on the way to your appointment and should arrive around {{eta}}. Reply below if anything changes.",
"example": {
"body_text_named_params": [
{ "param_name": "customer_name", "example": "Ana" },
{ "param_name": "tech_name", "example": "Marco" },
{ "param_name": "eta", "example": "2:40 PM" }
]
}
},
{
"type": "BUTTONS",
"buttons": [
{ "type": "QUICK_REPLY", "text": "Gate code / access info" },
{ "type": "QUICK_REPLY", "text": "Running late" },
{ "type": "QUICK_REPLY", "text": "Need to reschedule" }
]
}
]
}'
Send it only to customers who opted in to WhatsApp updates when they booked. The opt-in must name your business, as covered in how to collect WhatsApp opt-in.
The reply: taps and typed gate codes
Each quick reply gets a payload at send time, such as access:J-2291. A tap arrives as type: "button" with button.payload, button.text and context.id, the wamid of your template. The full shape and the username caveat are in order confirmation with Confirm and Cancel buttons. Match on context.id first.
The tap opens the 24-hour window, so the service can answer in free text. “Gate code / access info” replies “Please type the gate code or access details here.” The customer’s next message arrives as type: "text" with the code in text.body. It carries no context.id unless they quote your message, so the service matches it by phone to the job that is waiting for access info.
The write-back: a job note and a push to the technician
Every reply becomes a row in job_notes, keyed on the inbound wamid so a Meta retry inserts nothing. Then the technician needs it before they arrive. Housecall Pro documents no call that pushes a message to the technician’s app, so use a channel you control.
Telegram fits an internal alert. The technician starts your bot once, which gives you their private chat_id, and Telegram has no 24-hour window. Linking a chat to a user is covered in Telegram deep linking and, for app accounts, in linking a Telegram chat to your app user. A WhatsApp message to the technician’s own opted-in number also works. Outside a window it needs its own utility template.
Treat gate codes as sensitive. Store them with sensitive = true, send them only to the assigned technician’s private chat, and never echo them into a group or a dispatcher channel. Don’t repeat the code back to the customer either. Delete or redact the note after the job closes, under your own retention policy.
“Need to reschedule” changes the job, so it goes to a person. The service sets reschedule_requested, tells the technician to hold, and hands the job to dispatch. “Running late” only adds a note and a push.
The complete service
This Node 18+ file runs with npm install express. It takes status changes from your app, accepts Housecall Pro’s job.on_my_way, sends the template, verifies Meta’s X-Hub-Signature-256, and writes notes. State lives in memory; map it to the tables above.
// tech-en-route.js. Node 18+. npm install express
const crypto = require("crypto");
const express = require("express");
const {
WA_TOKEN, PHONE_NUMBER_ID, APP_SECRET, VERIFY_TOKEN,
TELEGRAM_BOT_TOKEN, INTERNAL_TOKEN,
HCP_SIGNING_SECRET = "", HCP_ENFORCE_SIGNATURE = "1", PORT = "3000",
} = process.env;
const GRAPH_URL = `https://graph.facebook.com/v26.0/${PHONE_NUMBER_ID}/messages`;
const TG_URL = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`;
const jobs = new Map(); // jobs table: id -> job
const byExternalId = new Map(); // Housecall Pro job id -> job id
const byWamid = new Map(); // template wamid -> job id
const jobNotes = []; // job_notes table
const noteWamids = new Set(); // job_notes.source_wamid UNIQUE
const seenEvents = new Set(); // `${jobId}:${eventType}` from Housecall Pro
const seenMessages = new Set(); // Meta messages[].id
const optOuts = new Set(); // phones and BSUIDs that sent STOP
let hcpHeadersLogged = false;
const safeEqual = (a, b) => {
const x = Buffer.from(a ?? ""), y = Buffer.from(b ?? "");
return x.length === y.length && crypto.timingSafeEqual(x, y);
};
const handOff = (jobId, reason, detail) => console.log("needs_person", { jobId, reason, detail });
function formatEta(iso, timeZone) {
return new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", timeZone }).format(new Date(iso));
}
async function waSend(body) {
const res = await fetch(GRAPH_URL, {
method: "POST",
headers: { Authorization: `Bearer ${WA_TOKEN}`, "Content-Type": "application/json" },
body: JSON.stringify({ messaging_product: "whatsapp", ...body }),
});
const json = await res.json();
if (!res.ok) throw new Error(`Graph ${res.status}: ${JSON.stringify(json.error ?? json)}`);
return json.messages[0].id;
}
const waText = (to, text) => waSend({ to, type: "text", text: { body: text } });
async function pushToTech(job, text) {
if (!job.techTelegramChatId) { handOff(job.id, "tech_not_linked", null); return false; } // never log the text: it may hold a gate code
const res = await fetch(TG_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ chat_id: job.techTelegramChatId, text }),
});
const json = await res.json();
if (!json.ok) handOff(job.id, "tech_push_failed", json.description);
return json.ok === true;
}
function addNote(job, kind, body, sourceWamid, sensitive = false) {
if (sourceWamid && noteWamids.has(sourceWamid)) return false;
if (sourceWamid) noteWamids.add(sourceWamid);
jobNotes.push({ jobId: job.id, kind, body, sensitive, sourceWamid, createdAt: new Date().toISOString() });
return true;
}
const canMessage = (job) => job.whatsappOptIn && !optOuts.has(job.phone) && !(job.userId && optOuts.has(job.userId));
async function sendEnRoute(job) {
const p = (k, v) => ({ type: "text", parameter_name: k, text: String(v) });
const qr = (index, payload) => ({ type: "button", sub_type: "quick_reply", index, parameters: [{ type: "payload", payload }] });
const wamid = await waSend({
to: job.phone, type: "template",
template: {
name: "tech_en_route", language: { code: "en_US" },
components: [
{ type: "body", parameters: [
p("customer_name", job.customerName), p("tech_name", job.techName), p("eta", formatEta(job.eta, job.timeZone)),
] },
qr(0, `access:${job.id}`), qr(1, `late:${job.id}`), qr(2, `resched:${job.id}`),
],
},
});
byWamid.set(wamid, job.id);
}
// UPDATE jobs SET status = 'en_route' ... WHERE id = $1 AND status = 'scheduled'
async function setEnRoute(job, etaIso) {
if (job.status === "en_route") {
if (!etaIso || etaIso === job.eta || job.etaUpdates >= 1) return "ignored"; // at most one ETA update
job.etaUpdates += 1;
} else if (job.status === "scheduled") {
job.status = "en_route";
} else {
return "ignored"; // canceled, done or already being rescheduled
}
job.eta = etaIso ?? job.eta ?? job.scheduledStart;
if (!canMessage(job)) return "no_opt_in";
try {
await sendEnRoute(job);
return "sent";
} catch (err) {
handOff(job.id, "en_route_send_failed", err.message);
return "send_failed";
}
}
function findWaitingJob(msg) {
const id = byWamid.get(msg.context?.id);
if (id) return jobs.get(id);
for (const job of jobs.values()) {
if (job.status === "en_route" && (job.phone === msg.from || (job.userId && job.userId === msg.from_user_id))) return job;
}
return null;
}
async function onWhatsAppMessage(msg) {
if (seenMessages.has(msg.id)) return;
seenMessages.add(msg.id);
const text = msg.type === "text" ? String(msg.text?.body ?? "").trim() : "";
if (/^stop$/i.test(text)) {
[msg.from, msg.from_user_id].filter(Boolean).forEach((v) => optOuts.add(v));
if (msg.from) await waText(msg.from, "Done. You will not get more visit updates here.");
return;
}
const job = findWaitingJob(msg);
if (!job) return handOff(null, "unmatched_message", { id: msg.id, type: msg.type });
if (msg.from_user_id) job.userId = msg.from_user_id;
if (msg.type === "button") {
const [verb] = String(msg.button?.payload ?? "").split(":");
const label = String(msg.button?.text ?? "").toLowerCase();
const action = ["access", "late", "resched"].includes(verb) ? verb
: label.startsWith("gate") ? "access" : label.startsWith("running") ? "late"
: label.includes("reschedule") ? "resched" : "";
if (action === "access") {
job.awaitingAccessInfo = true;
return waText(job.phone, "Please type the gate code or access details here. Only your technician will see them.");
}
if (action === "late") {
if (!addNote(job, "running_late", "Customer is running late", msg.id)) return;
await pushToTech(job, `Job ${job.id}: the customer says they are running late.`);
return waText(job.phone, `Thanks. We told ${job.techName}.`);
}
if (action === "resched") {
if (!addNote(job, "reschedule", "Customer asked to reschedule", msg.id)) return;
if (job.status === "en_route") job.status = "reschedule_requested";
await pushToTech(job, `Job ${job.id}: the customer asked to reschedule. Hold until dispatch confirms.`);
handOff(job.id, "reschedule_requested", null);
return waText(job.phone, "Thanks. Our team will message you here with new times.");
}
return handOff(job.id, "unreadable_button", msg.button);
}
if (msg.type !== "text") return handOff(job.id, "unsupported_type", msg.type);
if (job.awaitingAccessInfo) {
job.awaitingAccessInfo = false;
if (!addNote(job, "access_info", text, msg.id, true)) return;
const delivered = await pushToTech(job, `Job ${job.id} access info from the customer: ${text}`); // private chat only
return waText(job.phone, delivered ? `Thanks. ${job.techName} has it.` : "Thanks. We saved it for your technician.");
}
if (!addNote(job, "message", text, msg.id)) return;
await pushToTech(job, `Job ${job.id}, customer message: ${text}`);
}
// TODO:test: Housecall Pro signature scheme. A search snippet of its docs describes Api-Timestamp and
// Api-Signature, HMAC-SHA256 over the timestamp and the payload. The joining format and the hex encoding are guesses.
function verifyHcp(req) {
const ts = req.get("api-timestamp"), given = req.get("api-signature");
if (!HCP_SIGNING_SECRET || !ts || !given) return false;
return [Buffer.from(`${ts}.`), Buffer.from(ts)].some((prefix) => {
const hex = crypto.createHmac("sha256", HCP_SIGNING_SECRET).update(Buffer.concat([prefix, req.body])).digest("hex");
return safeEqual(hex, given);
});
}
const app = express();
const internal = (req, res, next) =>
safeEqual(req.get("authorization"), `Bearer ${INTERNAL_TOKEN}`) ? next() : res.sendStatus(401);
// Your app upserts jobs here, or you read them from the jobs table directly.
app.post("/internal/jobs", express.json(), internal, (req, res) => {
const j = req.body ?? {};
if (!j.id || !j.phone || !j.scheduledStart || !j.techName) return res.sendStatus(400);
const job = Object.assign(jobs.get(j.id) ?? { status: "scheduled", etaUpdates: 0, eta: null }, {
id: j.id, externalId: j.externalId ?? null, customerName: j.customerName ?? "there",
phone: String(j.phone).replace(/\D/g, ""), whatsappOptIn: j.whatsappOptIn === true,
timeZone: j.timeZone ?? "UTC", scheduledStart: j.scheduledStart,
techName: j.techName, techTelegramChatId: j.techTelegramChatId ?? null,
});
jobs.set(job.id, job);
if (job.externalId) byExternalId.set(String(job.externalId), job.id);
res.sendStatus(204);
});
// Your dispatch app posts { status: "en_route", eta: ISO string } when the technician leaves.
app.post("/internal/jobs/:id/status", express.json(), internal, async (req, res) => {
const job = jobs.get(req.params.id);
if (!job) return res.sendStatus(404);
const { status, eta } = req.body ?? {};
if (status === "en_route") return res.json({ result: await setEnRoute(job, eta) });
if (["in_progress", "done", "canceled"].includes(status)) {
job.status = status;
job.awaitingAccessInfo = false;
return res.json({ result: "updated" });
}
res.sendStatus(400);
});
app.post("/hcp/webhook", express.raw({ type: "*/*" }), async (req, res) => {
if (!hcpHeadersLogged) {
hcpHeadersLogged = true;
console.log("hcp_first_delivery_headers", req.headers); // read the real signature scheme here
}
const verified = verifyHcp(req);
if (!verified && HCP_ENFORCE_SIGNATURE === "1") return res.sendStatus(401);
if (!verified) console.warn("hcp_signature_unverified");
res.sendStatus(200);
let body;
try { body = JSON.parse(req.body.toString("utf8")); } catch { return; }
// TODO:test: payload shape. Assumed { event, job: { id } }. Only the id is used.
const jobId = byExternalId.get(String(body.job?.id ?? ""));
const job = jobId && jobs.get(jobId);
if (!job || !body.event) return;
const key = `${job.id}:${body.event}`;
if (seenEvents.has(key)) return;
seenEvents.add(key);
if (body.event === "job.on_my_way") return void (await setEnRoute(job, null));
if (body.event === "job.started") job.status = "in_progress";
if (body.event === "job.canceled") job.status = "canceled";
if (body.event === "job.started" || body.event === "job.canceled") job.awaitingAccessInfo = false;
});
app.get("/whatsapp/webhook", (req, res) => {
const ok = req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === VERIFY_TOKEN;
return ok ? res.send(req.query["hub.challenge"]) : res.sendStatus(403);
});
app.post("/whatsapp/webhook", express.raw({ type: "application/json" }), (req, res) => {
const expected = "sha256=" + crypto.createHmac("sha256", APP_SECRET).update(req.body).digest("hex");
if (!safeEqual(expected, req.get("x-hub-signature-256"))) return res.sendStatus(401);
res.sendStatus(200);
const body = JSON.parse(req.body.toString("utf8"));
for (const entry of body.entry ?? []) {
for (const change of entry.changes ?? []) {
for (const msg of change.value?.messages ?? []) {
onWhatsAppMessage(msg).catch((err) => handOff(null, "reply_failed", err.message));
}
}
}
});
app.listen(Number(PORT), () => console.log(`listening on ${PORT}`));
For Housecall Pro jobs, the ETA falls back to scheduled_start, because the event’s ETA fields are unknown. When Housecall Pro’s note endpoint is confirmed in its docs, add the write-back after addNote. Until then, the notes live in your table, and dispatch copies anything that matters. A rebooked visit needs a new job id or a reset to scheduled. A code typed without the tap is stored as a plain message, so mark it sensitive in review.
When something fails
If the customer never replies, nothing changes. The technician arrives, and job.started clears the access-info wait. If the phone stays off for 30 minutes, the TTL drops the message, so a stale notice never arrives.
If the technician is delayed, recompute the ETA and send the same template once more. The service allows one update per job and ignores the rest. No separate “still coming” template is needed.
The conditional move from scheduled to en_route, the job id plus event type key for Housecall Pro, and the unique source_wamid on notes absorb duplicates. A STOP reply adds the phone and from_user_id to an opt-out list that every send checks.
A failed Graph call goes to a person instead of a retry loop, because a late “on my way” helps nobody. A failed Telegram push also goes to a person, since the technician may be walking up to a locked gate. Housecall Pro’s retry policy is undocumented in readable form, so watch the first deliveries for repeats.
Where Z-API Omni fits
On Meta’s official API, Omni sends tech_en_route through POST https://api.omni.z-api.io/v1/channels/{channelId}/messages with a Bearer Secret Key, and template creation accepts message_send_ttl_seconds. Free-text replies, such as a typed gate code, arrive as MESSAGE_RECEIVED with contents[0].type: "TEXT". The docs don’t show the inbound shape of a quick-reply tap yet. No field-service integration is documented, so the service above stays the bridge.
The technician ping can run on a Telegram channel in the same subscription, which also covers WhatsApp, Messenger and Instagram. Pricing is US$29 per number per month for 1 to 10 numbers, falling in steps to US$20 above 100. Webhooks are included without limit, and Meta’s fees pass through on the official connection.
curl -X POST "https://api.omni.z-api.io/v1/channels/$CHANNEL_ID/messages" \
-H "Authorization: Bearer $OMNI_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"recipient":{"identifier":"5511999999999"},"content":{"type":"TEMPLATE","attachments":[{"template":{"name":"tech_en_route","language":{"policy":"deterministic","code":"en_US"},"components":[{"type":"body","parameters":[{"type":"text","text":"Ana"},{"type":"text","text":"Marco"},{"type":"text","text":"2:40 PM"}]}]}}]}}'
Z-API Omni team