Customer support
Validate requester emails and phone numbers in Freshdesk
Check the requester of each new Freshdesk ticket with an automation rule that triggers a webhook, then tag the ticket and update the contact through the API v2.
Updated 2026-11-26
This recipe checks the requester of every new Freshdesk ticket. The email status and the phone number in E.164 go to custom fields on the contact, the ticket gets a tag that views and automations can use, and a private note warns the agent about a probable typo or a disposable address. There is no native Qelka app for Freshdesk: an automation rule on ticket creation triggers a webhook, a small handler of yours calls our API and writes back through the Freshdesk API v2.
What you need
- A Freshdesk account with automations, and an admin or agent API key. API calls use Basic authentication with the API key as the username and
Xas the password. Freshdesk sets API rate limits per plan: check yours. - Two single-line text contact fields,
email_statusandphone_e164, added in Freshdesk's contact field settings. The API uses each field's name as its key: read them withGET /api/v2/contact_fieldsif Freshdesk named them differently. - A Qelka API key. A
sk_test_key returns simulated results and never spends credits: see Test mode. A restricted key limited toemailandphoneis enough. - 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 freshdesk-webhook.js:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
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 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 freshdesk(env, path, init = {}) {
const response = await fetch(`https://${env.FRESHDESK_DOMAIN}.freshdesk.com/api/v2${path}`, {
...init,
headers: { Authorization: `Basic ${btoa(`${env.FRESHDESK_API_KEY}:X`)}`, 'Content-Type': 'application/json' },
signal: AbortSignal.timeout(8000),
})
if (!response.ok) throw new Error(`Freshdesk ${init.method ?? 'GET'} ${path}: ${response.status}`)
return response.json()
}
async function checkTicket(env, ticketId) {
const ticket = await freshdesk(env, `/tickets/${ticketId}`)
if (ticket.tags.includes('contact_checked')) return
const contact = await freshdesk(env, `/contacts/${ticket.requester_id}`)
const stored = contact.custom_fields ?? {}
const fields = {}
const notes = []
const tags = ['contact_checked']
let emailStatus = stored.email_status
if (contact.email && !emailStatus) {
const result = await check(env, '/email', { email: contact.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}`)
const phone = contact.mobile || contact.phone
if (phone && !stored.phone_e164) {
const result = await check(env, '/phone', { 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 freshdesk(env, `/contacts/${contact.id}`, { method: 'PUT', body: JSON.stringify({ custom_fields: fields }) })
}
await freshdesk(env, `/tickets/${ticketId}`, { method: 'PUT', body: JSON.stringify({ tags: [...new Set([...ticket.tags, ...tags])] }) })
if (notes.length > 0) {
await freshdesk(env, `/tickets/${ticketId}/notes`, { method: 'POST', body: JSON.stringify({ body: notes.join('<br>'), private: true }) })
}
}
export async function handle(request, env, waitUntil) {
if (request.method !== 'POST') return new Response(null, { status: 405 })
if (!safeEqual(request.headers.get('X-Webhook-Token') ?? '', env.WEBHOOK_TOKEN)) return new Response(null, { status: 401 })
const payload = await request.json().catch(() => ({}))
const ticketId = Number(payload.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 })
}
The webhook only carries the ticket id. The handler reads the ticket and the requester's contact itself, answers Freshdesk at once and does the work in the background. Freshdesk retries a failed call every 30 minutes, up to 48 times, and emails the account administrators about failures, according to its docs, so a slow answer would only create noise.
The contact_checked tag makes the handler idempotent: a repeated call for the same ticket does nothing. The handler sends the ticket's existing tags along with its own, so no tag is lost whether the API replaces the list or adds to it. 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. DEFAULT_COUNTRY lets the API read numbers typed without +: see the phone reference.
2. Deploy it with its secrets
import { handle } from './freshdesk-webhook.js'
export default {
fetch: (request, env, ctx) => handle(request, env, (task) => ctx.waitUntil(task)),
}
import { waitUntil } from '@vercel/functions'
import { handle } from '../freshdesk-webhook.js'
export default {
fetch: (request) => handle(request, process.env, waitUntil),
}
On Vercel the entry file is api/freshdesk.js, with "type": "module" in package.json. Store as secrets (wrangler secret put or vercel env add): QELKA_API_KEY, FRESHDESK_DOMAIN (the yourcompany part of your Freshdesk address), FRESHDESK_API_KEY, WEBHOOK_TOKEN (a long random string) and, optionally, DEFAULT_COUNTRY.
3. Create the automation rule
In Freshdesk, go to Admin, Workflows, Automations, open the Ticket Creation tab and create a rule:
- Conditions: match the tickets you want, for example by source, so tickets that arrived by email can be left out.
- Action: Trigger Webhook. Request type: POST. Callback URL: your handler's URL.
- Turn on Add custom headers and add one line in the format Freshdesk shows,
X-Webhook-Token: your-token, with no extra spaces: Freshdesk warns that stray spaces can stop the webhook. - Encoding: JSON. Content: Advanced, with this body:
{ "ticket_id": "{{ticket.id}}" }
Leave Requires authentication off: it is meant for APIs that expect a key, and the handler checks its own token instead. Save the rule. It runs on ticket creation only, so the tags and notes the handler adds later do not fire it again; if you have rules on ticket updates, make sure they ignore the contact_checked tag.
4. Test it
With a sk_test_ key, open a ticket from the support portal 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.
5. Use the tags
| Tag | Meaning | Suggested action |
|---|---|---|
email_undeliverable |
Bad syntax, no domain, or the mailbox was refused | Read the private note for a likely correction; reach the customer by phone or another channel |
email_risky |
Disposable inbox, catch-all domain or full mailbox | Route disposable-address refund requests to a review group |
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 contact's number does not exist in its numbering plan | Ask for a working number before promising a callback |
An unknown email is not a bad email. Ticket views filtered on these tags give agents a queue to clean, and phone_e164 on the contact is the number to dial: see Format phone numbers in E.164.
Handle errors and rate limits
An API problem never blocks a ticket: it is tagged email_unchecked, no contact field is written, the handler logs the error type and the X-Request-Id, and the requester's next ticket 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 Freshdesk call throws and is logged with its path and status. Each new ticket costs the handler up to four Freshdesk calls, which counts against your plan's API limit; Freshdesk also caps webhook calls per hour and buffers the rest.
Related
Frequently asked questions
Why check the email of a customer who just wrote in?
How does the handler know the request comes from Freshdesk?
Does each ticket from the same customer cost a credit?
More in Customer support
All integrationsPut 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