How to Check New Sign-Ups' Phones and Emails by API

How to Check New Sign-Ups' Phones and Emails by API

You can check every new sign-up's phone number and email address by API, but not one at a time while the form waits. A verification order runs in the background and every order is billed as at least 2,000 entries, so the pattern that works is this: validate the format instantly in your own code, let the account in, queue its phone and email, and send the whole queue as one order every hour or every day. Then act on the results: ask for a new number, flag the account for review, or hold the free trial until it passes.

This guide is for developers at a business checking its own sign-ups, with a queue table and a batch job in Python. The signals that give a fake account away are in How to Detect Fake Sign-Ups With Phone and Email Checks; this is how to wire the checks into your own code.

Why not check each sign-up as it arrives?#

Three things about the TalismanLeads API make one order per sign-up the wrong design.

  • Orders take minutes. You ask for a price, place the order, then follow its status until it finishes, as Quote, Order, Follow: How an Asynchronous Verification Job Works explains. A sign-up form cannot wait that long.
  • Every order is billed as at least 2,000 entries. One email on the Email Deliverability Checker costs $1.80, exactly what 2,000 emails cost. A day of 300 sign-ups checked one by one is 300 orders at that price; checked as one batch, it is one order at $1.80.
  • New orders are rate-limited. At the time of writing an account can place 10 new orders a minute. A burst of sign-ups would soon be answered with 429; see API Rate Limits and 429 Errors.

GET /v1/checkers returns the minimum for each checker as minimum_billed_entries, beside minimum_entries, the fewest entries a checker accepts at all (zero for most), and every estimate shows billed_entries before anything is charged:

cURL
curl "https://api.talismanleads.io/v1/checkers" \
  -H "Authorization: Bearer $TALISMANLEADS_API_KEY"
JSON
{
  "checkers": [
    {
      "id": "global_carrier_checker",
      "name": "Number Carrier Lookup",
      "input": "phone",
      "price": { "amount": "1.20", "per_entries": 10000, "currency": "USD" },
      "minimum_entries": 0,
      "minimum_billed_entries": 2000,
      "calling_code": null
    }
  ]
}

That is an example answer, cut to one checker. Read the figures from your own account: some checkers have a higher floor.

Check the format at the form, in your own code#

What must happen in real time happens on your own server, instantly and at no cost.

  • Phone numbers. Parse them with libphonenumber (phonenumbers in Python, libphonenumber-js in Node.js), using the country of your form as the default, refuse what cannot exist, and store the rest in E.164 format, such as +14155550142. This matters again later: one line that is not a valid entry refuses a whole API order with invalid_entries, so only clean E.164 numbers should reach the queue.
  • Email addresses. Check the syntax and store them in lower case. The API has no checker for disposable or role addresses (admin@, sales@), so keep your own list; the open-source disposable-email-domains list is a good start. Catch-All, Disposable and Role Emails explains what to do with each.
  • A confirmation link. Send one to every new address. It is the only check that proves the person reads that inbox.
Python
"""Instant checks at the sign-up form, in your own code. Nothing leaves your server."""
import re

import phonenumbers  # pip install phonenumbers

EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[a-z]{2,}$")
ROLE = {"admin", "billing", "contact", "info", "noreply", "no-reply", "office", "sales", "support"}
# One domain per line, such as the open-source disposable-email-domains list.
with open("disposable_domains.txt") as f:
    DISPOSABLE = set(f.read().split())


def check_form(phone_raw, email_raw, region="US"):
    """Returns (phone, country, email, problems, flags). Ask again at once for a problem."""
    problems, flags = [], []
    phone = country = None
    try:
        number = phonenumbers.parse(phone_raw, region)
        if phonenumbers.is_valid_number(number):
            phone = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164)
            country = phonenumbers.region_code_for_number(number)
    except phonenumbers.NumberParseException:
        pass
    if phone is None:
        problems.append("phone")

    email = email_raw.strip().lower()
    local, _, domain = email.partition("@")
    if not EMAIL.match(email):
        problems.append("email")
    if domain in DISPOSABLE:
        flags.append("disposable")
    if local in ROLE:
        flags.append("role")
    return phone, country, email, problems, flags


def queue_for_checks(db, user_id, phone, country, email):
    """The account is open; its details wait for the next batch."""
    db.execute("INSERT INTO signup_checks (user_id, kind, value, country) VALUES (?, 'phone', ?, ?)",
               (user_id, phone, country))
    db.execute("INSERT INTO signup_checks (user_id, kind, value) VALUES (?, 'email', ?)", (user_id, email))
    db.commit()

A problem means the form asks again straight away. A flag, or nothing at all, lets the account in: hold back only what can be abused, such as trial credit, a referral bonus or a large coupon, until the batch has checked the account.

There is one thing libphonenumber cannot tell you. For (415) 555-0142 it answers "fixed line or mobile", because US landlines, mobiles and VoIP lines share area codes. Telling them apart is the batch check's job.

Which checkers to run by API#

Two checkers cover a sign-up's phone and email. Nobody is called, texted or emailed while they run.

  • Number Carrier Lookup (global_carrier_checker, $1.20 per 10,000 numbers). It returns one CSV with the columns Input, Number, Valid, Country, Country name, Line type, Carrier and Location. Valid is yes or no, and Line type is one of mobile, fixed (a landline), fixedOrMobile, voip, tollFree, premium or other. For +1 numbers our lookup reads the carrier and line type of the number's block from the public NANPA and Canadian (CNAC) assignment files, which is how it can label a US number mobile, landline or VoIP where libphonenumber cannot. It reads ranges, so a ported number shows the carrier that first held its block.
  • Email Deliverability Checker (email_deliverability_checker, $9.00 per 10,000 emails). It confirms whether each mailbox exists, and returns a zip whose all.csv holds the address and activated, yes or no. It covers Gmail, Yahoo, Outlook, iCloud, Yandex and Mail.ru only; other addresses are left out and not charged. A sign-up at a company domain therefore gets no answer: treat it as unknown and rely on the confirmation link.

Phone orders take one country each (at least 90% of a list), so the queue groups numbers by country.

A queue table and a batch job#

The job keeps two tables: one row per phone or email waiting to be checked, and one row per batch, holding the batch's Idempotency-Key from before anything is sent.

When should a batch go? Whichever comes first: 2,000 entries waiting, since a smaller order costs the same, or the oldest entry waiting a set time. With fewer than 2,000 sign-ups a day, a daily batch costs one minimum charge a day per checker, $0.24 for phones and $1.80 for emails. An hourly batch can cost that 24 times over. Choose the wait by weighing a trial held for up to a day against up to 23 extra minimum charges.

Save this as signup_checks.py, set TALISMANLEADS_API_KEY (a key that can place orders; see API Key Security) and run it from cron every hour, for example 0 * * * * python3 signup_checks.py. It needs the requests package and uses SQLite so it runs anywhere; the same two tables work in PostgreSQL or MySQL with their own date functions.

Python
"""Check new sign-ups' phones and emails in batches with the TalismanLeads API.

Run it every hour from cron. Each run places an order for every group of
waiting sign-ups that is big enough or has waited long enough, follows the
orders, and writes a verdict for each sign-up. Safe to stop and run again:
a batch keeps its Idempotency-Key, so it is never ordered or charged twice.
"""
import csv
import io
import os
import sqlite3
import time
import uuid
import zipfile

import requests

API = os.environ.get("TALISMANLEADS_API_URL", "https://api.talismanleads.io/v1")
AUTH = {"Authorization": f"Bearer {os.environ['TALISMANLEADS_API_KEY']}"}
CHECKER = {"phone": "global_carrier_checker", "email": "email_deliverability_checker"}
FLUSH_AT = 2000        # every order is billed as at least 2,000 entries
MAX_WAIT_HOURS = 24    # ...so a smaller group waits at most this long
FINISHED = {"completed", "partially_completed", "failed"}

SCHEMA = """
CREATE TABLE IF NOT EXISTS signup_checks (
  id         INTEGER PRIMARY KEY,
  user_id    INTEGER NOT NULL,
  kind       TEXT NOT NULL,                   -- 'phone' or 'email'
  value      TEXT NOT NULL,                   -- '+14155550142' or 'jane@example.com'
  country    TEXT NOT NULL DEFAULT '',        -- phones: one country per order
  status     TEXT NOT NULL DEFAULT 'pending', -- pending, ordered, done
  batch_id   INTEGER,
  verdict    TEXT,                            -- ok, review, ask_again, unknown
  detail     TEXT,                            -- the line type or mailbox answer
  created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS check_batches (
  id              INTEGER PRIMARY KEY,
  checker         TEXT NOT NULL,
  idempotency_key TEXT NOT NULL UNIQUE,
  expected_charge TEXT,
  order_id        TEXT,
  status          TEXT NOT NULL DEFAULT 'open'  -- open, done
);
"""


def call(method, path, json=None, headers=None):
    """One API request, waiting and repeating it when the API says to."""
    for _ in range(10):
        r = requests.request(method, API + path, json=json,
                             headers={**AUTH, **(headers or {})}, timeout=330)
        try:
            body = r.json()
        except ValueError:
            body = None  # a gateway's 502 or 504 page is not JSON
        if r.ok:
            return body
        if r.status_code == 429:
            wait = r.headers.get("Retry-After", "")
            time.sleep(int(wait) if wait.isdigit() else 30)
            continue
        error = (body or {}).get("error", {})
        if body is None or error.get("code") in ("order_status_unknown", "service_unavailable"):
            time.sleep(60)  # the same request with the same key never charges twice
            continue
        raise ApiError(error.get("code"), error.get("message"), error.get("request_id"))
    raise ApiError("no_answer", f"No answer from {path}", None)


class ApiError(Exception):
    def __init__(self, code, message, request_id):
        super().__init__(f"{code}: {message} (request {request_id})")
        self.code = code


def open_batches(db):
    """Group waiting sign-ups by kind and country; start a batch for each full or old group."""
    groups = db.execute("""
        SELECT kind, country FROM signup_checks WHERE status = 'pending'
        GROUP BY kind, country
        HAVING COUNT(*) >= ? OR MIN(created_at) <= datetime('now', ?)""",
        (FLUSH_AT, f"-{MAX_WAIT_HOURS} hours")).fetchall()
    for kind, country in groups:
        # The key is saved before anything is sent, so a crash cannot lose it.
        batch = db.execute("INSERT INTO check_batches (checker, idempotency_key) VALUES (?, ?)",
                           (CHECKER[kind], f"signups-{uuid.uuid4()}")).lastrowid
        db.execute("""UPDATE signup_checks SET status = 'ordered', batch_id = ?
                      WHERE id IN (SELECT id FROM signup_checks WHERE status = 'pending'
                                   AND kind = ? AND country = ? ORDER BY id LIMIT 100000)""",
                   (batch, kind, country))
        db.commit()


def read_rows(file_bytes):
    """The result as dicts with lower-case column names: a zip holding all.csv, or a CSV."""
    if file_bytes[:2] == b"PK":
        with zipfile.ZipFile(io.BytesIO(file_bytes)) as z:
            names = [n for n in z.namelist() if n.lower().endswith(".csv")]
            name = next((n for n in names if n.lower().endswith("all.csv")), names[0])
            file_bytes = z.read(name)
    reader = csv.DictReader(io.StringIO(file_bytes.decode("utf-8-sig")))
    return [{(k or "").strip().lower(): (v or "").strip() for k, v in row.items()} for row in reader]


def verdict(kind, row):
    """Turn one result row into what to do about the sign-up."""
    if kind == "phone":
        line_type = row.get("line type", "")
        if row.get("valid") != "yes":
            return "ask_again", "not a valid number"
        if line_type in ("fixed", "tollFree", "premium"):
            return "ask_again", line_type        # cannot receive a text code
        if line_type in ("voip", "other"):
            return "review", line_type           # a reason to look closer, not proof
        return "ok", line_type                   # mobile, fixedOrMobile
    answer = row.get("activated", "").lower()
    if answer == "no":
        return "ask_again", "mailbox does not exist"
    return ("ok", "mailbox exists") if answer == "yes" else ("unknown", answer)


def run_batch(db, batch_id):
    checker, key, expected, order_id = db.execute(
        "SELECT checker, idempotency_key, expected_charge, order_id FROM check_batches WHERE id = ?",
        (batch_id,)).fetchone()
    rows = db.execute("SELECT id, kind, value FROM signup_checks WHERE batch_id = ? ORDER BY id",
                      (batch_id,)).fetchall()
    entries = [value for _, _, value in rows]

    if order_id is None:
        if expected is None:  # 1. See the price once, and keep it with the batch.
            expected = call("POST", "/estimates", json={"checker": checker, "entries": entries})["charge"]
            db.execute("UPDATE check_batches SET expected_charge = ? WHERE id = ?", (expected, batch_id))
            db.commit()
        try:  # 2. Order. A re-run sends the very same request and key: one order, one charge.
            order = call("POST", "/orders", headers={"Idempotency-Key": key},
                         json={"checker": checker, "entries": entries, "expected_charge": expected})
        except ApiError as e:
            if e.code == "price_changed":  # nothing was placed: quote again under a new key
                db.execute("UPDATE check_batches SET idempotency_key = ?, expected_charge = NULL WHERE id = ?",
                           (f"signups-{uuid.uuid4()}", batch_id))
                db.commit()
            raise  # insufficient_balance: top up, and the next run repeats this order
        order_id = order["id"]
        db.execute("UPDATE check_batches SET order_id = ? WHERE id = ?", (order_id, batch_id))
        db.commit()

    # 3. Follow the order. One you do not finish now is picked up on the next run.
    for _ in range(60):
        order = call("GET", f"/orders/{order_id}")
        if order["status"] in FINISHED:
            break
        time.sleep(30)
    else:
        return

    # 4. Read the results. The links carry their own permission: no API key.
    results = {}
    for part in call("GET", f"/orders/{order_id}/results")["parts"]:
        if part.get("url"):
            for row in read_rows(requests.get(part["url"], timeout=300).content):
                entry = row.get("input") or row.get("email") or next(iter(row.values()), "")
                results[entry.lower()] = row

    for check_id, kind, value in rows:
        row = results.get(value.lower())
        if row:
            v, detail = verdict(kind, row)
        elif order["status"] == "completed":
            v, detail = "unknown", "not in the result"  # e.g. a mailbox provider not covered
        else:  # a failed part was refunded: queue these again
            db.execute("UPDATE signup_checks SET status = 'pending', batch_id = NULL WHERE id = ?", (check_id,))
            continue
        db.execute("UPDATE signup_checks SET status = 'done', verdict = ?, detail = ? WHERE id = ?",
                   (v, detail, check_id))
    db.execute("UPDATE check_batches SET status = 'done' WHERE id = ?", (batch_id,))
    db.commit()


if __name__ == "__main__":
    db = sqlite3.connect(os.environ.get("SIGNUPS_DB", "signups.db"))
    db.executescript(SCHEMA)
    open_batches(db)
    for (batch_id,) in db.execute("SELECT id FROM check_batches WHERE status = 'open'").fetchall():
        run_batch(db, batch_id)

Four choices in it keep your money safe:

  • The key and the price are saved with the batch. A repeated order must be the very same request: under the same key, a different list or expected_charge is refused with idempotency_conflict. So a run that crashes, or stops at insufficient_balance, repeats the identical order next time, and it is placed once. Only price_changed, where nothing was placed, earns a new key. Idempotency Keys: How to Retry an API Request Without Paying Twice explains why.
  • Lost answers are repeated, not replaced. A 502 page or order_status_unknown means the job asks again with the same key. Every other code is listed in Verification API Errors.
  • Failed parts go back in the queue. A part that fails is refunded in full, so its sign-ups simply wait for the next batch.
  • Columns are read by name. New columns can be added to a result file at any time.

We ran the job against a stand-in for the API that answered with rate limits, a low balance, a changed price and an order placed whose answer was lost behind a 502 page. Each batch was placed and charged once, and a later run placed nothing new.

Act on the results#

Each sign-up now has a verdict. The rules are yours; here is a sensible start.

  • Ask again. A number that cannot exist, a landline or toll-free number in a mobile field, or a mailbox that does not exist is usually a mistake, not fraud. Ask the customer to correct it at their next login or in an email, and hold the trial until they do.
  • Review. A VoIP number is a reason to look closer, never proof: many real customers use one. Weigh it with the other signals in the fake sign-ups guide.
  • Unknown. An address the check does not cover gets no verdict. The confirmation link decides.
  • Release. When every check of an account is done and none asks for action, release what you held:
SQL
-- Accounts whose checks are all done, with nothing to ask or review.
SELECT user_id FROM signup_checks
GROUP BY user_id
HAVING SUM(CASE WHEN status <> 'done' OR verdict IN ('ask_again', 'review') THEN 1 ELSE 0 END) = 0;

Keep each verdict with the date it was checked. From Results File to CRM shows how to carry results into your other systems, and Re-Checking a Customer List on a Schedule covers checking the same customers again later.

Frequently asked questions#

Can I verify a phone number at sign-up in real time with the API?#

Not usefully. An order runs in the background for minutes and is billed as at least 2,000 entries. Check the format in real time with libphonenumber in your own code, and check line type and carrier in an hourly or daily batch.

How often should the batch run?#

Send a batch when 2,000 entries are waiting or when the oldest has waited as long as you accept, often a day. Under 2,000 sign-ups a day, an hourly batch costs up to 24 minimum charges a day per checker instead of one.

What does checking a single sign-up cost?#

The same as 2,000 entries: $0.24 for one phone number on the Number Carrier Lookup and $1.80 for one email on the Email Deliverability Checker. POST /v1/estimates shows the exact charge, free, before you order.

Does the API flag disposable or role email addresses?#

No. Check them in your own code against a disposable-domain list and a list of role names such as admin@ and sales@. The Email Deliverability Checker answers whether a mailbox exists at the providers it covers.

Are my users contacted when they are checked?#

No. The carrier lookup reads numbering data and the email check sends nothing to the mailbox. Nobody is called, texted or emailed.

What if my sign-ups come from several countries?#

Put phone numbers from one country in each order. The job above groups the queue by country, so each country becomes its own batch. Emails have no such rule.

Businesses can try this on their own sign-ups with a $5, 14-day free trial; trial accounts have lower API limits until their first top-up. Create a key under API keys and run your first estimate on yesterday's sign-ups; the full reference is in the API documentation.

Was this helpful?