開發全國性分類資訊網、電商平台、表單驗證系統時,常需根據手機號碼顯示歸屬地(省份、運營商)以增強信任感或簡化填寫。本文整理 6 家主流免費 API,並提供 PHP 串接最佳實踐、錯誤處理與快取策略。
| 提供方 | API 端點 | 參數 | 回傳格式 | 特點/限制 |
|---|---|---|---|---|
| 淘寶 | https://tcc.taobao.com/cc/json/mobile_tel_segment.htm |
tel(手機號) |
JSONP | 穩定、支援 HTTPS、無需金鑰、頻率限制較寬 |
| 拍拍 | https://virtual.paipai.com/extinfo/GetMobileProductInfo |
mobile、callname、amount |
JSONP | 需指定回調函數、amount 必填但文檔不明 |
| 財付通 | https://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi |
chgmobile |
XML | 騰訊出品、穩定性佳、XML 解析稍繁瑣 |
| 百付寶 | https://www.baifubao.com/callback |
phone、callback、cmd |
JSONP | HTTPS、參數較多、回調函數名固定 |
| 115 網盤 | https://cz.115.com/?ct=index&ac=get_mobile_local |
mobile、callback |
JSONP | 支援 JSONP、相對較新、穩定性待觀察 |
| 有道 | https://www.youdao.com/smartresult-xml/search.s |
type=mobile、q、jsFlag |
XML / JSONP | 支援雙格式、字編碼為 GBK 需轉碼 |
<?php
class MobileLocationService
{
private const API_URL = 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm';
private const TIMEOUT = 5; // 秒
private const CACHE_TTL = 86400 * 30; // 30 天,歸屬地極少變動
private $httpClient;
private $cache;
public function __construct(\Psr\Http\Client\ClientInterface $client = null, \Psr\SimpleCache\CacheInterface $cache = null) {
$this->httpClient = $client ?? new \GuzzleHttp\Client(['timeout' => self::TIMEOUT]);
$this->cache = $cache;
}
public function query(string $mobile): ?array
{
// 基本驗證
if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
return null;
}
$cacheKey = 'mobile_loc_' . $mobile;
if ($this->cache && $this->cache->has($cacheKey)) {
return $this->cache->get($cacheKey);
}
try {
$response = $this->httpClient->request('GET', self::API_URL, [
'query' => ['tel' => $mobile, 't' => time()], // 避免快取
]);
$body = (string)$response->getBody();
// 淘寶回傳格式:__GetZoneResult_ = { ... } 或 JSONP
$json = $this->extractJson($body);
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE || empty($data['province'])) {
return null;
}
$result = [
'province' => $data['province'] ?? '',
'city' => $data['catName'] ?? '', // 實際為城市/地區
'carrier' => $data['isp'] ?? '', // 運營商:中國移動/聯通/電信
'area_code' => $data['areaCode'] ?? '',
'zip_code' => $data['postCode'] ?? '',
];
if ($this->cache) {
$this->cache->set($cacheKey, $result, self::CACHE_TTL);
}
return $result;
} catch (\Throwable $e) {
error_log('MobileLocationService error: ' . $e->getMessage());
return null;
}
}
private function extractJson(string $body): string
{
// 處理 JSONP:__GetZoneResult_ = {...};
if (preg_match('/^\s*\w+\s*=\s*(\{.*\})\s*;?\s*$/s', $body, $m)) {
return $m[1];
}
// 純 JSON
if (str_starts_with(trim($body), '{')) {
return $body;
}
throw new \RuntimeException('Unexpected response format');
}
}
<?php
require 'vendor/autoload.php';
$cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter('mobile_loc', 0, '/tmp/cache');
$service = new MobileLocationService(new \GuzzleHttp\Client(), $cache);
$mobile = '15018788111';
$location = $service->query($mobile);
if ($location) {
echo "省份: {$location['province']}\n"; // 例:上海
echo "城市: {$location['city']}\n"; // 例:上海
echo "運營商: {$location['carrier']}\n"; // 例:中國移動
} else {
echo "查詢失敗或號碼格式錯誤\n";
}
<?php
function get_mobile_location_simple(string $mobile): ?array
{
if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) return null;
$url = 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=' . urlencode($mobile) . '&t=' . time();
$ctx = stream_context_create(['http' => ['timeout' => 5, 'header' => 'User-Agent: PHP']]);
$content = @file_get_contents($url, false, $ctx);
if (!$content) return null;
// 簡易解析(淘寶回傳固定格式)
$json = preg_replace('/^\s*\w+\s*=\s*|\s*;?\s*$/', '', $content);
$data = json_decode($json, true);
return $data['province'] ? [
'province' => $data['province'],
'city' => $data['catName'] ?? '',
'carrier' => $data['isp'] ?? '',
] : null;
}
有道 API 回傳 GBK,需轉碼:
$xml = iconv('GBK', 'UTF-8', $xml);
$json = json_decode(json_encode(simplexml_load_string($xml)), true);
O(log n) 更穩定function queryWithFallback(string $mobile): ?array
{
$providers = [
'taobao' => fn() => $this->queryTaobao($mobile),
'youdao' => fn() => $this->queryYoudao($mobile),
'tenpay' => fn() => $this->queryTenpay($mobile),
];
foreach ($providers as $name => $fn) {
try {
$result = $fn();
if ($result) return $result;
} catch (\Throwable $e) {
error_log("Provider $name failed: " . $e->getMessage());
}
}
return null;
}
手機歸屬地查詢看似簡單,生產環境需考慮穩定性、編碼、快取、備援、合規。推薦策略:本地號段資料庫為主,免費 API 為備援;若必須仰賴外部 API,務必實作快取、超時控制、熔斷與多源輪詢。本文提供的服務類可直接整合至 Laravel、Symfony、ThinkPHP 等框架,或作為獨立函數使用。