Skip to content

Customer support

Validate requester emails and phone numbers in Zendesk

Check the requester of each new Zendesk ticket with a trigger, a signed webhook and a small handler that tags the ticket and stores the result on the user.

Updated 2026-11-26

This recipe checks the requester of every new Zendesk ticket: the email address, and the phone number when the profile has one. The result lands as tags on the ticket, which views and triggers can use, in two user fields on the requester, and in a private note when there is something an agent should see, such as a probable typo. There is no native Qelka app for Zendesk: a trigger notifies a webhook, a small handler of yours calls the API and writes back through Zendesk's REST API.

What you need

  • A Zendesk account with webhooks and triggers, and admin access to Admin Center. Zendesk lists webhooks on Team plans and above, as far as we know: check yours.
  • A Zendesk API token, created in Admin Center under Apps and integrations, APIs, and the email of the agent it belongs to. API calls use Basic authentication with email/token as the username and the token as the password.
  • Two text user fields with the keys email_status and phone_e164, created in Admin Center under People, User fields.
  • A Qelka API key. A sk_test_ key returns simulated results and never spends credits: see Test mode. A restricted key limited to email and phone is enough, plus phone_reports if you add the caller reports below.
  • A place to run the handler that receives a web Request: Cloudflare Workers or Vercel below, or any server through a framework such as Hono.

Steps

1. The handler

Save as zendesk-webhook.js:

javascript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const encoder = new TextEncoder()

function safeEqual(a, b) {
  if (a.length !== b.length) return false
  let difference = 0
  for (let index = 0; index < a.length; index += 1) difference |= a.charCodeAt(index) ^ b.charCodeAt(index)
  return difference === 0
}

async function signatureIsValid(env, timestamp, rawBody, signature) {
  const key = await crypto.subtle.importKey('raw', encoder.encode(env.ZENDESK_SIGNING_SECRET), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
  const digest = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(timestamp + rawBody)))
  return safeEqual(btoa(String.fromCharCode(...digest)), signature)
}

async function check(env, path, body, timeoutMs) {
  for (let attempt = 1; attempt <= 2; attempt += 1) {
    let response
    try {
      response = await fetch(`https://api.qelka.com/v1${path}`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${env.QELKA_API_KEY}`, 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
        signal: AbortSignal.timeout(timeoutMs),
      })
    } catch (error) {
      console.warn(`check skipped: ${path} unreachable (${error.name})`)
      return null
    }
    if (response.ok) return response.json()
    if (attempt === 1 && [429, 500, 502, 503].includes(response.status)) {
      const retryAfter = Number(response.headers.get('Retry-After'))
      await sleep((retryAfter > 0 ? Math.min(retryAfter, 5) : 1) * 1000)
      continue
    }
    const failure = await response.json().catch(() => ({}))
    console.warn(`check skipped: ${failure.error?.type ?? response.status} request ${response.headers.get('X-Request-Id')}`)
    return null
  }
  return null
}

async function zendesk(env, path, init = {}) {
  const response = await fetch(`https://${env.ZENDESK_SUBDOMAIN}.zendesk.com/api/v2${path}`, {
    ...init,
    headers: {
      Authorization: `Basic ${btoa(`${env.ZENDESK_EMAIL}/token:${env.ZENDESK_API_TOKEN}`)}`,
      'Content-Type': 'application/json',
    },
    signal: AbortSignal.timeout(8000),
  })
  if (!response.ok) throw new Error(`Zendesk ${init.method ?? 'GET'} ${path}: ${response.status}`)
  return response.json()
}

async function checkTicket(env, ticketId) {
  const { ticket } = await zendesk(env, `/tickets/${ticketId}`)
  if (ticket.tags.includes('contact_checked')) return
  const { user } = await zendesk(env, `/users/${ticket.requester_id}`)

  const stored = user.user_fields ?? {}
  const tags = ['contact_checked']
  const notes = []
  const fields = {}

  let emailStatus = stored.email_status
  if (user.email && !emailStatus) {
    const result = await check(env, '/email', { email: user.email, mode: 'full' }, 15000)
    emailStatus = result?.status ?? 'unchecked'
    if (result) fields.email_status = result.status
    if (result?.did_you_mean) notes.push(`The requester's email may be a typo of ${result.did_you_mean}. Confirm it before replying.`)
    if (result?.reason === 'disposable') notes.push('The requester uses a disposable email address.')
  }
  if (emailStatus) tags.push(`email_${emailStatus}`)

  if (user.phone && !stored.phone_e164) {
    const result = await check(env, '/phone', { phone: user.phone, country: env.DEFAULT_COUNTRY || undefined }, 8000)
    if (result?.status === 'valid') fields.phone_e164 = result.e164
    if (result?.status === 'invalid') tags.push('phone_invalid')
  }

  if (Object.keys(fields).length > 0) {
    await zendesk(env, `/users/${user.id}`, { method: 'PUT', body: JSON.stringify({ user: { user_fields: fields } }) })
  }
  await zendesk(env, `/tickets/${ticketId}/tags`, { method: 'PUT', body: JSON.stringify({ tags }) })
  if (notes.length > 0) {
    await zendesk(env, `/tickets/${ticketId}`, { method: 'PUT', body: JSON.stringify({ ticket: { comment: { body: notes.join('\n'), public: false } } }) })
  }
}

export async function handle(request, env, waitUntil) {
  if (request.method !== 'POST') return new Response(null, { status: 405 })
  const rawBody = await request.text()
  const timestamp = request.headers.get('X-Zendesk-Webhook-Signature-Timestamp') ?? ''
  const signature = request.headers.get('X-Zendesk-Webhook-Signature') ?? ''
  if (!(await signatureIsValid(env, timestamp, rawBody, signature))) return new Response(null, { status: 401 })

  const ticketId = Number(JSON.parse(rawBody).ticket_id)
  if (!Number.isInteger(ticketId) || ticketId <= 0) return new Response(null, { status: 204 })
  waitUntil(checkTicket(env, ticketId).catch((error) => console.error(`ticket check failed: ${error.message}`)))
  return new Response(null, { status: 204 })
}

Zendesk signs every webhook request: it computes an HMAC-SHA256 of the X-Zendesk-Webhook-Signature-Timestamp header followed by the raw body, with the webhook's signing secret, and sends it base64-encoded in X-Zendesk-Webhook-Signature. The handler checks it before reading the body.

The webhook only carries the ticket id. The handler reads the ticket and the requester itself, so it always works on current data, and it answers Zendesk at once and does the work in the background. The contact_checked tag makes it idempotent: a repeated event for the same ticket does nothing.

mode: 'full' runs the mailbox check, the only way to get deliverable. If your host stops background work early, use mode: 'fast', which still catches typos, dead domains and disposable inboxes. See the email reference. Set DEFAULT_COUNTRY so numbers typed without + can be read: see the phone reference.

2. Deploy it with its secrets

import { handle } from './zendesk-webhook.js'

export default {
  fetch: (request, env, ctx) => handle(request, env, (task) => ctx.waitUntil(task)),
}
import { waitUntil } from '@vercel/functions'
import { handle } from '../zendesk-webhook.js'

export default {
  fetch: (request) => handle(request, process.env, waitUntil),
}

On Vercel the entry file is api/zendesk.js, with "type": "module" in package.json. Store as secrets (wrangler secret put or vercel env add): QELKA_API_KEY, ZENDESK_SUBDOMAIN, ZENDESK_EMAIL, ZENDESK_API_TOKEN, optionally DEFAULT_COUNTRY, and after the next step ZENDESK_SIGNING_SECRET.

3. Create the webhook

In Admin Center, go to Apps and integrations, Webhooks, and create a webhook:

  1. Connection method: Trigger or automation.
  2. Endpoint URL: your handler's URL. Request method: POST. Request format: JSON.
  3. Authentication: none is needed, since the handler checks the signature.

Create it, open its details page and reveal the signing secret. Store it as ZENDESK_SIGNING_SECRET and redeploy.

4. Create the trigger

In Admin Center, go to Objects and rules, Business rules, Triggers, and add a trigger:

  • Conditions, meet all: Ticket is Created. Add a channel condition if you only want web form, chat or API tickets.
  • Actions: Notify webhook, choose your webhook, and set the JSON body:
json
{ "ticket_id": "{{ticket.id}}" }

The trigger runs on creation only, so the tags and the note the handler adds later never fire it again. Go back to the webhook and finish its setup.

5. Test it

With a sk_test_ key, submit a ticket from a web form as disposable@example.com. The ticket gets the tags contact_checked and email_risky and a private note about the disposable address. undeliverable@example.com gives email_undeliverable, any other well-formed address email_deliverable. Then swap in a live key.

6. Use the tags

Tag Meaning Suggested action
email_undeliverable Bad syntax, no domain, or the mailbox was refused Read the private note for a suggested correction; reach the customer another way before replying
email_risky Disposable inbox, catch-all domain or full mailbox Route disposable-address refund or trial requests to a review view
email_deliverable The mail server accepted the mailbox Nothing to do
email_unknown or email_unchecked Not conclusive, or the API was unreachable Handle the ticket normally
phone_invalid The phone on the profile does not exist in its numbering plan Ask for a working number before promising a callback

An unknown email is not a bad email. Views filtered on these tags give agents a queue to clean, and a second trigger can route email_risky tickets to a specific group.

Caller reports for US and Canadian numbers

For teams that call customers back, the API can also say how many consumers reported a North American number to the US Federal Trade Commission as an unwanted caller over the last 90 days of published data. Add this inside the phone block, right after the phone check:

javascript
if (result?.status === 'valid' && result.country?.calling_code === '1') {
  const reports = await check(env, '/phone/reports', { phone: result.e164 }, 8000)
  if (reports?.status === 'reported') {
    notes.push(`${reports.reports} consumers reported this number to the FTC between ${reports.first_reported} and ${reports.last_reported}. Reports are unverified and caller ID can be spoofed.`)
  }
}

Each lookup costs 1 credit, and numbers outside the North American plan come back unsupported and are not billed. Show the count as a fact about complaints, never as proof about the customer: see the phone reports reference.

Handle errors and rate limits

An API problem never blocks a ticket: the handler tags email_unchecked, writes no user field, logs the error type and the X-Request-Id, and the next ticket from the same requester tries again. No error is billed. 401 and 403 mean a wrong or restricted key and 402 an empty balance: alert on those. A 429 is retried once after Retry-After. A key allows 200 requests per 10 seconds. Each email check costs 1 credit and each basic phone check 1. See Errors and Rate limits.

A failed Zendesk call throws and is logged with its path and status; the most common cause is a token from an agent who cannot edit end users or tickets. Zendesk also rate-limits its own API per account, which matters only if you replay many tickets at once.

Frequently asked questions

Why check the email of someone who just wrote to us?
For a ticket that arrived by email, the address works: it just sent you mail. The check matters for tickets from web forms, chat, the API or agents typing an address, where a typo means your reply bounces and the customer thinks you ignored them. It also flags disposable inboxes, which you may want to review before granting a refund or a trial. Limit the trigger to those channels if you like.
Which Zendesk plan do I need?
Zendesk's help center currently lists webhooks on the Support Team, Professional and Enterprise plans, and on Suite plans from Team up. Plans change, so check yours before building. Trial accounts have lower webhook limits.
Does every ticket cost a credit?
No. The handler stores the result in user fields on the requester, and reads those first. A customer who opens ten tickets is checked once, and the next nine tickets are tagged from the stored values for free.

More in Customer support

All integrations

Put this check in your product

Get an API key in under a minute. 100 free credits every month, no card required.

  • 100 free credits a month
  • No card
  • Test keys spend nothing
  • Cancel any time