Blog
Build Your Own Missed-Call Alert With Twilio, WordPress and Nuxt, and Keep It Running (Part II)

Build Your Own Missed-Call Alert With Twilio, WordPress and Nuxt, and Keep It Running (Part II)

Part II of a two-part guide. Build a missed-call text-back and alert with Twilio, WordPress and Nuxt code that checks Twilio's signature, then keep it running through storms, number moves and ad changes.

This is Part II of two. Part I covers choosing and setting up the system without code: phone apps like Quo and CallRail, GoHighLevel, no-code tools and answering services. It also covers making the alert reach you, the landline and texting rules, and a test list. Read it first if you haven't, because those parts apply here too.

This part is for you or your developer. You want full control: your own number, your own rules, and the code on your own site. It covers the Twilio setup, then working code for WordPress and for a Nuxt site on Cloudflare. All of it checks that the request really came from Twilio, skips duplicate reports, texts the caller back and alerts you. After the code, it covers keeping the system running: escalation, moving your number, storm week, Local Services Ads and measuring results.

Test everything on a staging site first. I have checked the code's syntax and its signature check against Twilio's published example, but I haven't run it against a live account.

How it works: the Twilio setup

This route takes the most work, but nothing is hidden from you. The full code is in the WordPress and Nuxt sections below. Here is how the pieces fit.

  1. Get a number. Buy a Twilio number with Voice and SMS turned on.
  2. Register for texting. Anyone sending SMS from an application over a US 10-digit number must register for A2P 10DLC. Do this first. Approval can take days, and unregistered messages can be blocked or filtered.
  3. Ring your cell, then report back. Point the number's "A call comes in" setting at a TwiML Bin (a small piece of XML you paste into Twilio). It rings your cell and tells Twilio where to report what happened:
<Response>
  <Dial timeout="20" action="https://yoursite.com/api/missed-call">
    <Number>+15555550100</Number>
  </Dial>
</Response>

Replace the address with your endpoint and the number with your cell.

  1. Read the result. When the call ends, Twilio sends your address a DialCallStatus. completed means someone answered. no-answer, busy, failed and canceled mean a miss. You act on those four.
  2. Know the limits. The no-answer status arrives only after the call rings out, about as long as the timeout you set. Twilio relies on the recipient's carrier to report busy, and some carriers don't send that signal when you are already on a call. So don't rely on busy alone.
  3. Verify every request. Twilio signs each request with an X-Twilio-Signature header. Your code must check it before doing anything. Otherwise anyone who finds your address can trigger texts from your account. Both code samples below do this.

Before you text callers

Two things from Part I matter more here, because you are building the texting yourself:

  • Landlines can't get texts. A text to a landline fails and Twilio logs it as a delivery error. Your alert should still show the caller's number so you can call back. Twilio's Lookup service can tell you whether a number is a landline before you send.
  • Texting rules. Put your business name in the text, add "Reply STOP to opt out," and honor opt-outs. Read the rules section in Part I and check your state. This isn't legal advice.

WordPress

Showing the right number and alerting on form leads are covered in Part I. This is the receiver.

If you don't want a CRM, WordPress can take Twilio's report, verify it, text the caller and alert you. Put this in a small plugin, not your theme.

First, put your secrets in wp-config.php:

define('TWILIO_SID', 'ACxxxxxxxx');
define('TWILIO_TOKEN', 'your-auth-token');
define('TWILIO_WEBHOOK_URL', 'https://yoursite.com/wp-json/leads/v1/missed-call');
define('PUSHOVER_APP', 'your-app-token');
define('PUSHOVER_USER', 'your-user-key');

Then the plugin code:

function mc_valid_signature(WP_REST_Request $r): bool {
  $sent = $r->get_header('x-twilio-signature');
  if (!$sent) return false;
  $params = $r->get_body_params();
  ksort($params, SORT_STRING);
  $data = TWILIO_WEBHOOK_URL;
  foreach ($params as $k => $v) $data .= $k . $v;
  $expected = base64_encode(hash_hmac('sha1', $data, TWILIO_TOKEN, true));
  return hash_equals($expected, $sent);
}

add_action('rest_api_init', function () {
  register_rest_route('leads/v1', '/missed-call', [
    'methods' => 'POST',
    'permission_callback' => '__return_true', // the signature check is the lock
    'callback' => function (WP_REST_Request $r) {
      if (!mc_valid_signature($r)) return new WP_REST_Response('Forbidden', 403);

      $twiml  = '<Response><Say>Sorry we missed you. We are texting you now.</Say></Response>';
      $status = $r->get_param('DialCallStatus');
      if (!in_array($status, ['no-answer', 'busy', 'failed', 'canceled'], true)) {
        return new WP_REST_Response('<Response/>', 200);
      }

      $sid = sanitize_text_field($r->get_param('CallSid'));
      if (get_transient("mc_$sid")) return new WP_REST_Response($twiml, 200); // dedupe
      set_transient("mc_$sid", 1, HOUR_IN_SECONDS);

      $from = sanitize_text_field($r->get_param('From')); // the caller
      $to   = sanitize_text_field($r->get_param('To'));   // your Twilio number

      // 1. Text the caller back
      wp_remote_post('https://api.twilio.com/2010-04-01/Accounts/' . TWILIO_SID . '/Messages.json', [
        'timeout' => 5,
        'headers' => ['Authorization' => 'Basic ' . base64_encode(TWILIO_SID . ':' . TWILIO_TOKEN)],
        'body'    => [
          'From' => $to,
          'To'   => $from,
          'Body' => 'Hi, this is [Name] at [Company]. Sorry I missed you, I am on a roof. Text me what is going on, or I will call you back soon. Reply STOP to opt out.',
        ],
      ]);

      // 2. Alert you (repeats until you tap it)
      wp_remote_post('https://api.pushover.net/1/messages.json', [
        'timeout' => 5,
        'body'    => [
          'token' => PUSHOVER_APP, 'user' => PUSHOVER_USER, 'priority' => 2,
          'retry' => 60, 'expire' => 600, 'title' => 'Missed call',
          'message' => 'Missed call from ' . $from,
        ],
      ]);

      return new WP_REST_Response($twiml, 200);
    },
  ]);
});

// Twilio expects XML back, not JSON.
add_filter('rest_pre_serve_request', function ($served, $result, $request) {
  if ($request->get_route() !== '/leads/v1/missed-call') return $served;
  header('Content-Type: text/xml; charset=utf-8');
  echo $result->get_data();
  return true;
}, 10, 3);

Rules for this version:

  • The address in TWILIO_WEBHOOK_URL must match exactly what Twilio calls, including https and any trailing slash. A mismatch makes every signature check fail.
  • Exclude the endpoint from page caching and from your security plugin's blocks.
  • Don't use WP-Cron for escalation. It only runs when someone visits the site, so a "no reply in 5 minutes" step can fire late or never. Let your CRM or an automation tool handle the timing.
  • A failed text shouldn't stop the alert. For a stronger version, wrap each call so one failure doesn't block the other.
  • Test it before you rely on it. I'd use a staging site first.

Headless sites (Nuxt, Next, or WordPress as CMS only)

The call path doesn't change, because it never touched your front end. What changes is where your code lives.

  • The receiver is a server route (/api/missed-call in Nuxt or Next) or a serverless function on Vercel, Netlify or Cloudflare. It needs a public HTTPS address.
  • Form leads post from the front end to a server route. That route creates the CRM contact and sends the alert. Never put API keys in client code.
  • State lives in your CRM through its API, unless you want to build your own database.
  • Timers belong in an outside scheduler or the CRM's wait steps, not in a function that sleeps.
  • Webhooks can arrive twice. Dedupe on the call ID.

Here is the Nuxt version. It is written for Cloudflare, so it uses the Web Crypto API for the signature check and a KV store for the dedupe. A function on Cloudflare can't remember anything between requests, which is why the dedupe needs storage.

First, declare your secrets in nuxt.config.ts. Set the real values with NUXT_TWILIO_SID, NUXT_TWILIO_TOKEN and so on in your host's environment settings:

export default defineNuxtConfig({
  runtimeConfig: {
    twilioSid: '',
    twilioToken: '',
    twilioWebhookUrl: '', // exactly the address Twilio calls
    pushoverApp: '',
    pushoverUser: '',
  },
  nitro: {
    storage: {
      kv: { driver: 'cloudflare-kv-binding', binding: 'MISSED_CALLS' },
    },
  },
})

Then bind a KV namespace in wrangler.toml:

[[kv_namespaces]]
binding = "MISSED_CALLS"
id = "your-kv-namespace-id"

And the route itself:

// server/api/missed-call.post.ts
const form = (data: Record<string, string>) => new URLSearchParams(data).toString()
const formHeaders = { 'Content-Type': 'application/x-www-form-urlencoded' }

async function validSignature(url: string, params: Record<string, string>, sent: string, token: string) {
  const data = url + Object.keys(params).sort().map((k) => k + params[k]).join('')
  const key = await crypto.subtle.importKey(
    'raw', new TextEncoder().encode(token), { name: 'HMAC', hash: 'SHA-1' }, false, ['sign'],
  )
  const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(data)))
  const expected = btoa(String.fromCharCode(...mac))
  if (expected.length !== sent.length) return false
  let diff = 0
  for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ sent.charCodeAt(i)
  return diff === 0
}

export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig()
  const params = (await readBody(event)) as Record<string, string>
  const sent = getHeader(event, 'x-twilio-signature') || ''

  if (!(await validSignature(config.twilioWebhookUrl, params, sent, config.twilioToken))) {
    throw createError({ statusCode: 403, message: 'Forbidden' })
  }

  setResponseHeader(event, 'content-type', 'text/xml')
  const twiml = '<Response><Say>Sorry we missed you. We are texting you now.</Say></Response>'

  if (!['no-answer', 'busy', 'failed', 'canceled'].includes(params.DialCallStatus)) {
    return '<Response/>'
  }

  // Dedupe: Twilio can send the same report twice
  const kv = useStorage('kv')
  if (await kv.hasItem(`call:${params.CallSid}`)) return twiml
  await kv.setItem(`call:${params.CallSid}`, 1, { ttl: 3600 })

  // One failure shouldn't block the other
  await Promise.allSettled([
    // 1. Text the caller back
    $fetch(`https://api.twilio.com/2010-04-01/Accounts/${config.twilioSid}/Messages.json`, {
      method: 'POST',
      headers: {
        ...formHeaders,
        Authorization: 'Basic ' + btoa(`${config.twilioSid}:${config.twilioToken}`),
      },
      body: form({
        From: params.To,
        To: params.From,
        Body: 'Hi, this is [Name] at [Company]. Sorry I missed you, I am on a roof. Text me what is going on, or I will call you back soon. Reply STOP to opt out.',
      }),
    }),
    // 2. Alert you (repeats until you tap it)
    $fetch('https://api.pushover.net/1/messages.json', {
      method: 'POST',
      headers: formHeaders,
      body: form({
        token: config.pushoverApp,
        user: config.pushoverUser,
        priority: '2',
        retry: '60',
        expire: '600',
        title: 'Missed call',
        message: `Missed call from ${params.From}`,
      }),
    }),
  ])

  return twiml
})

Notes for Next.js, Vercel or Netlify: the logic is identical. Swap useRuntimeConfig for environment variables, and swap the KV store for your host's storage, or let your CRM remember call IDs.

Test it before you rely on it. The signature check is the part people get wrong, and it fails quietly if the address doesn't match.

Test it before you rely on it

  1. Call your Twilio number and don't answer. Did the text arrive? Did your alert fire?
  2. Answer a call. Nothing should be sent.
  3. Send a fake request by hand with no signature. You should get a 403 back:
curl -i -X POST https://yoursite.com/api/missed-call -d "DialCallStatus=no-answer"
  1. Call twice in a row and check your logs. One call should produce one text, even if Twilio reports it twice.
  2. Call from a landline, if you can. The text will fail, but your alert should still show their number.
  3. Open your Twilio message logs. Look for failed or blocked texts. If texts are blocked, your A2P registration probably isn't finished.
  4. After any change to your site address or your hosting, test again. The signature check breaks if the address Twilio calls no longer matches the one in your settings.

If any step fails, fix it before storm season, not during it.

What should happen after the alert

A simple order works for most crews:

  • Right away: the caller gets the text and you get the alert.
  • After 3 minutes with no reply from you: the alert goes to a second person.
  • After 10 minutes: someone calls the homeowner back.
  • After hours: a different text, such as "We'll call you at 7 tomorrow," and a quieter alert so you can sleep.

Change the times to fit your crew. What matters is that someone owns the callback.

Moving your number

Customers already know your number. You have two ways to point it at the new system.

  • Forward it. Your old number stays where it is, and calls forward to the new one. Quick, and easy to undo. You keep paying the old carrier.
  • Port it. You move the number itself to the new provider. It takes longer, so ask your new provider how long and what account details they need. Don't cancel your old line until the move is finished.

Either way, update your website and your Google Business Profile once the new number is live.

Storm week

A hail week sends many calls at once, and a few things behave differently.

  • Repeat texts. Quo caps replies at one per contact every 3 hours. GoHighLevel's built-in setting doesn't, so cap it in a workflow.
  • Alert overload. If your phone buzzes every minute, you start ignoring it. Send alerts to two people and split the callbacks.
  • A different message. Swap in a storm text: "We are getting a lot of calls. We'll get back to you in the order they came in."
  • Check ahead of time. Run the test list below before the season, not during it.

If you run Local Services Ads

Google told Local Services Ads advertisers that from October 1, 2026, a missed call during your business hours can be charged as a lead if the caller stays on the line more than 20 seconds. The announcement has some exceptions, and the details are in Google's notice to advertisers. Read it before you rely on this summary.

What it means for you:

  • Keep your business hours in Google accurate.
  • Make sure a person or a backup picks up fast.
  • Don't count a text-back as a fix for the charge. It helps you win the job, but it doesn't change how Google counts the call.

Measure what you recover

Once it's running, check four numbers each month from your CRM or phone app:

  1. How many calls you missed.
  2. How many texts went out.
  3. How many callers replied.
  4. How many of those became an estimate or a job.

If texts go out but nobody replies, change the message. If people reply but nobody books, the problem is the callback. These are your own numbers, so they'll tell you more than any industry average.

Want it built for you?

If you'd rather not build and maintain this yourself, I do it for roofing sites. I've been building WordPress and WooCommerce sites for 14+ years. Tell me which stack you're on and how you want the alert to reach you, and I'll tell you which route fits.

Start here: masoodhq.com/roofers

Want to see your homepage?

Send your company name and town. I’ll email you a free preview.