在 PHP 中使用 Watch-IP
digitload/watch-ip-sdk(Packagist,v0.1.1)基于 cURL,将 GET /v1/geo 封装进一个 Composer 软件包中——不依赖 Guzzle 或其他 HTTP 客户端。
安装
需要 PHP 8.1 及以上版本,并启用 curl 与 json 扩展——这两个扩展几乎在所有 PHP 安装中都已内置。
Composer
composer require digitload/watch-ip-sdk快速开始
与其他服务器端 SDK 一样,从 PHP 调用 GET /v1/geo 意味着由您自己的服务器发起调用,而不是访问者的浏览器,因此需要显式传入 origin 以满足该密钥的允许来源校验。
PHP
use Digitload\WatchIP\WatchIP;
$client = new WatchIP('wip_pub_xxxxxxxx', origin: 'https://example.com');
$geo = $client->getGeo();
echo $geo['country'], ' ', $geo['city'], ' ', $geo['timezone'];错误处理与超时
每一次失败都会抛出一个继承自 \RuntimeException 的 WatchIPError。PHP 的 Exception::getCode() 返回类型为 int,而 API 的错误代码是字符串,因此请使用 getErrorCode() 而不是 getCode() 来读取它们。请在 options 数组中与 include 一起传入 timeout(以秒为单位)。
PHP
use Digitload\WatchIP\WatchIP;
use Digitload\WatchIP\WatchIPError;
$client = new WatchIP('wip_pub_xxxxxxxx', origin: 'https://example.com');
try {
$geo = $client->getGeo(['timeout' => 5.0]);
} catch (WatchIPError $err) {
echo $err->getErrorCode(), ' ', $err->getStatus(), ' ', $err->getMessage();
}本 SDK 不涵盖的内容
该软件包只调用 GET /v1/geo。IP 查询、邮箱验证与风险检测是另外的服务器到服务器端点,目前尚无 PHP 客户端——请直接使用 cURL 调用它们,身份验证方式与身份验证指南中所述一致。