【问题标题】:Google Adsense Services AccountGoogle Adsense 服务帐户
【发布时间】:2026-01-14 10:50:01
【问题描述】:

我遇到了 Google Adsense API 的问题。我使用服务帐户进行身份验证,这是我的代码:

require_once dirname(__FILE__) . '/google-api-php-client/Google_Client.php';    
require_once dirname(__FILE__) . '/google-api-php-client/contrib/Google_AdSenseService.php';
require_once dirname(__FILE__) . '/google-api-php-client/contrib/Google_Oauth2Service.php';

$SERVICE_ACCOUNT_PKCS12_FILE_PATH = dirname(__FILE__) . '/keyfile.p12';

// create client object and set app name
$client = new Google_Client();
$client->setApplicationName("XXXX"); // name of your app

// set assertion credentials
$key  = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials("YYYYYY@developer.gserviceaccount.com", // email you added to GA
    array('https://www.googleapis.com/auth/adsense.readonly'), $key);

$client->setAssertionCredentials($auth);
$client->getAuth()->refreshTokenWithAssertion();
$accessToken = $client->getAccessToken();
// other settings
$client->setClientId("XYZ.apps.googleusercontent.com"); // from API console
$service   = new Google_AdsenseService($client);
$optParams = array('metric' => array('earnings'), 'dimension' => 'date');
$data      = $service->reports->generate('2013-01-01', '2013-03-03', $optParams);

然后我收到了这个错误消息:

致命错误:未捕获异常“Google_ServiceException”并显示消息“调用 GET https://www.googleapis.com/adsense/v1.3/reports?startDate=2013-01-01&endDate=2013-03-03&metric=earnings&dimension=date 时出错:(403) 用户没有 AdSense 帐户。”在 /opt/lampp/htdocs/googleads/google-api-php-client/io/Google_REST.php:66 堆栈跟踪:#0 /opt/lampp/htdocs/googleads/google-api-php-client/io/Google_REST .php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 /opt/lampp/htdocs/googleads/google-api-php-client/service/Google_ServiceResource.php(186): Google_REST::execute(Object (Google_HttpRequest)) #2 /opt/lampp/htdocs/googleads/google-api-php-client/contrib/Google_AdSenseService.php(849): Google_ServiceResource->__call('generate', Array) #3 /opt/lampp/ htdocs/googleads/index.php(28): Google_ReportsServiceResource->generate('2013-01-01', '2013-03-03', Array) #4 {main} 抛出 /opt/lampp/htdocs/googleads/ google-api-php-client/io/Google_REST.php 第 66 行

【问题讨论】:

  • 错误信息是:用户没有 AdSense 帐户您确定信息正确吗?
  • 您是否通过 Google API Console 启用了 AdSense?仅拥有 AdSense 帐户并不会自动授予您 API 访问权限。
  • 是的,在 $accessToken = $client->getAccessToken(); 之后,我可以获得访问令牌。但是我不能调用任何函数来获取数据报告。

标签: php adsense google-api-client adsense-api


【解决方案1】:

很遗憾,目前 AdSense API 不支持服务帐户,因此 API 看不到 AdSense 数据(这就是您收到该错误的原因)。

也许最好的解决方案是使用“Web 应用程序”登录:https://developers.google.com/adsense/management/getting_started#auth

【讨论】: