# Messages by SMS or WhatsApp

Source: https://developers.weerom.com/docs/use-cases/messages

> Read tomorrow's bookings once a day and send each customer a reminder by SMS or WhatsApp. Webhooks cover bookings made after the daily run.

**For** a shop whose customers read texts more than mail, and that already has an account with an SMS or WhatsApp provider.

Every evening at 18:00, a job reads tomorrow's confirmed bookings and sends each customer one message with the time and the service. WeerOm already sends a reminder by mail. This adds one on the phone, through a provider the shop chose and pays.

| What | You need |
| --- | --- |
| Key | **Read key** A read key, on a server. |
| Endpoints | `GET /shop` for the time zone and name, `GET /bookings` with `starts_after`, `starts_before` and `status`. |
| Webhook | Optional. An address for **Booking made** and **Booking changed**, for bookings made or moved after the run. See [Webhooks](https://developers.weerom.com/docs/webhooks#add-an-address). |
| Provider | An SMS or WhatsApp provider with an API, and your own code that sends through it. |

## Steps

1. Read the shop for its `time_zone` and `name`.
2. Work out tomorrow's date on the shop's clock.
3. Read the confirmed bookings that start tomorrow.
4. Send one message per booking. Remember which booking ids got one, so a second run sends nothing twice.

## The job

`sendMessage(phone, text)` stands for your own code. Fill it in from your provider's API documentation. This page does not describe any provider's API.

```js title="remind.js"
import { readFile, writeFile } from "node:fs/promises";

const BASE = "https://api.weerom.com/v1";
const SENT_FILE = "./sent.json";

async function weerom(path) {
  const response = await fetch(`${BASE}${path}`, {
    headers: { Authorization: `Bearer ${process.env.WEEROM_KEY}` },
  });
  const json = await response.json();
  if (!response.ok) {
    throw new Error(`${response.status} ${json.error.code}: ${json.error.message}`);
  }
  return json;
}

const addDays = (day, days) => {
  const date = new Date(`${day}T00:00:00Z`);
  date.setUTCDate(date.getUTCDate() + days);
  return date.toISOString().slice(0, 10);
};

const shop = await weerom("/shop");
const dayIn = new Intl.DateTimeFormat("en-CA", { timeZone: shop.time_zone });
const clock = new Intl.DateTimeFormat("nl-BE", {
  hour: "2-digit",
  minute: "2-digit",
  timeZone: shop.time_zone,
});

const tomorrow = addDays(dayIn.format(new Date()), 1);
const sent = new Set(await readFile(SENT_FILE, "utf8").then(JSON.parse, () => []));

// A day wider on both sides, then keep tomorrow on the shop's own clock.
const query = new URLSearchParams({
  limit: "100",
  order: "asc",
  starts_after: `${addDays(tomorrow, -1)}T00:00:00Z`,
  starts_before: `${addDays(tomorrow, 2)}T00:00:00Z`,
  status: "confirmed",
});

let cursor = null;
do {
  if (cursor) query.set("cursor", cursor);
  const page = await weerom(`/bookings?${query}`);

  for (const booking of page.data) {
    const startsAt = new Date(booking.starts_at);
    if (dayIn.format(startsAt) !== tomorrow) continue;
    if (!booking.customer.phone || sent.has(booking.id)) continue;

    const text = `${shop.name}: tot morgen om ${clock.format(startsAt)} voor ${booking.service.name}. Code ${booking.code}.`;
    await sendMessage(booking.customer.phone, text);
    sent.add(booking.id);
    await writeFile(SENT_FILE, JSON.stringify([...sent]));
  }
  cursor = page.has_more ? page.next_cursor : null;
} while (cursor);
```

The message reads "Studio Noord: tot morgen om 10:30 voor Knippen en baard. Code UEAMEFC9." `customer.phone` is in E.164, with the country code: `+32470123456`. The field can be `null`, and the job skips those bookings.

Run it once a day at 18:00:

```txt
0 18 * * * WEEROM_KEY=wo_live_... node remind.js
```

The cron runs on the server's clock. Set the server to the shop's zone, or move the hour.

## Bookings made after the run

A booking made at 20:00 for tomorrow morning misses the 18:00 run. A webhook catches it. Let the shop add your address for **Booking made** and **Booking changed**, and send the reminder at once when a booking lands in tomorrow after the run:

```js title="remind-webhook.js"
// Called from your webhook server once verify() passed. See the Webhooks guide.
export async function onBookingMessage(message) {
  if (message.type !== "booking.created" && message.type !== "booking.updated") return;
  const booking = message.data.object;
  if (booking.status !== "confirmed" || !booking.customer.phone) return;

  const tomorrow = addDays(dayIn.format(new Date()), 1);
  const ranToday = new Date().getHours() >= 18; // on the shop's clock
  if (!ranToday || dayIn.format(new Date(booking.starts_at)) !== tomorrow) return;
  if (await alreadySent(booking.id)) return;

  await sendMessage(booking.customer.phone, reminderText(booking));
  await markSent(booking.id);
}
```

`alreadySent` and `markSent` read and write the same record as the daily job, so a booking never gets two reminders. A booking moved to another time after its reminder went out keeps the old text. Send a second message for that case if the shop wants one.

## How often

Once a day. A day of 40 bookings is 2 requests. The job does not need to poll: tomorrow's list at 18:00 is the list, and the webhook covers what comes after. Without the webhook, a booking made after 18:00 for tomorrow gets the shop's mail reminder only.

## Limits

- **One language in the sketch.** The sketch writes Dutch. Each booking has `locale`, the language its mail goes out in. Pick the text by it.
- **No opt-out in WeerOm.** The API does not say whether a customer wants texts. The shop keeps that record, and the provider's own rules apply. WhatsApp has rules for messages a business starts. We did not check them: read your provider's documentation.
- **No reply into WeerOm.** A customer who answers "cancel" reaches your provider, not the agenda. A write key could cancel with `POST /bookings/{id}/cancel`, but reading the reply is yours to build. The manage link in the shop's confirmation mail already lets the customer cancel.
