2013-08-30 145 views
0

我遇到了Google Adsense API的问题。我使用的服务帐户认证介绍,这是我的代码:Google Adsense Services帐户

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("[email protected]", // 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); 

然后我得到这个错误messege:

Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/adsense/v1.3/reports?startDate=2013-01-01&endDate=2013-03-03&metric=earnings&dimension=date : (403) User does not have an AdSense account.' in /opt/lampp/htdocs/googleads/google-api-php-client/io/Google_REST.php:66 Stack trace: #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} thrown in /opt/lampp/htdocs/googleads/google-api-php-client/io/Google_REST.php on line 66

+0

的错误信息是:*用户没有AdSense帐户*你确定的信息是正确的? – Raptor

+0

是否从[Google API控制台](https://code.google.com/apis/console/)启用了AdSense?只需拥有AdSense帐户并不会自动为您提供API访问权限。 – roninblade

+0

是的,$ accessToken = $ client-> getAccessToken()后,我可以获得访问令牌。但我无法调用任何函数来获取数据报告。 –

回答