2017-05-31 183 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作業中請求新的訪問令牌,即可驗證您的代碼。