2017-05-31 89 views
0

我试图通过AdSense Management API从AdSense帐户中检索数据。使用Google AdSense Management API访问数据 - PHP

我与AdSense帐户关联时,使用Google API Explorer成功检索了数据。

我现在试图从将在crontab中运行的PHP脚本获取这些数据。

我的理解是我需要一个我创建的Service account,并生成了一个json文件。

  1. 如果我用SETSUBJECT与AdSense帐户的所有者:如果我尝试使用JSON文件有两个不同的错误

    下面的代码失败 “错误”:“unauthorized_client” “error_description”:“客户未经授权使用此方法检索访问令牌。”

  2. 如果我评论的SETSUBJECT: “理由”: “noAdSenseAccount”, “消息”: “用户没有AdSense帐户。”

代码:

<?php 

require_once '../../vendor/autoload.php'; 

putenv('GOOGLE_APPLICATION_CREDENTIALS=../conf/Mercury-testlpstats.json'); 

$client = new Google_Client(); 
$client->useApplicationDefaultCredentials(); 

$client->addScope('https://www.googleapis.com/auth/adsense.readonly'); 

//$client->setSubject('[email protected]'); 


$service = new Google_Service_AdSense($client); 


$startDate = '2017-05-01'; 
$endDate = '2017-05-01'; 
$optParams = array(
    'metric' => array('INDIVIDUAL_AD_IMPRESSIONS', 'EARNINGS'), 
    'dimension' => 'DATE', 
    'filter' => array('AD_UNIT_ID==ca-pub-XXXX:YYYY'), 
    'useTimezoneReporting' => true 
); 

$report = $service->accounts_reports->generate('pub-ZZZZZ', $startDate, $endDate, $optParams); 

使用OAuth

我在https://console.cloud.google.com/apis/credentials/oauthclient/创建帐户的OAuth第2次尝试。当我查看AdSense API时,我的帐户出现在https://console.cloud.google.com/apis/api/adsense.googleapis.com/overview的授权用户列表中。

我已经下载了相应的JSON和改变了我的代码,但它仍然说:

  • “insufficientPermissions” 如果我设置$客户 - > useApplicationDefaultCredentials();
  • “需要登录”,否则

require_once '../../vendor/autoload.php'; 

$client = new Google_Client(); 
$client->setAccessType('online'); 
$client->setAuthConfigFile('/home/al1/lpstats/conf/client_secret_725834039890-klbuc13f8089rjh7eis439b93n7sqqfv.apps.googleusercontent.com.json'); 
$client->addScope('https://www.googleapis.com/auth/adsense.readonly'); 

$service = new Google_Service_AdSense($client); 

$startDate = '2017-05-01'; 
$endDate = '2017-05-01'; 

$optParams = array(
    'metric' => array('INDIVIDUAL_AD_IMPRESSIONS', 'EARNINGS'), 
    'dimension' => 'DATE', 
    'filter' => array('AD_UNIT_ID==ca-pub-5035025648894332:3442683203'), 
    'useTimezoneReporting' => true 
); 

$report = $service->accounts_reports->generate('pub-5035025648894332', $startDate, $endDate, $optParams); 
+0

您正在进行身份验证的用户没有您需要向拥有adSence帐户的用户进行身份验证的帐户。 – DaImTo

+0

谢谢。这就是我在使用setSubject和AdSense帐户所有者的电子邮件时所要做的。我应该使用别的服务帐号吗? –

+0

当您使用服务帐户进行身份验证时,setSubject用于模拟用户。确保服务帐户有权访问用户adsence帐户 – DaImTo

回答

0

unauthorized_client

意味着你与authencating的用户没有访问Adsence帐户您试图访问。

服务帐户支持

有一些不支持的服务帐户谷歌的API。最明显的将是YouTube API,它甚至没有与其他用户共享您的帐户的方式。

还有其他人可以让您与其他用户分享您的数据,但要求有问题的用户回复电子邮件通知。 Blogger是一个,Adsence显然是另一个。

解决方案

您需要使用的oauth2使用谁有权访问有问题的adsence帐户的用户进行身份验证。一旦保存刷新令牌,并使用刷新令牌在您的cron作业中请求新的访问令牌,即可验证您的代码。