如何使用Adsense API单域名查询?PHP SDK正确语法求助
使用AdSense PHP SDK直接查询单个域名是否已接入AdSense
你可以通过Google AdSense PHP SDK的accounts_sites->get方法直接查询单个域名,无需遍历所有站点。具体实现代码如下:
# Setup client $client = new Google_Client(); $client->setAccessToken(GOOGLE_ACCESS_TOKEN); $client->setScopes(['https://www.googleapis.com/auth/adsense']); # Setup api $adsense = new \Google\Service\Adsense($client); $accountId = "accounts/pub-xxxxxxxxxxxxxxxx"; $targetDomain = "example.com"; // 替换为你要查询的域名 $in_adsense = false; try { // 调用get方法,格式为 accounts/{accountId}/sites/{domain} $site = $adsense->accounts_sites->get("$accountId/sites/$targetDomain"); // 如果请求成功,说明域名已接入 $in_adsense = true; } catch (\Google\Service\Exception $e) { // 捕获404异常,说明域名未接入 if ($e->getCode() === 404) { $in_adsense = false; } else { // 处理其他错误,比如权限不足、token失效等 throw $e; } } // 最终结果 var_dump($in_adsense);
关键说明:
get方法的参数格式必须是accounts/{accountId}/sites/{domain},其中domain是不带http/https的纯域名(比如example.com,不是https://example.com)。- 当域名未接入AdSense时,API会返回404 Not Found异常,需要通过捕获这个异常来判断域名不存在,而非依赖返回值。
- 确保你的AccessToken拥有
https://www.googleapis.com/auth/adsense权限,否则会返回权限错误。
对比原方法的优势:
- 无需拉取所有站点数据,减少API请求的数据量和网络耗时。
- 逻辑更简洁,直接通过API的返回状态判断结果,避免遍历数组的额外操作。
内容的提问来源于stack exchange,提问作者Benjamin de Bos
相关产品推荐
相关产品推荐

