[ 01 — 本地化 ]
场景
一位来自吉隆坡的访客打开你的英文首页,看到的是美元价格和面向美国的配送横幅。大多数人还没找到语言切换按钮就离开了。
工作原理
会用到的字段
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 ?>">
// 调用你自己的后端路由,由服务器端添加 API 密钥。
// 切勿把 API 密钥放在浏览器代码中。
const res = await fetch('/geo'); // 你的服务器代理 ipinfo.dkly.net/api/
const geo = await res.json();
const country = geo.location?.country?.code; // "MY"
const lang = geo.location?.language?.code ?? 'en'; // "ms"
document.querySelector('#country').value = country ?? '';
if (!localStorage.lang && lang !== document.documentElement.lang) {
showBanner(`View this site in ${geo.location.language.name}?`, () => switchLang(lang));
}
[ 02 — 反欺诈 ]
场景
虚假账户和盗用的银行卡往往来自 VPN、代理、Tor 或数据中心 IP,或者来自与账单地址不符的国家。
工作原理
会用到的字段
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(); // 加强验证,而不是直接拦截
const API = 'https://ipinfo.dkly.net/api/';
export async function ipRisk(ip, billingCountry) {
const r = await fetch(`${API}?ip=${encodeURIComponent(ip)}`, {
headers: { 'X-API-Key': process.env.DKLY_API_KEY },
signal: AbortSignal.timeout(3000),
}).catch(() => null);
if (!r?.ok) return { score: 0, reasons: ['lookup_failed'] }; // 失败时放行
const d = await r.json(), s = d.security ?? {};
const rules = [
[s.is_tor, 50, 'tor'], [s.is_threat, 40, 'known_threat'], [s.is_proxy, 30, 'proxy'],
[s.is_vpn, 20, 'vpn'], [s.is_cloud_provider, 20, 'datacenter'],
[billingCountry && d.location?.country?.code !== billingCountry, 25, 'country_mismatch'],
];
const hits = rules.filter(([hit]) => hit);
return { score: hits.reduce((n, [, p]) => n + p, 0), reasons: hits.map(([, , why]) => why) };
}
[ 03 — 货币与定价 ]
场景
看到“$49”,马来西亚或日本的访客得自己心算,很多人就放弃了。本地货币和格式能提高转化率。
工作原理
会用到的字段
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"
// geo = API 响应(在你的服务器上获取)
const code = geo.currency?.code ?? 'USD';
const rate = rates[code]; // 来自你的汇率来源
const price = rate ? 49 * rate : 49;
// Intl 负责格式化;API 告诉你用哪种货币
const label = new Intl.NumberFormat(navigator.language, {
style: 'currency', currency: rate ? code : 'USD',
}).format(price); // "RM 219.03"
[ 04 — 访问控制 ]
场景
授权许可、制裁或滥用可能迫使你限制服务的使用地区,或在管理后台、登录等敏感页面拦截匿名流量。
工作原理
会用到的字段
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);
<?php
// auth_request 目标:nginx 在提供 /admin 之前先询问此脚本
// location /admin { auth_request /geo-check.php; ... }
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'];
$key = 'geo:' . $ip;
$d = apcu_fetch($key);
if ($d === false) {
$ctx = stream_context_create(['http' => ['header' => 'X-API-Key: ' . getenv('DKLY_API_KEY'), 'timeout' => 2]]);
$d = json_decode(@file_get_contents('https://ipinfo.dkly.net/api/?ip=' . urlencode($ip), false, $ctx) ?: 'null', true);
apcu_store($key, $d, 600);
}
$ok = $d && !($d['security']['is_tor'] ?? false) && in_array($d['location']['country']['code'] ?? '', ['MY', 'SG'], true);
http_response_code($ok ? 204 : 403);
[ 05 — 分析 ]
场景
原始访问日志只显示 IP 地址。把它们转换成国家、城市、ISP 以及企业与家庭流量,你就能知道该在哪里推广、机器人从哪里来。
工作原理
会用到的字段
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), ...]
-- 本月按国家和连接类型统计的注册数
SELECT g.country, g.type, COUNT(*) AS signups
FROM signups s
JOIN ip_geo g ON g.ip = s.ip
WHERE s.created_at >= DATE_FORMAT(NOW(), '%Y-%m-01')
GROUP BY g.country, g.type
ORDER BY signups DESC;
-- 注册数很多的 'hosting' 行通常是值得细查的机器人
[ 06 — 时区 ]
场景
按服务器时间早上 9 点发送的提醒,对一半用户来说是凌晨 1 点。显示 UTC 的预约页面会让所有人困惑。
工作原理
会用到的字段
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'));
// 来自 API 响应的 tz(注册时保存)
const tz = geo.time_zone?.id ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
const fmt = new Intl.DateTimeFormat('en-GB', {
timeZone: tz, weekday: 'short', day: 'numeric', month: 'short',
hour: '2-digit', minute: '2-digit', timeZoneName: 'short',
});
fmt.format(new Date('2026-12-02T13:30:00Z')); // "Wed 2 Dec, 21:30 GMT+8"