我試圖通過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