如何通过 API 检测新注册用户的手机号和邮箱

如何通过 API 检测新注册用户的手机号和邮箱

您可以通过 API 检测每位新注册用户的手机号和邮箱地址,但不能在表单等待时逐个检测。检测订单在后台运行,且每个订单至少按 2,000 条计费。因此,行之有效的做法是:在您自己的代码中即时校验格式,先让账户注册成功,把手机号和邮箱放入队列,再每小时或每天把整个队列作为一个订单发送。然后根据结果采取行动:要求用户提供新号码、将账户标记为待审核,或在检测通过前暂缓发放免费试用。

本指南面向检测自家注册用户的企业开发者,内容包括一张队列表和一个 Python 批处理任务。暴露虚假账户的信号见如何通过手机号和邮箱检测识别虚假注册;本文讲的是如何把这些检测接入您自己的代码。

为什么不在每次注册时立即检测?#

TalismanLeads API 的三个特点,决定了“每次注册下一个订单”是错误的设计。

  • 订单需要几分钟。您先询价、下单,然后跟踪订单状态直到完成,详见询价、下单、跟踪:异步检测任务的工作原理。注册表单等不了这么久。
  • 每个订单至少按 2,000 条计费。在 Email Deliverability Checker 上检测一个邮箱需要 $1.80,与检测 2,000 个邮箱的费用完全相同。一天 300 个注册逐个检测,就是 300 个这个价格的订单;合成一批检测,只需一个 $1.80 的订单。
  • 新订单有速率限制。截至本文撰写时,每个账户每分钟可提交 10 个新订单。注册量一旦激增,很快就会收到 429;详见API 速率限制与 429 错误。

GET /v1/checkers 以 minimum_billed_entries 返回每个检测器的最低计费条数,旁边的 minimum_entries 是检测器可接受的最少条数(大多数为零);每次估价都会在扣费前显示 billed_entries:

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
    }
  ]
}

以上是一个示例响应,只保留了一个检测器。请以您自己账户中的数值为准:部分检测器的下限更高。

在表单环节用您自己的代码校验格式#

必须实时完成的工作,都在您自己的服务器上即时完成,不产生任何费用。

  • 手机号。使用 libphonenumber(Python 中为 phonenumbers,Node.js 中为 libphonenumber-js)解析,以表单所在国家为默认值,拒绝不可能存在的号码,其余号码以 E.164 格式保存,例如 +14155550142。这一点稍后还会用到:只要有一行不是有效条目,整个 API 订单就会以 invalid_entries 被拒绝,因此只有干净的 E.164 号码才应进入队列。
  • 邮箱地址。检查语法并以小写保存。API 没有识别一次性邮箱或角色邮箱(admin@、sales@)的检测器,所以请自行维护名单;开源的 disposable-email-domains 名单是个不错的起点。全收邮箱、一次性邮箱和角色邮箱介绍了每种邮箱的处理方法。
  • 确认链接。向每个新地址发送一封确认链接。这是唯一能证明对方确实在查看该收件箱的检测。
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()

出现问题(problem)时,表单会立即要求重新填写。带有标记(flag)或没有任何结果时,账户都可以注册:只需暂缓发放可能被滥用的东西,例如试用额度、推荐奖励或大额优惠券,直到批处理检测完该账户。

有一件事 libphonenumber 无法告诉您。对于 (415) 555-0142,它的回答是“固定电话或手机”,因为在美国,固定电话、手机和 VoIP 线路共用区号。区分它们正是批量检测的任务。

通过 API 运行哪些检测器#

两个检测器即可覆盖注册用户的手机号和邮箱。运行期间不会给任何人打电话、发短信或发邮件。

  • Number Carrier Lookup(global_carrier_checker,每 10,000 个号码 $1.20)。它返回一个 CSV,包含 Input、Number、Valid、Country、Country name、Line type、Carrier 和 Location 列。Valid 为 yes 或 no,Line type 为 mobile、fixed(固定电话)、fixedOrMobile、voip、tollFree、premium 或 other 之一。对于 +1 号码,我们的查询会从 NANPA 和加拿大(CNAC)公开的号段分配文件中读取号码所属号段的运营商和线路类型,因此能在 libphonenumber 无法区分的情况下,把美国号码标记为手机、固定电话或 VoIP。它读取的是号段,所以携号转网的号码显示的是最初持有该号段的运营商。
  • Email Deliverability Checker(email_deliverability_checker,每 10,000 个邮箱 $9.00)。它确认每个邮箱是否存在,并返回一个 zip 文件,其中的 all.csv 包含地址和 activated(yes 或 no)。它只覆盖 Gmail、Yahoo、Outlook、iCloud、Yandex 和 Mail.ru;其他地址会被排除,不收费。因此,使用企业域名注册的用户不会得到结果:请将其视为未知,并依靠确认链接。

每个手机号订单只能针对一个国家(至少占名单的 90%),因此队列按国家对号码分组。

一张队列表和一个批处理任务#

该任务维护两张表:每个等待检测的手机号或邮箱占一行;每个批次占一行,在发送任何内容之前就保存该批次的 Idempotency-Key。

什么时候发送一个批次?以先到者为准:等待中的条目达到 2,000 条(订单再小,费用也一样),或最早的条目已等待了设定的时长。如果每天注册少于 2,000 个,每天一批的费用是每个检测器每天一次最低收费,手机号为 $0.24,邮箱为 $1.80。每小时一批的费用最多可能是它的 24 倍。请在“试用最多暂缓一天”和“最多多出 23 次最低收费”之间权衡,选择等待时长。

将以下代码保存为 signup_checks.py,设置 TALISMANLEADS_API_KEY(一个有权下单的密钥;参见API 密钥安全),并通过 cron 每小时运行一次,例如 0 * * * * python3 signup_checks.py。它需要 requests 包,并使用 SQLite,因此在任何环境都能运行;同样的两张表也适用于 PostgreSQL 或 MySQL,只需换用各自的日期函数。

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)

其中有四个设计保障您的资金安全:

  • 密钥和价格随批次一起保存。重复的订单必须是完全相同的请求:在同一密钥下,名单或 expected_charge 不同的请求会以 idempotency_conflict 被拒绝。因此,崩溃的运行或因 insufficient_balance 而停止的运行,会在下一次重复完全相同的订单,而该订单只会被提交一次。只有在 price_changed(即什么都没下单)的情况下才换用新密钥。原因见幂等键:如何重试 API 请求而不重复付费。
  • 丢失的响应会重新询问,而不是另起一单。遇到 502 页面或 order_status_unknown 时,任务会用同一个密钥再次询问。其他所有代码都列在检测 API 错误中。
  • 失败的部分重新回到队列。失败的部分会全额退款,因此其中的注册只需等待下一个批次。
  • 按名称读取列。结果文件随时可能新增列。

我们让该任务对接一个模拟 API 运行,它会返回速率限制、余额不足、价格变动,以及一个已下单但响应丢失在 502 页面之后的订单。每个批次都只下单并计费一次,之后的运行也没有产生新订单。

根据结果采取行动#

现在每个注册都有了结论。规则由您决定;下面是一个合理的起点。

  • 重新填写。不可能存在的号码、在手机号栏填写的固定电话或免费电话,或不存在的邮箱,通常是失误而非欺诈。请客户在下次登录时或通过邮件更正,并在更正前暂缓发放试用。
  • 审核。VoIP 号码是需要进一步查看的理由,但绝不是证据:许多真实客户都在使用。请结合虚假注册指南中的其他信号综合判断。
  • 未知。检测范围之外的地址不会得到结论,由确认链接决定。
  • 放行。当一个账户的所有检测都已完成且都无需处理时,发放您暂缓的内容:
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;

请将每个结论与检测日期一同保存。从结果文件到 CRM 介绍了如何把结果导入您的其他系统,定期重新检测客户名单则介绍了日后如何再次检测同一批客户。

常见问题#

能否在注册时通过 API 实时验证手机号?#

实际意义不大。订单会在后台运行几分钟,且至少按 2,000 条计费。请在您自己的代码中用 libphonenumber 实时检查格式,再通过每小时或每天一批检测线路类型和运营商。

批处理应该多久运行一次?#

当有 2,000 条在等待,或最早的条目已等待到您能接受的时长(通常为一天)时,就发送一个批次。如果每天注册少于 2,000 个,每小时一批每天每个检测器最多要支付 24 次最低收费,而不是一次。

检测单个注册用户要多少钱?#

与 2,000 条相同:在 Number Carrier Lookup 上检测一个手机号为 $0.24,在 Email Deliverability Checker 上检测一个邮箱为 $1.80。下单前,POST /v1/estimates 会免费显示确切金额。

API 会标记一次性邮箱或角色邮箱吗?#

不会。请在您自己的代码中,对照一次性域名名单和 admin@、sales@ 等角色名称名单进行检查。Email Deliverability Checker 回答的是:在其覆盖的服务商中,某个邮箱是否存在。

检测时会联系我的用户吗?#

不会。运营商查询读取的是号码分配数据,邮箱检测不会向邮箱发送任何内容。不会给任何人打电话、发短信或发邮件。

如果我的注册用户来自多个国家怎么办?#

每个订单只放一个国家的手机号。上面的任务按国家对队列分组,因此每个国家各成一个批次。邮箱没有这一限制。

企业可以通过 $5、为期 14 天的免费试用,在自己的注册用户上试用这一方案;试用账户在首次充值前的 API 限额较低。在“API 密钥”中创建一个密钥,对昨天的注册用户运行您的第一次估价;完整参考请见 API 文档。

这篇内容有帮助吗?