DEV Community

Cover image for Build a WhatsApp Appointment Booking Flow for Clinics with Interactive List Messages (Node.js)
Wabbiyo
Wabbiyo

Posted on

Build a WhatsApp Appointment Booking Flow for Clinics with Interactive List Messages (Node.js)

Clinics get the same message all day: "Is the doctor available tomorrow?" Then begins a back-and-forth of slot suggestions that ties up the front desk.

WhatsApp interactive list messages fix this. The patient taps a button, picks a slot from a list, and your server books it. In this post we'll build that flow with Node.js, Express and the WhatsApp Cloud API.

How the flow works

  1. Patient messages the clinic ("Hi", "Book appointment")
  2. Server replies with a list message of available slots
  3. Patient picks a slot; the reply arrives at your webhook as list_reply
  4. Server confirms the booking (and later sends a reminder template)

Because the patient messages first, steps 2–4 happen inside the 24-hour customer service window, so free-form interactive messages are allowed.

1. Send a list message

// send.js
const GRAPH = `https://graph.facebook.com/v21.0/${process.env.PHONE_NUMBER_ID}/messages`;

async function sendSlotList(to, slots) {
  const body = {
    messaging_product: 'whatsapp',
    to,
    type: 'interactive',
    interactive: {
      type: 'list',
      header: { type: 'text', text: 'CityCare Clinic' },
      body: { text: 'Pick a time that suits you. All times are IST.' },
      footer: { text: 'Reply STOP to opt out' },
      action: {
        button: 'Choose slot',             // max 20 characters
        sections: [{
          title: 'Dr. Rao – General',      // max 24 characters
          rows: slots.slice(0, 10).map(s => ({
            id: `slot_${s.id}`,             // returned to you on selection
            title: s.label,                 // max 24 characters, e.g. "Tue 10:30 AM"
            description: s.note || ''       // optional, max 72 characters
          }))
        }]
      }
    }
  };

  const res = await fetch(GRAPH, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.WA_TOKEN}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  });
  if (!res.ok) throw new Error(`WhatsApp API ${res.status}: ${await res.text()}`);
  return res.json();
}

async function sendText(to, text) {
  return fetch(GRAPH, {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.WA_TOKEN}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ messaging_product: 'whatsapp', to, type: 'text', text: { body: text } })
  });
}

module.exports = { sendSlotList, sendText };
Enter fullscreen mode Exit fullscreen mode

Limits to remember: up to 10 rows in total across all sections, a button label of 20 characters, and row titles of 24 characters.

2. Handle the webhook

// server.js
const express = require('express');
const crypto = require('crypto');
const { sendSlotList, sendText } = require('./send');

const app = express();
app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }));

// Meta verification handshake
app.get('/webhook', (req, res) => {
  const ok = req.query['hub.mode'] === 'subscribe' &&
             req.query['hub.verify_token'] === process.env.VERIFY_TOKEN;
  return ok ? res.send(req.query['hub.challenge']) : res.sendStatus(403);
});

function validSignature(req) {
  const sig = req.get('X-Hub-Signature-256') || '';
  const expected = 'sha256=' + crypto.createHmac('sha256', process.env.APP_SECRET)
    .update(req.rawBody).digest('hex');
  return sig.length === expected.length &&
         crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
}

app.post('/webhook', async (req, res) => {
  if (!validSignature(req)) return res.sendStatus(401);
  res.sendStatus(200); // reply fast; Meta retries slow webhooks

  const msg = req.body.entry?.[0]?.changes?.[0]?.value?.messages?.[0];
  if (!msg) return; // status updates etc.

  if (msg.type === 'text') {
    const slots = await getFreeSlots();          // from your calendar/DB
    await sendSlotList(msg.from, slots);
  }

  if (msg.type === 'interactive' && msg.interactive.type === 'list_reply') {
    const slotId = msg.interactive.list_reply.id.replace('slot_', '');
    const booked = await bookSlot(slotId, msg.from); // your booking logic
    await sendText(msg.from, booked
      ? `Booked: ${booked.label} with ${booked.doctor}. Reply CANCEL to cancel.`
      : 'Sorry, that slot was just taken. Send "Hi" to see new times.');
  }
});

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

3. Send reminders

Reminders go out a day later, usually outside the 24-hour window, so use an approved utility template (e.g. appointment_reminder) instead of free-form text. Keep the wording neutral: name, date and time, with no diagnosis or treatment details in the message.

Production checklist

  • Lock slots in your DB when you send the list, so two patients can't book the same one
  • Store patient consent (opt-in) for reminders
  • Hand off to a human when the patient types something your flow doesn't understand
  • Log every message for audit

No-code option

If your clinic website runs on WordPress, you don't have to build and host this yourself. Here's how clinics run WhatsApp booking, reminders and a shared reception inbox with a plugin: https://wabbiyo.com/industries/clinics/

Wabbiyo, the self-hosted WhatsApp Business API plugin for WordPress: https://wabbiyo.com/

Top comments (0)