我试图通过AdSense Management API从AdSense帐户中检索数据。使用Google AdSense Management API访问数据 - PHP
我与AdSense帐户关联时,使用Google API Explorer成功检索了数据。
我现在试图从将在crontab中运行的PHP脚本获取这些数据。
我的理解是我需要一个我创建的Service account
,并生成了一个json文件。
如果我用SETSUBJECT与AdSense帐户的所有者:如果我尝试使用JSON文件有两个不同的错误
下面的代码失败 “错误”:“unauthorized_client” “error_description”:“客户未经授权使用此方法检索访问令牌。”
如果我评论的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);
您正在进行身份验证的用户没有您需要向拥有adSence帐户的用户进行身份验证的帐户。 – DaImTo
谢谢。这就是我在使用setSubject和AdSense帐户所有者的电子邮件时所要做的。我应该使用别的服务帐号吗? –
当您使用服务帐户进行身份验证时,setSubject用于模拟用户。确保服务帐户有权访问用户adsence帐户 – DaImTo