Skip to content

Automation

Validate data from any webhook, and receive Qelka webhooks

Receive a form or CRM webhook, verify its signature, validate the email and phone in it, then receive and verify Qelka's own signed bulk and credit events.

Updated 2026-11-26

Some tools can only send a webhook: a form builder, a CRM, a payment page. This recipe is for that case, with no automation platform in between. A small endpoint of your own receives the webhook, checks that it really comes from the sender, validates the email and phone in it, and forwards or stores the result. The second half covers the other direction: receiving Qelka's own webhooks when a bulk job ends or your credits run low, and verifying their signature.

What you need

  • A server that the sender can reach over HTTPS: any Node.js 20+ or Python 3.10+ host, or a serverless function. During development, expose your machine through an HTTPS tunnel.
  • A Qelka API key in the QELKA_API_KEY environment variable. A sk_test_ key returns simulated results and never spends credits: see Test mode. Restrict the key to /email and /phone: see Restricted keys.
  • The signing secret of the sender's webhook, in SENDER_SECRET, and, for the second half, the signing secret of your Qelka webhook endpoint in WEBHOOK_SECRET.

Part 1: validate the data in any webhook

How senders sign their webhooks

Most form and CRM tools sign each webhook with an HMAC-SHA256 of the raw request body, keyed with a secret you set or copy when you create the webhook. What differs is the header name, the encoding of the digest (hex or base64) and sometimes a prefix. Typeform, for example, sends Typeform-Signature: sha256= followed by the base64 digest. Read your sender's webhook documentation for those three values and set them as environment variables:

Variable Typeform's value What it is
SENDER_SIGNATURE_HEADER Typeform-Signature The header that carries the signature
SENDER_SIGNATURE_PREFIX sha256= Text before the digest, empty if none
SENDER_SIGNATURE_ENCODING base64 base64 or hex

Some senders sign a timestamp together with the body, as Qelka does in Part 2; use that code shape for them. If a sender cannot sign at all, put a long random token in the webhook URL and compare it in constant time: it is weaker, but it still keeps strangers out.

The endpoint

The endpoint verifies the signature against the raw bytes, answers at once, then does the slow work: senders give up after a few seconds, and an answer that comes late makes them retry. Because the check runs after the answer, it can afford a full email check, which waits for the recipient's mail server and is the only mode that can answer deliverable.

The example reads email, phone, country and id at the top level of the JSON. Most senders nest their fields: adapt readContact to your sender's payload, such as the form_response.answers list of Typeform.

import express from 'express'
import { createHash, createHmac, timingSafeEqual } from 'node:crypto'

const sender = {
  secret: process.env.SENDER_SECRET,
  header: process.env.SENDER_SIGNATURE_HEADER ?? 'Typeform-Signature',
  prefix: process.env.SENDER_SIGNATURE_PREFIX ?? 'sha256=',
  encoding: process.env.SENDER_SIGNATURE_ENCODING ?? 'base64',
}
const retryable = new Set([429, 500, 502])
const handled = new Set()

function senderSignatureIsValid(rawBody, received) {
  if (!received || !sender.secret) return false
  const expected = sender.prefix + createHmac('sha256', sender.secret).update(rawBody).digest(sender.encoding)
  const receivedBytes = Buffer.from(received)
  const expectedBytes = Buffer.from(expected)
  return receivedBytes.length === expectedBytes.length && timingSafeEqual(receivedBytes, expectedBytes)
}

function readContact(payload) {
  return { id: payload.id, email: payload.email, phone: payload.phone, country: payload.country }
}

async function callApi(path, body) {
  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 ${process.env.QELKA_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(body),
        signal: AbortSignal.timeout(15000),
      })
    } catch (error) {
      console.warn(`validation skipped: ${error.name}`)
      return null
    }
    if (response.ok) return response.json()
    if (retryable.has(response.status) && attempt < 2) {
      const retryAfter = Number(response.headers.get('Retry-After'))
      await new Promise((resolve) => setTimeout(resolve, Math.min(retryAfter > 0 ? retryAfter : 1, 5) * 1000))
      continue
    }
    const failure = await response.json().catch(() => ({}))
    console.warn(`validation skipped: ${failure.error?.type ?? response.status} request ${response.headers.get('X-Request-Id')}`)
    return null
  }
  return null
}

async function processContact(contact) {
  const result = { id: contact.id, email_status: 'unchecked', did_you_mean: null, phone_status: 'unchecked', e164: null }
  if (typeof contact.email === 'string' && contact.email.trim()) {
    const email = await callApi('/email', { email: contact.email.trim() })
    if (email) Object.assign(result, { email_status: email.status, did_you_mean: email.did_you_mean })
  }
  if (typeof contact.phone === 'string' && contact.phone.trim()) {
    const body = { phone: contact.phone.trim(), ...(contact.country ? { country: contact.country } : {}) }
    const phone = await callApi('/phone', body)
    if (phone) Object.assign(result, { phone_status: phone.status, e164: phone.e164 })
  }
  if (!process.env.FORWARD_URL) return console.log(result)
  await fetch(process.env.FORWARD_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(result),
    signal: AbortSignal.timeout(10000),
  })
}

const app = express()

app.post('/inbound', express.raw({ type: '*/*', limit: '1mb' }), (req, res) => {
  const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0)
  if (!senderSignatureIsValid(rawBody, req.get(sender.header))) return res.status(401).send('Invalid signature')
  let payload
  try {
    payload = JSON.parse(rawBody.toString('utf8'))
  } catch {
    return res.status(400).send('Invalid JSON')
  }
  res.status(204).end()
  const deliveryId = createHash('sha256').update(rawBody).digest('hex')
  if (handled.has(deliveryId)) return
  handled.add(deliveryId)
  processContact(readContact(payload)).catch((error) => console.error('processing failed', error))
})

app.listen(3000)
import base64
import hashlib
import hmac
import json
import os
import threading
import time

import requests
from flask import Flask, request

app = Flask(__name__)
API_KEY = os.environ["QELKA_API_KEY"]
SENDER_SECRET = os.environ["SENDER_SECRET"]
SENDER_HEADER = os.environ.get("SENDER_SIGNATURE_HEADER", "Typeform-Signature")
SENDER_PREFIX = os.environ.get("SENDER_SIGNATURE_PREFIX", "sha256=")
SENDER_ENCODING = os.environ.get("SENDER_SIGNATURE_ENCODING", "base64")
FORWARD_URL = os.environ.get("FORWARD_URL")
RETRYABLE = {429, 500, 502}
handled = set()
handled_lock = threading.Lock()


def sender_signature_is_valid(raw_body: bytes, received: str | None) -> bool:
    if not received:
        return False
    digest = hmac.new(SENDER_SECRET.encode(), raw_body, hashlib.sha256).digest()
    encoded = base64.b64encode(digest).decode() if SENDER_ENCODING == "base64" else digest.hex()
    return hmac.compare_digest((SENDER_PREFIX + encoded).encode(), received.encode())


def read_contact(payload: dict) -> dict:
    return {key: payload.get(key) for key in ("id", "email", "phone", "country")}


def call_api(path: str, body: dict) -> dict | None:
    for attempt in (1, 2):
        try:
            response = requests.post(
                f"https://api.qelka.com/v1{path}",
                headers={"Authorization": f"Bearer {API_KEY}"},
                json=body,
                timeout=15,
            )
        except requests.RequestException as error:
            app.logger.warning("validation skipped: %s", type(error).__name__)
            return None
        if response.ok:
            return response.json()
        if response.status_code in RETRYABLE and attempt == 1:
            retry_after = response.headers.get("Retry-After", "")
            time.sleep(min(int(retry_after), 5) if retry_after.isdigit() else 1)
            continue
        try:
            error_type = response.json()["error"]["type"]
        except (ValueError, KeyError, TypeError):
            error_type = str(response.status_code)
        app.logger.warning("validation skipped: %s request %s", error_type, response.headers.get("X-Request-Id"))
        return None
    return None


def process_contact(contact: dict) -> None:
    result = {"id": contact["id"], "email_status": "unchecked", "did_you_mean": None, "phone_status": "unchecked", "e164": None}
    if isinstance(contact["email"], str) and contact["email"].strip():
        email = call_api("/email", {"email": contact["email"].strip()})
        if email:
            result.update(email_status=email["status"], did_you_mean=email["did_you_mean"])
    if isinstance(contact["phone"], str) and contact["phone"].strip():
        body = {"phone": contact["phone"].strip()}
        if contact["country"]:
            body["country"] = contact["country"]
        phone = call_api("/phone", body)
        if phone:
            result.update(phone_status=phone["status"], e164=phone["e164"])
    if FORWARD_URL:
        requests.post(FORWARD_URL, json=result, timeout=10)
    else:
        app.logger.info("result %s", result)


@app.post("/inbound")
def receive_inbound():
    raw_body = request.get_data()
    if not sender_signature_is_valid(raw_body, request.headers.get(SENDER_HEADER)):
        return "Invalid signature", 401
    try:
        payload = json.loads(raw_body)
    except ValueError:
        return "Invalid JSON", 400
    delivery_id = hashlib.sha256(raw_body).hexdigest()
    with handled_lock:
        if delivery_id in handled:
            return "", 204
        handled.add(delivery_id)
    threading.Thread(target=process_contact, args=(read_contact(payload),), daemon=True).start()
    return "", 204


if __name__ == "__main__":
    app.run(port=3000)

The Node.js version needs Express (npm install express), the Python version Flask and Requests (pip install flask requests).

A few choices in that code are deliberate:

  • The raw body is verified before anything parses it. Parsing and serializing JSON again changes the bytes and breaks every signature. In Express, the route uses express.raw(); keep a global express.json() away from it.
  • The API never blocks the webhook. The sender gets its 204 before any check runs. A check that times out or fails leaves unchecked in the result and logs the error type with the X-Request-Id, so the record still moves on.
  • Repeats are skipped. Senders retry when they think a delivery failed, so the same body can arrive twice. The example remembers a hash of each body in memory; in production, store the sender's own delivery id in your database, and run the checks from a job queue rather than a thread.

Test it

Sign a sample body with your secret the way the sender would, then post it. For Typeform's scheme:

bash
BODY='{"id":"test-1","email":"undeliverable@example.com","phone":"(415) 555-0123","country":"US"}'
SIGNATURE="sha256=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SENDER_SECRET" -binary | base64)"
curl -i http://localhost:3000/inbound \
  -H "Content-Type: application/json" \
  -H "Typeform-Signature: $SIGNATURE" \
  --data-binary "$BODY"

The endpoint answers 204, and with a test key the logged result says undeliverable for the email and gives +14155550123 as e164. Change one character of BODY after signing and the answer becomes 401.

Act on the result

Field Value What to do
email_status undeliverable Mark the contact, and offer did_you_mean when it is set
email_status risky Disposable inbox, catch-all domain or full mailbox: send to review
email_status deliverable or unknown Keep the contact; confirm an unknown by email
email_status unchecked The API could not answer: check again later
phone_status valid Store e164
phone_status invalid or unknown Ask for a correction; unknown means no + and no country

See the email reference and the phone reference for every reason and line type.

Part 2: receive Qelka webhooks

Qelka sends a signed POST to your endpoint for two events:

Event Sent when data holds
bulk.completed A bulk job ends, whether it completed or failed The bulk job object, the same one GET /bulk/{id} returns
credits.low Your credit balance drops under 10% of your plan's monthly credits org_id, balance and threshold

Add the endpoint in the dashboard, under Webhooks, with Add endpoint: the URL must start with https://, and you pick at least one event. Copy the signing secret right away. It starts with whsec_ and is shown only once.

Verify the signature

Each delivery carries X-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">, keyed with the endpoint's signing secret, the whole string including whsec_, as UTF-8 bytes. Read the raw body before any parsing, reject a t more than 300 seconds away from your clock, and compare each v1 in constant time.

import express from 'express'
import { createHmac, timingSafeEqual } from 'node:crypto'

const seenEvents = new Set()

function verifySignature(rawBody, header, secret, toleranceSeconds = 300) {
  if (!header) return false
  let timestamp = null
  const signatures = []
  for (const part of header.split(',')) {
    const [key, value] = part.trim().split('=', 2)
    if (key === 't' && /^\d+$/.test(value ?? '')) timestamp = Number(value)
    if (key === 'v1' && value) signatures.push(value)
  }
  if (timestamp === null || signatures.length === 0) return false
  if (Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false
  const expected = createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest('hex')
  return signatures.some(
    (signature) => signature.length === expected.length && timingSafeEqual(Buffer.from(signature), Buffer.from(expected)),
  )
}

async function handleEvent(event) {
  if (event.type === 'credits.low') {
    console.warn(`Credit balance ${event.data.balance} is under ${event.data.threshold}`)
  } else if (event.type === 'bulk.completed' && event.data.status === 'completed') {
    const results = await fetch(event.data.download_url, { signal: AbortSignal.timeout(60000) })
    console.log(`Bulk job ${event.data.id} done:`, (await results.text()).length, 'characters of results')
  } else if (event.type === 'bulk.completed') {
    console.warn(`Bulk job ${event.data.id} failed: ${event.data.error}`)
  }
}

const app = express()

app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0)
  if (!verifySignature(rawBody, req.get('X-Signature'), process.env.WEBHOOK_SECRET)) {
    return res.status(400).send('Invalid signature')
  }
  const event = JSON.parse(rawBody.toString('utf8'))
  res.status(204).end()
  if (seenEvents.has(event.id)) return
  seenEvents.add(event.id)
  handleEvent(event).catch((error) => console.error(error))
})

app.listen(3000)
import hashlib
import hmac
import json
import os
import time

from flask import Flask, request

app = Flask(__name__)
WEBHOOK_SECRET = os.environ["WEBHOOK_SECRET"]
seen_events = set()


def verify_signature(raw_body: bytes, header: str | None, secret: str, tolerance: int = 300) -> bool:
    if not header:
        return False
    timestamp = None
    signatures = []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t" and value.isascii() and value.isdigit():
            timestamp = value
        elif key == "v1" and value:
            signatures.append(value)
    if timestamp is None or not signatures:
        return False
    if abs(time.time() - int(timestamp)) > tolerance:
        return False
    message = timestamp.encode() + b"." + raw_body
    expected = hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected.encode(), signature.encode()) for signature in signatures)


@app.post("/webhooks")
def receive_webhook():
    raw_body = request.get_data()
    if not verify_signature(raw_body, request.headers.get("X-Signature"), WEBHOOK_SECRET):
        return "Invalid signature", 400
    event = json.loads(raw_body)
    if event["id"] in seen_events:
        return "", 204
    seen_events.add(event["id"])
    if event["type"] == "credits.low":
        app.logger.warning("Credit balance %s is under %s", event["data"]["balance"], event["data"]["threshold"])
    elif event["type"] == "bulk.completed":
        app.logger.warning("Bulk job %s ended: %s", event["data"]["id"], event["data"]["status"])
    return "", 204


if __name__ == "__main__":
    app.run(port=3000)

The webhooks reference has the same check in PHP, Go and Ruby, and a known secret, timestamp and body with the HMAC they must produce, to test your code on its own.

Answer fast, and expect repeats

  • Answer 2xx within 10 seconds. Anything else is a failure: a 4xx or 5xx, a timeout, a refused connection, a DNS or TLS error. Redirects are not followed, so register the final URL. Downloading a large result file can take longer than 10 seconds, which is why the Node.js version answers first and works after.
  • Retries: a failed delivery is retried up to 5 times, after 1 minute, 5 minutes, 30 minutes, 2 hours and 6 hours. After the sixth failed attempt, the event is dropped. Each attempt is signed again with a new t.
  • Duplicates and order: every attempt of an event has the same id, so skip ids you have handled; the in-memory sets above are for the example, a database table is the real thing. Events can also arrive out of order after retries: rely on created_at and on the state in data, such as the job's status.
  • What to do with each event: for bulk.completed with status completed, download download_url, a signed link valid for 24 hours that needs no API key; if it expired, GET /bulk/{id} returns a fresh one. With status failed, read error; the reserved credits are back on your balance. For credits.low, alert whoever manages billing: calls the balance cannot cover fail with 402 insufficient_credits and are not billed.

The User-Agent header, Qelka-Webhooks/1.0, helps you find deliveries in your logs, but anyone can send it: only the signature proves the origin. Test keys never trigger events, and the dashboard has no test button, so sign a sample event yourself as the webhooks reference shows, or run a small live bulk job.

Handle errors and rate limits

In Part 1, no API error is billed. 401 invalid_api_key and 403 forbidden mean a wrong or restricted key, 402 insufficient_credits an empty balance: the endpoint keeps answering the sender, logs the error type, and leaves unchecked in the result, so watch your logs for those three. A 429 rate_limited or a 500 or 502 is retried once, after Retry-After for a 429. A key allows 200 requests per 10 seconds; a burst of webhooks from an import can pass it, which a job queue with fixed concurrency smooths out. See Errors and Rate limits.

Each email check costs 1 credit and each basic phone check 1. Store the result with the record so a repeated webhook does not pay twice. For a whole export, a bulk job is cheaper on requests, and its bulk.completed event tells your endpoint when the results are ready.

Frequently asked questions

Which events does Qelka send by webhook?
Two: bulk.completed when a bulk job ends, whether it completed or failed, and credits.low when your balance drops under 10% of your plan's monthly credits. Single checks never trigger a webhook, because their answer comes back in the HTTP response of the call. Test keys never trigger events either.
How do I verify a Qelka webhook?
Read the X-Signature header: t is the Unix time in seconds when the request was signed, and v1 the hex signature. Compute the HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with the whole signing secret including whsec_, and compare it in constant time with each v1. Reject the request if t is more than 300 seconds away from your clock.
What happens if my endpoint is down?
A delivery fails when your endpoint does not answer a 2xx status within 10 seconds, and a failed delivery is retried up to 5 times: after 1 minute, 5 minutes, 30 minutes, 2 hours and 6 hours. After the sixth failed attempt the event is dropped. Every attempt carries the same event id, so store the ids you handled and skip repeats.

More in Automation

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