[ 解决方案 ]

一个 API,多种方案

一次 IP 查询就能解决的六个常见问题。每个都包含场景说明、分步工作原理、要读取的字段,以及可直接粘贴到项目中的代码。

[ 01 — 本地化 ]

从第一次访问起就显示正确的语言和国家

场景

一位来自吉隆坡的访客打开你的英文首页,看到的是美元价格和面向美国的配送横幅。大多数人还没找到语言切换按钮就离开了。

工作原理

  1. 1在服务器上读取访客 IP(使用 Cloudflare 时读取 CF-Connecting-IP 请求头)。
  2. 2只查询一次,并把结果缓存在会话中。
  3. 3根据 location.language.code 选择语言,没有时退回浏览器的 Accept-Language。
  4. 4在表单中预选国家并显示本地横幅。始终允许用户自行更改。

会用到的字段

location.country.codelocation.country.namelocation.language.codelocation.country.calling_codelocation.in_eu

响应片段

{
    "location": {
        "country": {
            "code": "MY",
            "name": "Malaysia",
            "calling_code": "60"
        },
        "language": {
            "code": "ms",
            "name": "Malay"
        },
        "in_eu": false
    }
}
<?php
session_start();

function visitorGeo(): ?array {
    if (isset($_SESSION['geo'])) return $_SESSION['geo'];          // 每次访问只查询一次
    $ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'];
    $ch = curl_init('https://ipinfo.dkly.net/api/?ip=' . urlencode($ip));
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('DKLY_API_KEY')],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 2,                                        // 不要让页面长时间卡住
    ]);
    $res = json_decode(curl_exec($ch) ?: 'null', true);
    return $_SESSION['geo'] = is_array($res) && isset($res['location']) ? $res : null;
}

$geo  = visitorGeo();
$supported = ['en', 'ms', 'zh', 'ja', 'th'];
$lang = $geo['location']['language']['code'] ?? 'en';
$lang = in_array($lang, $supported, true) ? $lang : 'en';
$country = $geo['location']['country']['code'] ?? null;          // 例如 "MY"

// <select name="country"> ... 将 $country 设为选中
// <html lang="<?= $lang ?>">
✓按会话缓存结果:一次访问中 IP 所在国家很少变化。
✓把 IP 当作默认值,而不是限制。旅行者和 VPN 用户必须能够切换。
✓GDPR 横幅:location.in_eu 告诉你是否需要显示欧盟同意流程。

[ 02 — 反欺诈 ]

在造成损失之前,为高风险注册和支付打分

场景

虚假账户和盗用的银行卡往往来自 VPN、代理、Tor 或数据中心 IP,或者来自与账单地址不符的国家。

工作原理

  1. 1在注册或结账时查询客户端 IP。
  2. 2为每个风险信号加分:VPN、代理、Tor、已知威胁、云/托管网络、国家不符。
  3. 3按分数决定:放行、要求额外验证(邮件/短信/3-D Secure)或拦截。
  4. 4把分数和订单一起保存,方便团队日后复核。

会用到的字段

security.is_vpnsecurity.is_proxysecurity.is_torsecurity.is_threatsecurity.is_abusersecurity.is_cloud_providerlocation.country.codeconnection.type

响应片段

{
    "security": {
        "is_vpn": true,
        "is_proxy": false,
        "is_tor": false,
        "is_threat": false,
        "is_cloud_provider": true
    },
    "connection": {
        "type": "hosting"
    }
}
<?php
function ipRisk(string $ip, ?string $billingCountry = null): array {
    $ch = curl_init('https://ipinfo.dkly.net/api/?ip=' . urlencode($ip));
    curl_setopt_array($ch, [CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('DKLY_API_KEY')],
                            CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 3]);
    $d = json_decode(curl_exec($ch) ?: 'null', true);
    if (!isset($d['security'])) return ['score' => 0, 'reasons' => ['lookup_failed']]; // 失败时放行

    $s = $d['security']; $score = 0; $why = [];
    $add = function (bool $hit, int $pts, string $r) use (&$score, &$why) { if ($hit) { $score += $pts; $why[] = $r; } };
    $add($s['is_tor'] ?? false,            50, 'tor');
    $add($s['is_threat'] ?? false,         40, 'known_threat');
    $add($s['is_proxy'] ?? false,          30, 'proxy');
    $add($s['is_vpn'] ?? false,            20, 'vpn');
    $add($s['is_cloud_provider'] ?? false, 20, 'datacenter');
    $add($billingCountry && ($d['location']['country']['code'] ?? null) !== $billingCountry, 25, 'country_mismatch');

    return ['score' => $score, 'reasons' => $why];
}

$risk = ipRisk($_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'], $order['billing_country']);
if ($risk['score'] >= 70)      reject('Please contact support to complete this order.');
elseif ($risk['score'] >= 30)  requireOtp();       // 加强验证,而不是直接拦截
✓失败时放行:查询超时不要拦截真实客户,改用你的其他检查。
✓单纯使用 VPN 很常见(注重隐私的用户、办公网络),所以用它来加强验证,而不是直接拦截。
✓保留原因列表:它能向客服人员和客户解释决定。

[ 03 — 货币与定价 ]

用访客自己的货币显示价格

场景

看到“$49”,马来西亚或日本的访客得自己心算,很多人就放弃了。本地货币和格式能提高转化率。

工作原理

  1. 1查询 IP,获取 currency.code 和本地数字格式。
  2. 2用你的汇率来源从基础价格换算,或使用分区价目表。
  3. 3使用返回的货币符号和分隔符进行格式化。
  4. 4用你实际支持的货币收费,并在结账时清楚说明。

会用到的字段

currency.codecurrency.symbol_nativecurrency.format.positivecurrency.format.decimal_separatorcurrency.format.group_separator

响应片段

{
    "currency": {
        "code": "MYR",
        "symbol_native": "RM",
        "format": {
            "decimal_separator": ".",
            "group_separator": ",",
            "positive": {
                "prefix": "RM",
                "suffix": ""
            }
        }
    }
}
import os, requests

def local_price(ip: str, usd: float, rates: dict) -> str:
    r = requests.get("https://ipinfo.dkly.net/api/", params={"ip": ip},
                     headers={"X-API-Key": os.environ["DKLY_API_KEY"]}, timeout=2)
    cur = r.json().get("currency") or {}
    code = cur.get("code", "USD")
    if code not in rates:                       # 只处理你支持的货币
        code, cur = "USD", {"format": {"positive": {"prefix": "$", "suffix": ""},
                                       "decimal_separator": ".", "group_separator": ","}}
    amount = usd * rates.get(code, 1.0)
    f = cur["format"]
    whole, frac = f"{amount:,.2f}".split(".")
    whole = whole.replace(",", f["group_separator"])
    return f'{f["positive"]["prefix"]}{whole}{f["decimal_separator"]}{frac}{f["positive"]["suffix"]}'

# local_price("111.221.48.163", 49, {"USD": 1, "MYR": 4.47})  ->  "RM219.03"
✓按货币取整到友好的价格点(RM219 而不是 RM219.03)。
✓缓存汇率:每小时或每天刷新,而不是每次请求都刷新。
✓如果只用一种货币收费,请显示“以美元结算”,避免让用户意外。

[ 04 — 访问控制 ]

按国家、网络或匿名性放行或拦截

场景

授权许可、制裁或滥用可能迫使你限制服务的使用地区,或在管理后台、登录等敏感页面拦截匿名流量。

工作原理

  1. 1在受保护的路由前加一个小检查(中间件)。
  2. 2查询客户端 IP,并按 IP 把决定缓存几分钟。
  3. 3把国家与你的允许或拒绝列表比对,必要时拦截 Tor 或代理。
  4. 4返回清晰的 403 页面说明原因,并提供联系方式。

会用到的字段

location.country.codeconnection.asnsecurity.is_torsecurity.is_proxysecurity.is_anonymous

响应片段

{
    "location": {
        "country": {
            "code": "MY"
        }
    },
    "connection": {
        "asn": 38278
    },
    "security": {
        "is_tor": false,
        "is_proxy": false,
        "is_anonymous": false
    }
}
import express from 'express';
const cache = new Map();                                   // ip -> { d, t }
const ALLOWED = new Set(['MY', 'SG', 'ID', 'TH']);

async function lookup(ip) {
  const hit = cache.get(ip);
  if (hit && Date.now() - hit.t < 10 * 60_000) return hit.d;   // 10 分钟
  const r = await fetch(`https://ipinfo.dkly.net/api/?ip=${ip}`, {
    headers: { 'X-API-Key': process.env.DKLY_API_KEY },
  });
  const d = r.ok ? await r.json() : null;
  cache.set(ip, { d, t: Date.now() });
  return d;
}

export async function geoGate(req, res, next) {
  const ip = req.get('CF-Connecting-IP') ?? req.ip;
  const d = await lookup(ip);
  if (!d) return next();                                   // 失败时放行(或拒绝,由你决定)
  if (d.security?.is_tor || d.security?.is_proxy) return res.status(403).send('Anonymous proxies are not allowed here.');
  if (!ALLOWED.has(d.location?.country?.code)) return res.status(403).send('This service is not available in your region.');
  next();
}

app.use('/admin', geoGate);
✓提前决定查询不可用时是放行还是拒绝。
✓在地理检查之前,把你自己的办公室或监控 IP 加入允许列表。
✓按国家拦截比较粗略:VPN 可以绕过。对要求更严格的区域,请结合 is_anonymous 使用。

[ 05 — 分析 ]

了解你的流量和客户来自哪里

场景

原始访问日志只显示 IP 地址。把它们转换成国家、城市、ISP 以及企业与家庭流量,你就能知道该在哪里推广、机器人从哪里来。

工作原理

  1. 1从日志或事件中收集不重复的 IP(每个 IP 查询一次,而不是每次访问查询一次)。
  2. 2每个新 IP 只查询一次,并把需要的字段和 IP 存在一起。
  3. 3把这张表与事件关联,按国家、城市、ASN 或连接类型分组。
  4. 4每隔几周刷新旧记录:IP 分配变化很慢。

会用到的字段

location.country.codelocation.citylocation.region.nameconnection.asnconnection.organizationconnection.typecompany.name

响应片段

{
    "location": {
        "city": "Kuala Lumpur",
        "region": {
            "name": "Wilayah Persekutuan Kuala Lumpur"
        },
        "country": {
            "code": "MY"
        }
    },
    "connection": {
        "asn": 38278,
        "organization": "Orient Telecoms Sdn. Bhd",
        "type": "isp"
    }
}
import os, sqlite3, requests, collections

db = sqlite3.connect("geo.db")
db.execute("CREATE TABLE IF NOT EXISTS ip_geo (ip TEXT PRIMARY KEY, country TEXT, city TEXT, asn INT, org TEXT, type TEXT)")
s = requests.Session()
s.headers["X-API-Key"] = os.environ["DKLY_API_KEY"]

ips = {line.split()[0] for line in open("/var/log/nginx/access.log")}
known = {r[0] for r in db.execute("SELECT ip FROM ip_geo")}

for ip in ips - known:                                   # 只有新 IP 才会产生请求
    d = s.get("https://ipinfo.dkly.net/api/", params={"ip": ip}, timeout=5).json()
    loc, con = d.get("location", {}), d.get("connection", {})
    db.execute("INSERT OR REPLACE INTO ip_geo VALUES (?,?,?,?,?,?)",
               (ip, (loc.get("country") or {}).get("code"), loc.get("city"),
                con.get("asn"), con.get("organization"), con.get("type")))
db.commit()

top = db.execute("SELECT country, COUNT(*) FROM ip_geo GROUP BY country ORDER BY 2 DESC LIMIT 10").fetchall()
print(top)          # [('MY', 1840), ('SG', 610), ('US', 402), ...]
✓先去重:繁忙网站的唯一 IP 远少于访问次数,能让你稳稳控制在配额之内。
✓connection.type = hosting 可以把数据中心机器人和真实访客区分开。
✓尊重隐私:存储国家/城市汇总数据,不再需要时删除原始 IP。

[ 06 — 时区 ]

在合适的当地时间触达用户

场景

按服务器时间早上 9 点发送的提醒,对一半用户来说是凌晨 1 点。显示 UTC 的预约页面会让所有人困惑。

工作原理

  1. 1注册时查询 IP,并把 time_zone.id(IANA 名称,例如 Asia/Kuala_Lumpur)保存到用户资料中。
  2. 2所有时间都以 UTC 存储,显示时再用保存的时区转换。
  3. 3按当地时间安排邮件和推送,例如每位用户所在时区的 9:00。
  4. 4允许用户在设置中更正时区:浏览器的 Intl API 是很好的参考。

会用到的字段

time_zone.idtime_zone.offsettime_zone.current_timetime_zone.in_daylight_savingtime_zone.abbreviation

响应片段

{
    "time_zone": {
        "id": "Asia/Kuala_Lumpur",
        "abbreviation": "GMT+08:00",
        "offset": 28800,
        "in_daylight_saving": false,
        "current_time": "2026-12-02T21:30:00+08:00"
    }
}
<?php
// 注册时
$geo = lookup($clientIp);                                   // 你的 API 辅助函数
$tz  = $geo['time_zone']['id'] ?? 'UTC';                    // "Asia/Kuala_Lumpur"
$db->prepare('UPDATE users SET timezone = ? WHERE id = ?')->execute([$tz, $userId]);

// 用用户的当地时间显示 UTC 时间戳
$when = new DateTime($row['starts_at_utc'], new DateTimeZone('UTC'));
$when->setTimezone(new DateTimeZone($user['timezone']));
echo $when->format('D j M, H:i T');                         // "Wed 2 Dec, 21:30 +08"

// 下一个当地 09:00(换算为 UTC),用于提醒队列
$next = new DateTime('tomorrow 09:00', new DateTimeZone($user['timezone']));
$next->setTimezone(new DateTimeZone('UTC'));
queueEmail($userId, $next->format('Y-m-d H:i:s'));
✓保存 IANA ID(time_zone.id),而不是偏移量:偏移量会随夏令时变化。
✓先用 IP 时区作为初步猜测,再用浏览器的 Intl API 确认。
✓按当地时间发送,可以把邮件负载分散到全天。

[ 开始使用 ]

今天就动手,免费

注册账户,把 API 密钥填入 DKLY_API_KEY,上面的每个示例即可直接运行。