Appointment reminders

Schedule appointment reminders, cancel them, and handle replies.

Appointment reminders are one of the most common uses of SMS, for clinics, salons, service calls, and anything else with a calendar.

This guide builds a complete reminder flow on three API calls and one webhook.

When to use this guide

Use it when…Use something else when…
You text people about something on a calendar: appointments, bookings, service visits.You want a complete, runnable service rather than the individual steps → End-to-end example
You want replies (confirm or reschedule) tied back to the booking.You're sending the same message to many people at once → Campaigns to a group

What you'll build

  1. When an appointment is booked, schedule a reminder for 24 hours before it.
  2. If the appointment is cancelled or moved, cancel the scheduled reminder (and schedule a new one).
  3. When the customer replies C or R, confirm or flag the appointment for rescheduling.

Prerequisites: an EZ Texting account, credentials in EZTEXTING_USERNAME / EZTEXTING_PASSWORD, and the Quickstart under your belt.


Design decisions first

DecisionRecommendation
Who schedules?Let EZ Texting hold the schedule. Send with sendAt at booking time instead of running your own cron job. Fewer moving parts; nothing to send if your server is down at 9am.
Which number format?Normalize to 11 digits when the appointment is created, not when the reminder fires. → Phone number formatting
When to send?24 hours before is the default. Respect quiet hours: if that lands before 8am or after 9pm in the customer's time zone, pull it earlier to the previous evening.
What to store?The EZ Texting message id alongside the appointment. It's the handle for cancelling.
Consent?Booking an appointment is not consent to be texted about it. Collect it at booking ("Text me reminders about this appointment"), store when and how, and refuse to schedule a text without it. → Compliance

Step 1: Schedule the reminder at booking time

Compute the send time, format it as ISO 8601 with the customer's UTC offset, and send with sendAt. Keep strictValidation on (it's the default; the samples set it explicitly) so a bad number fails now, when you can still ask for a correct one, rather than silently never sending.

curl -X POST https://a.eztexting.com/v1/messages \
  -u "$EZTEXTING_USERNAME:$EZTEXTING_PASSWORD" \
  -H "Content-Type: application/json" \
  -d '{
    "toNumbers": ["15551234567"],
    "companyName": "Harbor Dental",
    "message": "Reminder: your cleaning with Dr. Lee is tomorrow, Nov 19 at 9:00 AM. Reply C to confirm or R to reschedule. Reply STOP to opt out.",
    "sendAt": "2027-11-18T09:00:00-08:00",
    "strictValidation": true
  }'
import os
from datetime import timedelta
import requests

auth = (os.environ["EZTEXTING_USERNAME"], os.environ["EZTEXTING_PASSWORD"])

def schedule_reminder(appointment):
    # appointment.starts_at is a timezone-aware datetime in the customer's zone
    send_at = appointment.starts_at - timedelta(hours=24)

    resp = requests.post(
        "https://a.eztexting.com/v1/messages",
        auth=auth,
        json={
            # "15551234567"
            "toNumbers": [appointment.phone],
            "companyName": "Harbor Dental",
            "message": (
                f"Reminder: your {appointment.service} with {appointment.provider} is "
                f"tomorrow, {appointment.starts_at:%b %-d at %-I:%M %p}. "
                "Reply C to confirm or R to reschedule. Reply STOP to opt out."
            ),
            # "2026-11-20T09:00:00-08:00"
            "sendAt": send_at.isoformat(),
            "strictValidation": True,
        },
        timeout=30,
    )
    resp.raise_for_status()
    # store this
    appointment.reminder_message_id = resp.json()["id"]
    appointment.save()
const credentials = Buffer.from(
  `${process.env.EZTEXTING_USERNAME}:${process.env.EZTEXTING_PASSWORD}`
).toString("base64");

async function scheduleReminder(appointment) {
  // appointment.startsAt is a Date; appointment.offset is e.g. "-08:00"
  const sendAt = new Date(appointment.startsAt.getTime() - 24 * 60 * 60 * 1000);

  const res = await fetch("https://a.eztexting.com/v1/messages", {
    method: "POST",
    headers: { Authorization: `Basic ${credentials}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      // "15551234567"
      toNumbers: [appointment.phone],
      companyName: "Harbor Dental",
      message:
        `Reminder: your ${appointment.service} with ${appointment.provider} is tomorrow, ` +
        `${appointment.displayTime}. Reply C to confirm or R to reschedule. Reply STOP to opt out.`,
      // "2026-11-20T09:00:00-08:00"
      sendAt: toIsoWithOffset(sendAt, appointment.offset),
      strictValidation: true,
    }),
  });
  if (!res.ok) throw new Error(`EZ Texting ${res.status}: ${await res.text()}`);

  const { id } = await res.json();
  // store this
  await appointment.update({ reminderMessageId: id });
}
<?php
function scheduleReminder(array $appt): string {
    // DateTimeImmutable in customer's zone
    $sendAt = (clone $appt['startsAt'])->modify('-24 hours');

    $ch = curl_init("https://a.eztexting.com/v1/messages");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERPWD => getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"),
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        CURLOPT_POSTFIELDS => json_encode([
            "toNumbers" => [$appt['phone']],
            "companyName" => "Harbor Dental",
            "message" => "Reminder: your {$appt['service']} with {$appt['provider']} is tomorrow, "
                       . $appt['startsAt']->format('M j \a\t g:i A')
                       . ". Reply C to confirm or R to reschedule. Reply STOP to opt out.",
            // "2026-11-20T09:00:00-08:00"
            "sendAt" => $sendAt->format(DATE_ATOM),
            "strictValidation" => true,
        ]),
    ]);
    $body = json_decode(curl_exec($ch), true);
    curl_close($ch);
    // store this
    return $body['id'];
}
require "net/http"
require "json"

def schedule_reminder(appt)
  # Time with customer's offset
  send_at = appt.starts_at - 24 * 60 * 60

  uri = URI("https://a.eztexting.com/v1/messages")
  req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
  req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
  req.body = {
    toNumbers: [appt.phone],
    companyName: "Harbor Dental",
    message: "Reminder: your #{appt.service} with #{appt.provider} is tomorrow, " \
             "#{appt.starts_at.strftime('%b %-d at %-l:%M %p')}. " \
             "Reply C to confirm or R to reschedule. Reply STOP to opt out.",
    # "2026-11-20T09:00:00-08:00"
    sendAt: send_at.iso8601,
    strictValidation: true
  }.to_json

  res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }
  raise "EZ Texting #{res.code}: #{res.body}" unless res.code == "201"
  # store this
  JSON.parse(res.body)["id"]
end
String scheduleReminder(Appointment appt) throws Exception {
    // customer's offset preserved
    OffsetDateTime sendAt = appt.startsAt().minusHours(24);

    String message = "Reminder: your %s with %s is tomorrow, %s. Reply C to confirm or R to reschedule. Reply STOP to opt out."
        .formatted(appt.service(), appt.provider(),
                   appt.startsAt().format(DateTimeFormatter.ofPattern("MMM d 'at' h:mm a")));

    String json = mapper.writeValueAsString(Map.of(
        "toNumbers", List.of(appt.phone()),
        "companyName", "Harbor Dental",
        "message", message,
        "sendAt", sendAt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME),
        "strictValidation", true));

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://a.eztexting.com/v1/messages"))
        .header("Authorization", "Basic " + basicAuth)
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(json))
        .build();

    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    if (response.statusCode() != 201) throw new RuntimeException("EZ Texting " + response.statusCode());
    // store this
    return mapper.readTree(response.body()).get("id").asText();
}
async Task<string> ScheduleReminderAsync(Appointment appt)
{
    // DateTimeOffset in customer's zone
    var sendAt = appt.StartsAt.AddHours(-24);

    var payload = new
    {
        toNumbers = new[] { appt.Phone },
        companyName = "Harbor Dental",
        message = $"Reminder: your {appt.Service} with {appt.Provider} is tomorrow, " +
                  $"{appt.StartsAt:MMM d 'at' h:mm tt}. Reply C to confirm or R to reschedule. Reply STOP to opt out.",
        // "2026-11-20T09:00:00-08:00"
        sendAt = sendAt.ToString("yyyy-MM-dd'T'HH:mm:sszzz"),
        strictValidation = true
    };

    var res = await client.PostAsJsonAsync("https://a.eztexting.com/v1/messages", payload);
    res.EnsureSuccessStatusCode();
    var body = await res.Content.ReadFromJsonAsync<JsonElement>();
    // store this
    return body.GetProperty("id").GetString()!;
}
func scheduleReminder(appt Appointment) (string, error) {
	// time.Time in the customer's location
	sendAt := appt.StartsAt.Add(-24 * time.Hour)

	payload := map[string]any{
		"toNumbers":   []string{appt.Phone},
		"companyName": "Harbor Dental",
		"message": fmt.Sprintf("Reminder: your %s with %s is tomorrow, %s. Reply C to confirm or R to reschedule. Reply STOP to opt out.",
			appt.Service, appt.Provider, appt.StartsAt.Format("Jan 2 at 3:04 PM")),
		// "2026-11-20T09:00:00-08:00"
		"sendAt":           sendAt.Format(time.RFC3339),
		"strictValidation": true,
	}
	body, _ := json.Marshal(payload)

	req, _ := http.NewRequest("POST", "https://a.eztexting.com/v1/messages", bytes.NewReader(body))
	req.SetBasicAuth(os.Getenv("EZTEXTING_USERNAME"), os.Getenv("EZTEXTING_PASSWORD"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 201 {
		return "", fmt.Errorf("EZ Texting %d", resp.StatusCode)
	}
	var out struct{ ID string `json:"id"` }
	json.NewDecoder(resp.Body).Decode(&out)
	// store this
	return out.ID, nil
}
{
  "id": "128451077003"
}

The reminder now lives in EZ Texting's queue. You can see it (and every other pending send) with GET /v1/campaign-info.

sendAt must be in the future and must carry an offset

2026-11-20T09:00:00 with no offset is ambiguous and may be interpreted as UTC, which for a West Coast customer means 1am. Always emit -08:00, Z, or similar. A sendAt in the past is rejected with a 400.


Step 2: Cancel or reschedule

When an appointment is cancelled or moved, delete the pending reminder by ID. Then, if it was moved, schedule a fresh one with Step 1.

curl -X DELETE https://a.eztexting.com/v1/messages \
  -u "$EZTEXTING_USERNAME:$EZTEXTING_PASSWORD" \
  -H "Content-Type: application/json" \
  -d '{"ids": ["128451077003"]}'
def cancel_reminder(appointment):
    if not appointment.reminder_message_id:
        return
    requests.delete(
        "https://a.eztexting.com/v1/messages",
        auth=auth,
        json={"ids": [appointment.reminder_message_id]},
        timeout=30,
    ).raise_for_status()
    appointment.reminder_message_id = None
    appointment.save()

def reschedule(appointment, new_starts_at):
    cancel_reminder(appointment)
    appointment.starts_at = new_starts_at
    schedule_reminder(appointment)
async function cancelReminder(appointment) {
  if (!appointment.reminderMessageId) return;
  const res = await fetch("https://a.eztexting.com/v1/messages", {
    method: "DELETE",
    headers: { Authorization: `Basic ${credentials}`, "Content-Type": "application/json" },
    body: JSON.stringify({ ids: [appointment.reminderMessageId] }),
  });
  if (!res.ok) throw new Error(`EZ Texting ${res.status}`);
  await appointment.update({ reminderMessageId: null });
}

async function reschedule(appointment, newStartsAt) {
  await cancelReminder(appointment);
  appointment.startsAt = newStartsAt;
  await scheduleReminder(appointment);
}
<?php
function cancelReminder(array &$appt): void {
    if (empty($appt['reminderMessageId'])) return;
    $ch = curl_init("https://a.eztexting.com/v1/messages");
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => "DELETE",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERPWD => getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"),
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        CURLOPT_POSTFIELDS => json_encode(["ids" => [$appt['reminderMessageId']]]),
    ]);
    curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($status >= 300) throw new RuntimeException("EZ Texting $status");
    // and save
    $appt['reminderMessageId'] = null;
}

function reschedule(array &$appt, DateTimeImmutable $newStartsAt): void {
    cancelReminder($appt);
    $appt['startsAt'] = $newStartsAt;
    // and save
    $appt['reminderMessageId'] = scheduleReminder($appt);
}
def cancel_reminder(appt)
  return unless appt.reminder_message_id
  uri = URI("https://a.eztexting.com/v1/messages")
  req = Net::HTTP::Delete.new(uri, "Content-Type" => "application/json")
  req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
  req.body = { ids: [appt.reminder_message_id] }.to_json
  # raises unless 2xx
  Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }.value
  appt.update!(reminder_message_id: nil)
end

def reschedule(appt, new_starts_at)
  cancel_reminder(appt)
  appt.starts_at = new_starts_at
  appt.update!(reminder_message_id: schedule_reminder(appt))
end
void cancelReminder(Appointment appt) throws Exception {
    if (appt.reminderMessageId() == null) return;
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://a.eztexting.com/v1/messages"))
        .header("Authorization", "Basic " + basicAuth)
        .header("Content-Type", "application/json")
        .method("DELETE", HttpRequest.BodyPublishers.ofString(
            mapper.writeValueAsString(Map.of("ids", List.of(appt.reminderMessageId())))))
        .build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    if (response.statusCode() >= 300) throw new RuntimeException("EZ Texting " + response.statusCode());
    appointments.saveReminderId(appt.id(), null);
}

void reschedule(Appointment appt, OffsetDateTime newStartsAt) throws Exception {
    cancelReminder(appt);
    Appointment moved = appointments.move(appt.id(), newStartsAt);
    appointments.saveReminderId(moved.id(), scheduleReminder(moved));
}
async Task CancelReminderAsync(Appointment appt)
{
    if (appt.ReminderMessageId is null) return;
    var req = new HttpRequestMessage(HttpMethod.Delete, "https://a.eztexting.com/v1/messages")
    {
        Content = JsonContent.Create(new { ids = new[] { appt.ReminderMessageId } })
    };
    (await client.SendAsync(req)).EnsureSuccessStatusCode();
    appt.ReminderMessageId = null;
    await db.SaveChangesAsync();
}

async Task RescheduleAsync(Appointment appt, DateTimeOffset newStartsAt)
{
    await CancelReminderAsync(appt);
    appt.StartsAt = newStartsAt;
    appt.ReminderMessageId = await ScheduleReminderAsync(appt);
    await db.SaveChangesAsync();
}
func cancelReminder(appt *Appointment) error {
	if appt.ReminderMessageID == "" {
		return nil
	}
	body, _ := json.Marshal(map[string][]string{"ids": {appt.ReminderMessageID}})
	req, _ := http.NewRequest("DELETE", "https://a.eztexting.com/v1/messages", bytes.NewReader(body))
	req.SetBasicAuth(os.Getenv("EZTEXTING_USERNAME"), os.Getenv("EZTEXTING_PASSWORD"))
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	resp.Body.Close()
	if resp.StatusCode >= 300 {
		return fmt.Errorf("EZ Texting %d", resp.StatusCode)
	}
	appt.ReminderMessageID = ""
	return appt.Save()
}

func reschedule(appt *Appointment, newStartsAt time.Time) error {
	if err := cancelReminder(appt); err != nil {
		return err
	}
	appt.StartsAt = newStartsAt
	id, err := scheduleReminder(*appt)
	if err != nil {
		return err
	}
	appt.ReminderMessageID = id
	return appt.Save()
}

Deleting a message that has already gone out doesn't un-send it, so cancel as soon as you know, and treat a reschedule inside the 24-hour window as "send a correction" rather than "cancel the reminder".


Step 3: Handle the reply

Subscribe to inbound_text.received once (see Webhooks for signature verification and the full payload), then route replies by their first word.

import os, hmac, hashlib, base64
from flask import Flask, request, abort

app = Flask(__name__)
WEBHOOK_SECRET = os.environ["EZTEXTING_WEBHOOK_SECRET"]

@app.post("/webhooks/eztexting")
def inbound():
    expected = base64.b64encode(
        hmac.new(WEBHOOK_SECRET.encode(), request.get_data(), hashlib.sha256).digest()
    ).decode()
    if not hmac.compare_digest(expected, request.headers.get("X-Signature-256", "")):
        abort(401)

    event = request.get_json()
    if event["type"] != "inbound_text.received":
        return "", 204

    phone = event["fromNumber"]
    # the whole reply, so "Can I come later?" isn't read as C
    word = event["message"].strip().upper()
    # your lookup: by the reminder's message ID first, then by phone
    appt = Appointment.for_reply(event.get("id"), phone)

    if appt and word == "C":
        appt.confirm()
        send(phone, f"Thanks! You're confirmed for {appt.starts_at:%b %-d at %-I:%M %p}.")
    elif appt and word == "R":
        appt.flag_for_reschedule()
        send(phone, "No problem — we'll call you shortly to find a new time.")
    # Anything else (including STOP) needs no action: EZ Texting handles opt-outs.

    return "", 204

def send(phone, text):
    requests.post(
        "https://a.eztexting.com/v1/messages",
        auth=auth,
        json={"toNumbers": [phone], "companyName": "Harbor Dental", "message": text},
        timeout=30,
    )
import express from "express";
import crypto from "node:crypto";

const app = express();
const SECRET = process.env.EZTEXTING_WEBHOOK_SECRET;

app.post("/webhooks/eztexting", express.raw({ type: "application/json" }), async (req, res) => {
  const expected = crypto.createHmac("sha256", SECRET).update(req.body).digest("base64");
  const given = req.get("X-Signature-256") || "";
  if (expected.length !== given.length || !crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(given))) {
    return res.sendStatus(401);
  }

  const event = JSON.parse(req.body);
  if (event.type !== "inbound_text.received") return res.sendStatus(204);

  const phone = event.fromNumber;
  // the whole reply, so "Can I come later?" isn't read as C
  const word = event.message.trim().toUpperCase();
  // your lookup: by the reminder's message ID first, then by phone
  const appt = await Appointment.forReply(event.id, phone);

  if (appt && word === "C") {
    await appt.confirm();
    await send(phone, `Thanks! You're confirmed for ${appt.displayTime}.`);
  } else if (appt && word === "R") {
    await appt.flagForReschedule();
    await send(phone, "No problem — we'll call you shortly to find a new time.");
  }
  // Anything else (including STOP) needs no action: EZ Texting handles opt-outs.

  res.sendStatus(204);
});

async function send(phone, text) {
  await fetch("https://a.eztexting.com/v1/messages", {
    method: "POST",
    headers: { Authorization: `Basic ${credentials}`, "Content-Type": "application/json" },
    body: JSON.stringify({ toNumbers: [phone], companyName: "Harbor Dental", message: text }),
  });
}
<?php
$secret = getenv("EZTEXTING_WEBHOOK_SECRET");
$rawBody = file_get_contents("php://input");
$expected = base64_encode(hash_hmac("sha256", $rawBody, $secret, true));
if (!hash_equals($expected, $_SERVER["HTTP_X_SIGNATURE_256"] ?? "")) {
    http_response_code(401);
    exit;
}

$event = json_decode($rawBody, true);
if ($event['type'] === 'inbound_text.received') {
    $phone = $event['fromNumber'];
    // the whole reply, so "Can I come later?" isn't read as C
    $word = strtoupper(trim($event['message']));
    // your lookup: by the reminder's message ID first, then by phone
    $appt = Appointment::forReply($event['id'] ?? null, $phone);

    if ($appt && $word === 'C') {
        $appt->confirm();
        send($phone, "Thanks! You're confirmed for " . $appt->startsAt->format('M j \a\t g:i A') . ".");
    } elseif ($appt && $word === 'R') {
        $appt->flagForReschedule();
        send($phone, "No problem — we'll call you shortly to find a new time.");
    }
    // Anything else (including STOP) needs no action: EZ Texting handles opt-outs.
}
http_response_code(204);

function send(string $phone, string $text): void {
    $ch = curl_init("https://a.eztexting.com/v1/messages");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERPWD => getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"),
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        CURLOPT_POSTFIELDS => json_encode(["toNumbers" => [$phone], "companyName" => "Harbor Dental", "message" => $text]),
    ]);
    curl_exec($ch);
    curl_close($ch);
}
class EzTextingWebhooksController < ApplicationController
  skip_before_action :verify_authenticity_token

  def create
    raw = request.raw_post
    expected = Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", ENV.fetch("EZTEXTING_WEBHOOK_SECRET"), raw))
    given = request.headers["X-Signature-256"].to_s
    return head :unauthorized unless ActiveSupport::SecurityUtils.secure_compare(expected, given)

    event = JSON.parse(raw)
    return head :no_content unless event["type"] == "inbound_text.received"

    phone = event["fromNumber"]
    # the whole reply, so "Can I come later?" isn't read as C
    word = event["message"].strip.upcase
    # your lookup: by the reminder's message ID first, then by phone
    appt = Appointment.for_reply(event["id"], phone)

    if appt && word == "C"
      appt.confirm!
      send_text(phone, "Thanks! You're confirmed for #{appt.starts_at.strftime('%b %-d at %-l:%M %p')}.")
    elsif appt && word == "R"
      appt.flag_for_reschedule!
      send_text(phone, "No problem — we'll call you shortly to find a new time.")
    end
    # Anything else (including STOP) needs no action: EZ Texting handles opt-outs.

    head :no_content
  end

  private

  def send_text(phone, text)
    uri = URI("https://a.eztexting.com/v1/messages")
    req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
    req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
    req.body = { toNumbers: [phone], companyName: "Harbor Dental", message: text }.to_json
    Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }
  end
end
@PostMapping("/webhooks/eztexting")
public ResponseEntity<Void> inbound(@RequestBody byte[] rawBody,
                                    @RequestHeader(value = "X-Signature-256", required = false) String given) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(System.getenv("EZTEXTING_WEBHOOK_SECRET").getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    String expected = Base64.getEncoder().encodeToString(mac.doFinal(rawBody));
    if (given == null || !MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), given.getBytes(StandardCharsets.UTF_8))) {
        return ResponseEntity.status(401).build();
    }

    JsonNode event = mapper.readTree(rawBody);
    if (!"inbound_text.received".equals(event.path("type").asText())) return ResponseEntity.noContent().build();

    String phone = event.get("fromNumber").asText();
    // the whole reply, so "Can I come later?" isn't read as C
    String word = event.get("message").asText().trim().toUpperCase();
    // your lookup: by the reminder's message ID first, then by phone
    Appointment appt = appointments.forReply(event.path("id").asText(null), phone);

    if (appt != null && word.equals("C")) {
        appointments.confirm(appt.id());
        send(phone, "Thanks! You're confirmed for "
            + appt.startsAt().format(DateTimeFormatter.ofPattern("MMM d 'at' h:mm a")) + ".");
    } else if (appt != null && word.equals("R")) {
        appointments.flagForReschedule(appt.id());
        send(phone, "No problem — we'll call you shortly to find a new time.");
    }
    // Anything else (including STOP) needs no action: EZ Texting handles opt-outs.

    return ResponseEntity.noContent().build();
}

void send(String phone, String text) throws Exception {
    String json = mapper.writeValueAsString(
        Map.of("toNumbers", List.of(phone), "companyName", "Harbor Dental", "message", text));
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://a.eztexting.com/v1/messages"))
        .header("Authorization", "Basic " + basicAuth)
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(json))
        .build();
    client.send(request, HttpResponse.BodyHandlers.ofString());
}
app.MapPost("/webhooks/eztexting", async (HttpRequest req, AppointmentStore appointments) =>
{
    using var ms = new MemoryStream();
    await req.Body.CopyToAsync(ms);
    var rawBody = ms.ToArray();

    var key = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("EZTEXTING_WEBHOOK_SECRET")!);
    var expected = Convert.ToBase64String(HMACSHA256.HashData(key, rawBody));
    var given = req.Headers["X-Signature-256"].ToString();
    if (!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(given)))
        return Results.Unauthorized();

    var evt = JsonDocument.Parse(rawBody).RootElement;
    if (evt.GetProperty("type").GetString() != "inbound_text.received") return Results.NoContent();

    var phone = evt.GetProperty("fromNumber").GetString()!;
    // the whole reply, so "Can I come later?" isn't read as C
    var word = evt.GetProperty("message").GetString()!.Trim().ToUpperInvariant();
    // your lookup: by the reminder's message ID first, then by phone
    var replyTo = evt.TryGetProperty("id", out var rid) ? rid.GetString() : null;
    var appt = await appointments.ForReplyAsync(replyTo, phone);

    if (appt is not null && word == "C")
    {
        await appointments.ConfirmAsync(appt);
        await SendAsync(phone, $"Thanks! You're confirmed for {appt.StartsAt:MMM d 'at' h:mm tt}.");
    }
    else if (appt is not null && word == "R")
    {
        await appointments.FlagForRescheduleAsync(appt);
        await SendAsync(phone, "No problem — we'll call you shortly to find a new time.");
    }
    // Anything else (including STOP) needs no action: EZ Texting handles opt-outs.

    return Results.NoContent();
});

async Task SendAsync(string phone, string text) =>
    await client.PostAsJsonAsync("https://a.eztexting.com/v1/messages",
        new { toNumbers = new[] { phone }, companyName = "Harbor Dental", message = text });
func inbound(w http.ResponseWriter, r *http.Request) {
	rawBody, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	mac := hmac.New(sha256.New, []byte(os.Getenv("EZTEXTING_WEBHOOK_SECRET")))
	mac.Write(rawBody)
	expected := base64.StdEncoding.EncodeToString(mac.Sum(nil))
	if !hmac.Equal([]byte(expected), []byte(r.Header.Get("X-Signature-256"))) {
		http.Error(w, "invalid signature", http.StatusUnauthorized)
		return
	}

	var event struct {
		ID         string `json:"id"`
		Type       string `json:"type"`
		FromNumber string `json:"fromNumber"`
		Message    string `json:"message"`
	}
	json.Unmarshal(rawBody, &event)
	if event.Type == "inbound_text.received" {
		// the whole reply, so "Can I come later?" isn't read as C
		word := strings.ToUpper(strings.TrimSpace(event.Message))
		// your lookup: by the reminder's message ID first, then by phone
		appt, found := appointmentForReply(event.ID, event.FromNumber)

		switch {
		case found && word == "C":
			appt.Confirm()
			send(event.FromNumber, "Thanks! You're confirmed for "+appt.StartsAt.Format("Jan 2 at 3:04 PM")+".")
		case found && word == "R":
			appt.FlagForReschedule()
			send(event.FromNumber, "No problem — we'll call you shortly to find a new time.")
		}
		// Anything else (including STOP) needs no action: EZ Texting handles opt-outs.
	}
	w.WriteHeader(http.StatusNoContent)
}

func send(phone, text string) {
	body, _ := json.Marshal(map[string]any{"toNumbers": []string{phone}, "companyName": "Harbor Dental", "message": text})
	req, _ := http.NewRequest("POST", "https://a.eztexting.com/v1/messages", bytes.NewReader(body))
	req.SetBasicAuth(os.Getenv("EZTEXTING_USERNAME"), os.Getenv("EZTEXTING_PASSWORD"))
	req.Header.Set("Content-Type", "application/json")
	if resp, err := http.DefaultClient.Do(req); err == nil {
		resp.Body.Close()
	}
}

Which appointment does a reply belong to? The lookup hides a real decision. One phone number can have several appointments booked (a parent booking for two kids, a patient with a cleaning and a follow-up). When the webhook includes id, it's the message ID of the reminder being replied to: match on that. Without it, apply the reply only if exactly one booked appointment for that number has had its reminder go out; otherwise don't guess, and ask the person to confirm another way. The End-to-end example implements this rule. If you need certainty, put a reply code in the reminder (Reply C2 to confirm) and parse it.


Gotchas

  • Time zones. Store the customer's zone (or at least their offset) with the appointment. "9am" means nothing without it, and sendAt without an offset is a bug waiting for daylight-saving time.
  • Quiet hours. A 24-hour lead time for a 7am appointment means a 7am text. Clamp sends into 8am–9pm local, or shift to the previous evening.
  • Duplicate reminders. If your booking system emits "updated" events for trivial changes, you'll schedule twice. Only reschedule when the start time actually changes, and always cancel the previous ID first.
  • Numbers that bounce. Disconnected numbers, most landlines, and some VoIP numbers are accepted at send time and bounce later. Check /responses/delivery with filters[status][eq]=bounced the morning after, and fall back to a phone call for those.
  • Opted-out customers. Scheduling a reminder for them is rejected with a 400, "The phone numbers that you're sending to are opted out". Read optOut on the contact (GET /v1/contacts/{phoneNumber}) when the appointment is booked and offer another channel.

Variations

  • Two reminders (one week + one day): two sendAt sends, two stored IDs.
  • Confirmation at booking: an immediate send (no sendAt) with the same template.
  • Many locations: set companyName per location, and fromNumber if each has its own number.
  • Bulk reminders for a whole day: put tomorrow's patients in a contact group with custom fields for time and provider, and send one template to the group. See Core concepts: transactional vs. campaign.

Related

API reference


Did this page help you?