Google Adsense服务帐户

时间:2013-08-30 03:40:03

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

我遇到了谷歌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->生成('2013-01-01','2013-03-03',数组)#4 {main}抛出/ opt / lampp / htdocs /第66行的googleads / google-api-php-client / io / Google_REST.php

2 个答案:

答案 0 :(得分:2)

AdSense Management API中未提供服务帐户。

如果要在没有用户干预的情况下使用API​​,可以使用“Web应用程序”或“已安装的应用程序”方案。用户授予对您应用的访问权限后,即可开始申请访问令牌。

查看PHP示例:https://code.google.com/p/google-api-php-client/source/browse/#svn%2Ftrunk%2Fexamples%2Fadsense

答案 1 :(得分:0)

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

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