萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

免費手機號碼歸屬地查詢 API 整理與 PHP 串接實戰指南

前言

開發全國性分類資訊網、電商平台、表單驗證系統時,常需根據手機號碼顯示歸屬地(省份、運營商)以增強信任感或簡化填寫。本文整理 6 家主流免費 API,並提供 PHP 串接最佳實踐、錯誤處理與快取策略。

六大免費 API 對比表

提供方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 串接最佳實踐:以淘寶 API 為例

1. 封裝可復用的服務類

<?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');
    }
}

2. 使用範例

<?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";
}

3. 無 Composer 環境的簡易版

<?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;
}

進階議題

1. 編碼陷阱

有道 API 回傳 GBK,需轉碼:

$xml = iconv('GBK', 'UTF-8', $xml);
$json = json_decode(json_encode(simplexml_load_string($xml)), true);

2. 高併發與限流

  • 本地快取(Redis/Memcached/檔案)是必須,歸屬地資料幾乎不變
  • 單機 QPS 瓶頸在外部 HTTP 請求,建議非同步預熱或批次查詢
  • 若自建資料庫:下載號段資料庫(約 50 萬條),本地查詢 O(log n) 更穩定

3. 備援機制

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

4. 法律與合規提醒

  • 免費 API 多為內部業務衍生,無正式 SLA,隨時可能下線或限流
  • 商業專案建議採購正規號段資料庫(工信部授權數據商)或使用三方付費服務(極光、騰訊雲、阿里雲號碼歸屬地)
  • 注意個資保護:僅查詢歸屬地,勿儲存完整手機號與用戶身份關聯資料

總結

手機歸屬地查詢看似簡單,生產環境需考慮穩定性、編碼、快取、備援、合規。推薦策略:本地號段資料庫為主,免費 API 為備援;若必須仰賴外部 API,務必實作快取、超時控制、熔斷與多源輪詢。本文提供的服務類可直接整合至 Laravel、Symfony、ThinkPHP 等框架,或作為獨立函數使用。

copyright © 萬盛學電腦網 all rights reserved