[ Solutions ]

One API, many solutions

Six common problems that one IP lookup solves. Each has the scenario, how it works step by step, the fields to read, and code you can paste into your project.

[ 01 — Localization ]

Show the right language and country from the first page view

The scenario

A visitor from Kuala Lumpur lands on your English homepage, sees prices in USD and a shipping banner for the US. Most will leave before they find the language switcher.

How it works

  1. 1Read the visitor's IP on your server (behind Cloudflare: the CF-Connecting-IP header).
  2. 2Look it up once and cache the answer in the session.
  3. 3Pick the language from location.language.code, fall back to the browser's Accept-Language.
  4. 4Pre-select the country in forms and show a local banner. Always let the user change it.

Fields you'll use

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

Response excerpt

{
    "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'];          // one lookup per visit
    $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,                                        // never block the page for long
    ]);
    $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;          // e.g. "MY"

// <select name="country"> ... mark $country as selected
// <html lang="<?= $lang ?>">
✓Cache the result per session: the country of an IP rarely changes during a visit.
✓Use the IP as a default, not a lock. Travellers and VPN users must be able to switch.
✓GDPR banner: location.in_eu tells you whether to show EU consent flows.

[ 02 — Fraud prevention ]

Score risky sign-ups and payments before they cost you

The scenario

Fake accounts and stolen cards often come through VPNs, proxies, Tor or data-center IPs, or from a country that doesn't match the billing address.

How it works

  1. 1At sign-up or checkout, look up the client IP.
  2. 2Add points for each risk signal: VPN, proxy, Tor, known threat, cloud/hosting network, country mismatch.
  3. 3Decide by score: allow, ask for extra verification (email/SMS/3-D Secure), or block.
  4. 4Store the score with the order so your team can review it later.

Fields you'll use

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

Response excerpt

{
    "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']]; // fail open

    $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();       // step-up, don't block outright
✓Fail open: if the lookup times out, don't block real customers. Fall back to your other checks.
✓VPN alone is common (privacy users, office networks), so use it to step up verification rather than block.
✓Keep the reasons list: it explains decisions to support staff and customers.

[ 03 — Currency & pricing ]

Show prices in the visitor's own currency

The scenario

Seeing "$49" makes a visitor in Malaysia or Japan do mental maths, and many give up. Local currency and formatting raise conversion.

How it works

  1. 1Look up the IP to get currency.code and the local number format.
  2. 2Convert from your base price with your exchange-rate source, or use regional price lists.
  3. 3Format with the returned symbol and separators.
  4. 4Charge in the currency you actually support, and say so clearly at checkout.

Fields you'll use

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

Response excerpt

{
    "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:                       # only currencies you support
        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"
✓Round to friendly price points per currency (RM219 rather than RM219.03).
✓Cache exchange rates: refresh them hourly or daily, not per request.
✓Show "billed in USD" if you only charge in one currency, to avoid surprises.

[ 04 — Access control ]

Allow or block by country, network or anonymity

The scenario

Licensing, sanctions or abuse may force you to limit where your service is used, or to block anonymous traffic on sensitive pages such as admin or login.

How it works

  1. 1Put a small check in front of the protected routes (middleware).
  2. 2Look up the client IP and cache the decision for a few minutes per IP.
  3. 3Compare the country with your allow or deny list, and block Tor or proxies where needed.
  4. 4Return a clear 403 page explaining why, with a contact option.

Fields you'll use

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

Response excerpt

{
    "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 min
  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();                                   // fail open (or closed, your call)
  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);
✓Decide in advance whether to fail open or closed when the lookup is unavailable.
✓Allow-list your own office or monitoring IPs before the geo check runs.
✓Country blocking is coarse: VPNs can get around it. Combine it with is_anonymous for stricter areas.

[ 05 — Analytics ]

Know where your traffic, and your customers, come from

The scenario

Raw access logs only show IP addresses. Turning them into countries, cities, ISPs and business vs. residential traffic shows you where to market and where bots come from.

How it works

  1. 1Collect the distinct IPs from your logs or events (one lookup per IP, not per hit).
  2. 2Look up each new IP once and store the fields you need next to the IP.
  3. 3Join that table with your events to group by country, city, ASN or connection type.
  4. 4Refresh old entries every few weeks: IP assignments change slowly.

Fields you'll use

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

Response excerpt

{
    "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:                                   # only new IPs cost a request
    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), ...]
✓Deduplicate first: a busy site has far fewer unique IPs than hits, which keeps you well inside your quota.
✓connection.type = hosting separates data-center bots from real visitors.
✓Respect privacy: store country/city aggregates, and drop raw IPs when you no longer need them.

[ 06 — Timezone ]

Reach people at the right local time

The scenario

A reminder sent at 9am server time lands at 1am for half your users. Booking pages showing UTC confuse everyone.

How it works

  1. 1At sign-up, look up the IP and save time_zone.id (an IANA name like Asia/Kuala_Lumpur) on the profile.
  2. 2Store all times in UTC, and convert for display with the saved zone.
  3. 3Schedule emails and pushes for a local hour, e.g. 9:00 in each user's zone.
  4. 4Let users correct the zone in settings: the browser's Intl API is a good second opinion.

Fields you'll use

time_zone.idtime_zone.offsettime_zone.current_timetime_zone.in_daylight_savingtime_zone.abbreviation

Response excerpt

{
    "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
// at sign-up
$geo = lookup($clientIp);                                   // your API helper
$tz  = $geo['time_zone']['id'] ?? 'UTC';                    // "Asia/Kuala_Lumpur"
$db->prepare('UPDATE users SET timezone = ? WHERE id = ?')->execute([$tz, $userId]);

// show a UTC timestamp in the user's time
$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"

// next 09:00 local, as UTC, for the reminder queue
$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'));
✓Save the IANA id (time_zone.id), not the offset: offsets change with daylight saving.
✓Use the IP zone as a first guess and confirm it with the browser's Intl API.
✓Sending at a local hour spreads out email load across the day.

[ Get started ]

Build it today, free

Create an account, copy your API key into DKLY_API_KEY, and every example above works as-is.