Skip to content

CRM

Validate phone numbers and emails in Close

Check the email and phone of each new Close contact with a signed webhook and a small handler, then store the result in contact custom fields.

Updated 2026-11-26

This recipe checks the email and phone number of every contact created in Close and writes the answer to two contact custom fields, so reps see a bad address before they start a sequence and dial numbers in a clean format. There is no native Qelka integration for Close: a Close webhook subscription sends a signed event to a small handler of yours, which calls the API and updates the contact through Close's REST API.

What you need

  • A Close organization and a Close API key, from a user who can edit contacts and create webhook subscriptions. Close's API uses HTTP Basic authentication with the API key as the username and an empty password.
  • 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.
  • 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. Create two contact custom fields

In Close's custom field settings, add two text fields on contacts: Email status and Phone check. Read their ids, which start with cf_:

bash
curl https://api.close.com/api/v1/custom_field/contact/ -u "$CLOSE_API_KEY:"

2. The handler

Save as close-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 keyBytes = Uint8Array.from(env.CLOSE_SIGNATURE_KEY.match(/../g), (pair) => parseInt(pair, 16))
  const key = await crypto.subtle.importKey('raw', keyBytes, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
  const digest = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(timestamp + rawBody)))
  const expected = [...digest].map((byte) => byte.toString(16).padStart(2, '0')).join('')
  return safeEqual(expected, 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
}

const close = (env, path, init = {}) =>
  fetch(`https://api.close.com/api/v1${path}`, {
    ...init,
    headers: { Authorization: `Basic ${btoa(`${env.CLOSE_API_KEY}:`)}`, 'Content-Type': 'application/json' },
    signal: AbortSignal.timeout(8000),
  })

async function checkContact(env, id) {
  const found = await close(env, `/contact/${id}/`)
  if (!found.ok) return console.warn(`contact ${id} not readable: ${found.status}`)
  const contact = await found.json()
  const emailField = `custom.${env.EMAIL_STATUS_FIELD}`
  const phoneField = `custom.${env.PHONE_CHECK_FIELD}`
  if (contact[emailField] || contact[phoneField]) return

  const email = contact.emails?.[0]?.email
  const phone = contact.phones?.[0]?.phone
  const [emailResult, phoneResult] = await Promise.all([
    email ? check(env, '/email', { email, mode: 'full' }, 15000) : null,
    phone ? check(env, '/phone', { phone, country: env.DEFAULT_COUNTRY || undefined }, 8000) : null,
  ])

  const changes = {}
  if (email) changes[emailField] = emailResult ? emailResult.status : 'unchecked'
  if (phone) changes[phoneField] = !phoneResult ? 'unchecked' : phoneResult.status === 'valid' ? phoneResult.e164 : phoneResult.status
  if (Object.keys(changes).length === 0) return

  const saved = await close(env, `/contact/${id}/`, { method: 'PUT', body: JSON.stringify(changes) })
  if (!saved.ok) console.warn(`contact ${id} not updated: ${saved.status}`)
}

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('close-sig-timestamp') ?? ''
  const signature = request.headers.get('close-sig-hash') ?? ''
  if (!(await signatureIsValid(env, timestamp, rawBody, signature))) return new Response(null, { status: 401 })

  const { event } = JSON.parse(rawBody)
  if (event?.object_type !== 'contact' || event.action !== 'created') return new Response(null, { status: 204 })

  waitUntil(checkContact(env, event.object_id).catch((error) => console.error(`contact check failed: ${error.name}`)))
  return new Response(null, { status: 204 })
}

Close signs each event with an HMAC-SHA256 of the close-sig-timestamp header followed by the raw body, keyed with the subscription's hex signature key, and sends the hex digest in close-sig-hash. The handler checks it on the raw text before parsing anything.

It answers at once and works in the background. Close counts a delivery as failed when it gets no 2xx answer within its time limit (15 seconds in its current docs) and retries with backoff, so the mail server check must never hold the answer. The handler only trusts event.object_id and reads the contact itself, so it always works on current data.

mode: 'full' runs the mailbox check, the only way to get deliverable. If your host stops background work early, switch to mode: 'fast', which skips the mailbox and answers unknown with smtp_not_checked when the other checks pass. See the email reference. A number saved with a + prefix is read as it is; DEFAULT_COUNTRY tells the API how to read the others. See the phone reference.

3. Deploy it with its secrets

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

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

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

On Vercel the entry file is api/close.js, with "type": "module" in package.json. Store as secrets (wrangler secret put or vercel env add): QELKA_API_KEY, CLOSE_API_KEY, EMAIL_STATUS_FIELD and PHONE_CHECK_FIELD (the two cf_ ids), optionally DEFAULT_COUNTRY, and, after the next step, CLOSE_SIGNATURE_KEY.

4. Subscribe to created contacts

Create the subscription with Close's webhook API, pointing at your deployed URL:

bash
curl https://api.close.com/api/v1/webhook/ \
  -u "$CLOSE_API_KEY:" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://your-handler.example.com/", "events": [{"object_type": "contact", "action": "created"}]}'

The response holds the subscription id, its status and a signature_key. Store the key as the CLOSE_SIGNATURE_KEY secret and redeploy. Until then, every event is refused with 401 and retried by Close.

5. Test it

With a sk_test_ key, add a contact with the email disposable@example.com to any lead. Email status reads risky a few seconds later. undeliverable@example.com gives undeliverable and any other well-formed address deliverable; phone numbers are parsed for real. Then swap in a live key.

6. Use the result

Build Smart Views on the two fields:

Email status Meaning Suggested action
undeliverable Bad syntax, no domain, or the mailbox was refused Keep the contact out of sequences, find a correct address
risky Disposable inbox, catch-all domain or full mailbox Review before enrolling
deliverable The mail server accepted the mailbox Nothing to do
unknown or unchecked Not conclusive, or the API was unreachable Keep the contact, check again later

An unknown email is not a bad email: never delete a contact on it. Phone check holds the E.164 number when it is valid, or invalid, unknown or unchecked. See Format phone numbers in E.164.

Handle errors and rate limits

Every API problem ends as unchecked, logged with the error type and the X-Request-Id, and never touches the rest of the contact. 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; a large lead import can exceed it, so check imported files with a bulk file check. Each email check costs 1 credit and each basic phone check 1. See Errors and Rate limits.

On Close's side, a subscription whose deliveries keep failing is paused after some days, according to its docs, and must be reactivated through the API. Watch the handler's 401 responses: they usually mean the signature key is missing or belongs to another subscription.

Frequently asked questions

Why create the webhook with Close's API?
Close documents webhook subscriptions as an API resource, and the response to the creation call is where you get the signature key that signs every event. Store it as a secret right away: the handler needs it to reject requests that do not come from Close.
Will writing the custom fields trigger the webhook again?
No. The subscription listens to created contacts only, and the handler's update is an updated event. The handler also reads the contact first and stops when a status is already stored, so a redelivered event, which Close may send more than once and in any order, costs nothing.
Can I check contacts that already exist in Close?
Yes. Export them, run a bulk file check, and import the statuses back into the same custom fields. Sending existing contacts through the handler one by one works too, but mind the rate limits of both APIs and the credits each check costs.

More in CRM

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