Customer support
Validate user and lead emails and phones in Intercom
Check the email and phone of each new Intercom user or lead with a signed webhook and a small handler that stores the result in contact custom attributes.
Updated 2026-11-26
This recipe checks the email and phone number of every new user and lead in Intercom and stores the answer in custom attributes on the contact, so teammates see a probable typo before replying, and you can build segments that keep bad or disposable addresses out of outbound messages. There is no native Qelka app for Intercom: a private Intercom app sends webhook notifications to a small handler of yours, which calls the API and updates the contact through Intercom's REST API.
What you need
- An Intercom workspace and a private app in the Developer Hub. Its access token, under Configure, Authentication, calls the REST API for your own workspace; its client secret, on Basic Info, verifies webhook signatures.
- Three custom data attributes on people, of type text:
email_status,email_suggestionandphone_e164. Create them in Intercom's people data settings, or with the API'sPOST /data_attributesand"model": "contact". - 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 intercom-webhook.js:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const encoder = new TextEncoder()
const topics = new Set(['contact.user.created', 'contact.lead.created', 'contact.lead.added_email'])
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, rawBody, header) {
const key = await crypto.subtle.importKey('raw', encoder.encode(env.INTERCOM_CLIENT_SECRET), { name: 'HMAC', hash: 'SHA-1' }, false, ['sign'])
const digest = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(rawBody)))
return safeEqual(`sha1=${[...digest].map((byte) => byte.toString(16).padStart(2, '0')).join('')}`, header)
}
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 intercom(env, path, init = {}) {
const response = await fetch(`https://api.intercom.io${path}`, {
...init,
headers: {
Authorization: `Bearer ${env.INTERCOM_ACCESS_TOKEN}`,
'Intercom-Version': '2.18',
Accept: 'application/json',
'Content-Type': 'application/json',
},
signal: AbortSignal.timeout(8000),
})
if (!response.ok) throw new Error(`Intercom ${init.method ?? 'GET'} ${path}: ${response.status}`)
return response.json()
}
async function checkContact(env, contactId) {
const contact = await intercom(env, `/contacts/${contactId}`)
const stored = contact.custom_attributes ?? {}
if (stored.email_status || stored.phone_e164) return
const [emailResult, phoneResult] = await Promise.all([
contact.email ? check(env, '/email', { email: contact.email, mode: 'full' }, 15000) : null,
contact.phone ? check(env, '/phone', { phone: contact.phone, country: env.DEFAULT_COUNTRY || undefined }, 8000) : null,
])
const attributes = {}
if (contact.email) {
attributes.email_status = emailResult ? emailResult.status : 'unchecked'
attributes.email_suggestion = emailResult?.did_you_mean ?? ''
}
if (contact.phone) attributes.phone_e164 = !phoneResult ? 'unchecked' : phoneResult.status === 'valid' ? phoneResult.e164 : phoneResult.status
if (Object.keys(attributes).length === 0) return
await intercom(env, `/contacts/${contactId}`, { method: 'PUT', body: JSON.stringify({ custom_attributes: attributes }) })
}
export async function handle(request, env, waitUntil) {
if (request.method === 'HEAD') return new Response(null, { status: 200 })
if (request.method !== 'POST') return new Response(null, { status: 405 })
const rawBody = await request.text()
if (!(await signatureIsValid(env, rawBody, request.headers.get('X-Hub-Signature') ?? ''))) return new Response(null, { status: 401 })
const notification = JSON.parse(rawBody)
const contactId = notification.data?.item?.id
if (!topics.has(notification.topic) || !contactId) return new Response(null, { status: 200 })
waitUntil(checkContact(env, contactId).catch((error) => console.error(`contact check failed: ${error.message}`)))
return new Response(null, { status: 200 })
}
Intercom validates the endpoint with a HEAD request when you save it, so the handler answers HEAD with 200. Every notification is a notification_event with a topic and the contact in data.item; the handler only takes the id from it.
Intercom gives an endpoint 5 seconds to answer, according to its current docs, and retries once a minute later; too many errors pause deliveries for a while. The handler therefore answers at once and does the checks in the background. mode: 'full' runs the mailbox check, the only way to get deliverable; if your host stops background work early, use mode: 'fast', which answers unknown with smtp_not_checked when the other checks pass. See the email reference.
The Intercom-Version header pins the REST API version the code was written against; check Intercom's changelog before you raise it. A lead without an email or phone yet is skipped and picked up again by contact.lead.added_email.
2. Deploy it with its secrets
import { handle } from './intercom-webhook.js'
export default {
fetch: (request, env, ctx) => handle(request, env, (task) => ctx.waitUntil(task)),
}
import { waitUntil } from '@vercel/functions'
import { handle } from '../intercom-webhook.js'
export default {
fetch: (request) => handle(request, process.env, waitUntil),
}
On Vercel the entry file is api/intercom.js, with "type": "module" in package.json. Store as secrets (wrangler secret put or vercel env add): QELKA_API_KEY, INTERCOM_ACCESS_TOKEN, INTERCOM_CLIENT_SECRET and, optionally, DEFAULT_COUNTRY, the two-letter country used to read numbers typed without +.
3. Subscribe to the topics
In the Developer Hub, open your app, then Configure, Webhooks. Enter the handler's HTTPS URL and select the topics contact.user.created, contact.lead.created and contact.lead.added_email. If a topic shows a permission error, the app is missing a permission that topic needs. Webhook subscriptions belong to the app, so you receive events from every workspace where it is installed.
4. Test it
With a sk_test_ key, start a Messenger conversation as a visitor and leave the email disposable@example.com. The lead's email_status reads risky a few seconds later. undeliverable@example.com gives undeliverable, any other well-formed address deliverable. Then swap in a live key.
5. Use the attributes
email_status |
Meaning | Suggested action |
|---|---|---|
undeliverable |
Bad syntax, no domain, or the mailbox was refused | Ask for the right address in the conversation; email_suggestion holds a likely correction |
risky |
Disposable inbox, catch-all domain or full mailbox | Exclude disposable addresses from outbound messages, review trial and refund requests |
deliverable |
The mail server accepted the mailbox | Nothing to do |
unknown or unchecked |
Not conclusive, or the API was unreachable | Treat the contact normally, check again later |
Custom attributes show in the contact's details next to the conversation, and segments, workflows and outbound audiences can filter on them. An unknown email is not a bad email. phone_e164 holds the number in E.164 when it is valid, or invalid, unknown or unchecked. See Block disposable email signups for the disposable case.
Handle errors and rate limits
An API problem never blocks a conversation: the attribute reads unchecked, the handler logs the error type and the X-Request-Id, and you can re-check those contacts later. 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, which a bulk contact import can exceed: check imported files with a bulk file check instead. Each email check costs 1 credit and each basic phone check 1. See Errors and Rate limits.
A failed Intercom call throws and is logged with its path and status. When the update fails, check first that the three custom attributes exist with exactly these names.
Related
Frequently asked questions
Which webhook topics should I subscribe to?
How do I know a webhook really comes from Intercom?
Will updating the custom attributes trigger the webhook again?
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