· 4 min · TextMeFlow Team

Sending WhatsApp Messages from Firebase Cloud Functions

If your app runs on Firebase, the data that should trigger a WhatsApp message — a new order, a status change, a booking — already lives in Firestore. Rather than polling it from an external script, a Cloud Function can react to the write itself and call the TextMeFlow API in the same breath. No separate backend, no cron job checking "did anything change since last time I looked."

This covers the two triggers you'll actually use: a Firestore onDocumentWritten function for anything tied to a single document, and a scheduled function for reminders that fire on the clock instead.

Store the API key as a secret, not an env var

Cloud Functions (2nd gen) supports Secret Manager natively, which is where a tmf_ API key belongs — never in .env, never committed alongside firebase.json. Create it once:

firebase functions:secrets:set TEXTMEFLOW_API_KEY

You'll be prompted to paste the key value, and Firebase stores it in Google Secret Manager rather than in your function's source or config.

React to a Firestore write

Say you have an orders collection, and you want a WhatsApp message the moment a document's status field flips to shipped. Using the Firebase Functions v2 SDK:

const { onDocumentUpdated } = require("firebase-functions/v2/firestore");
const { defineSecret } = require("firebase-functions/params");

const textmeflowKey = defineSecret("TEXTMEFLOW_API_KEY");

exports.notifyOrderShipped = onDocumentUpdated(
  { document: "orders/{orderId}", secrets: [textmeflowKey] },
  async (event) => {
    const before = event.data.before.data();
    const after = event.data.after.data();

    if (before.status === after.status || after.status !== "shipped") {
      return;
    }

    const res = await fetch("https://api.textmeflow.eu/v1/messages", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${textmeflowKey.value()}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        to: after.customerPhone,
        text: `Your order #${after.orderNumber} has shipped and is on its way.`,
      }),
    });

    if (!res.ok) {
      const body = await res.text();
      throw new Error(`TextMeFlow send failed: ${res.status} ${body}`);
    }
  }
);

The before.status === after.status guard matters more than it looks: Firestore triggers also fire on writes that touch unrelated fields on the same document, and without that check you'd send a duplicate WhatsApp message every time someone edits the order's shipping address after it already shipped.

Throwing on a non-2xx response is deliberate too. Cloud Functions retries a failed invocation (when you enable retries on the trigger), so surfacing the real error — a bad phone format, a disconnected session, a 429 from a rate limit — lets Firebase's own retry logic handle it instead of the message silently vanishing into a function log nobody reads until a customer complains.

Scheduled reminders with Cloud Scheduler

Not every message maps to a single document change. A "your appointment is tomorrow" reminder needs to fire based on the clock, not a write. onSchedule wraps Cloud Scheduler for exactly this:

const { onSchedule } = require("firebase-functions/v2/scheduler");
const { getFirestore } = require("firebase-admin/firestore");

exports.appointmentReminders = onSchedule(
  { schedule: "0 9 * * *", secrets: [textmeflowKey] },
  async () => {
    const db = getFirestore();
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const dateStr = tomorrow.toISOString().slice(0, 10);

    const snapshot = await db
      .collection("appointments")
      .where("date", "==", dateStr)
      .get();

    await Promise.all(
      snapshot.docs.map((doc) => {
        const appt = doc.data();
        return fetch("https://api.textmeflow.eu/v1/messages", {
          method: "POST",
          headers: {
            Authorization: `Bearer ${textmeflowKey.value()}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            to: appt.phone,
            text: `Reminder: your appointment is tomorrow at ${appt.time}.`,
          }),
        });
      })
    );
  }
);

This runs daily at 09:00 in the function's configured time zone, finds every appointment scheduled for tomorrow, and fires one WhatsApp send per document. It's a close cousin of the pattern in sending WhatsApp confirmations from Stripe webhooks — a trigger source that isn't a direct API call, feeding the same /v1/messages request.

Avoid double sends across retried invocations

A scheduled function or a retried Firestore trigger can run twice for the same logical event — Cloud Functions guarantees at-least-once delivery, not exactly-once. If a duplicate WhatsApp reminder would annoy a customer more than a missed one, write a marker back to Firestore before or after the send (remindedAt: new Date() on the appointment document) and check it at the top of the function. That turns a retry into a no-op instead of a second message landing in the same chat ten seconds later.

Handle the response as a queue, not a delivery guarantee

A 202 Accepted with a message_id means TextMeFlow queued the job — not that WhatsApp delivered it. Writing that message_id back onto the Firestore document (whatsappMessageId: body.message_id) lets your incoming webhook handler update the same document when the delivery-status event arrives, so a failed send shows up as a field you can query instead of disappearing after the function returns.

Sign up for the free plan to get an API key and wire this into your own Firebase project — 50 messages a month costs nothing while you get the trigger logic right before sending real volume.

Want to send WhatsApp messages via API yourself?

Free forever up to 50 messages/month. Scan a QR and send your first message within 5 minutes.

Free forever