0

我正在尝试通过 AdSense 管理 API 从 AdSense 帐户中检索数据。

连接到我的 AdSense 帐户后,我已使用 Google APIs Explorer 成功检索数据。

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

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

如果我尝试使用带有两个不同错误的 json 文件,则以下代码将失败:

  1. 如果我将 setSubject 与 AdSense 帐户的所有者一起使用:“error”:“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('AdTech@Lagardere-Pub.com');


$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 帐户。当我检查 AdSense API 时,我的帐户出现在https://console.cloud.google.com/apis/api/adsense.googleapis.com/overview的授权用户列表中。

我已经下载了相应的 JSON 并更改了我的代码,但它仍然显示:

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

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);
4

1 回答 1

1

未经授权的客户端

表示与您进行身份验证的用户无权访问您尝试访问的 Adsence 帐户。

服务帐户支持

有许多不支持服务帐户的 Google API。最引人注目的是 YouTube API,它甚至无法与其他用户共享您的帐户。

还有其他方法允许您与其他用户共享您的数据,但要求相关用户回复电子邮件通知。Blogger 是一个,而 Adsence 显然是另一个。

解决方案

您将需要使用有权访问相关广告帐户的用户使用 Oauth2 进行身份验证。保存刷新令牌后验证您的代码,并使用刷新令牌在您的 cron 作业中请求新的访问令牌。

于 2017-06-01T10:18:43.207 回答