2

我正在尝试使用 PHP 脚本连接到 AdSense API。我开始使用谷歌的本教程:https ://developers.google.com/api-client-library/php/start/get_started#build-the-client-object

但是,我没有设法连接。这是我尝试过的:

$client = new Google_Client();
$client->setApplicationName("AppName");
$client->setDeveloperKey(API_Key);
$client->setAuthConfigFile('../AdSense/google-api-php-client/client_secret.json');

$service = new Google_Service_AdSenseTest($client);
$results = $service->testReportsGenerate();

foreach($results as $item)
{
    echo $item;
}

我遇到了一些问题,主要问题是代码无法识别“Google_Service_AdSenseTest”类 - 即使代码建议了它。所以我真正的问题是:如果我想从 AdSense 中提取数据,我应该使用什么服务?以及如何设置所需的参数(意思是 - 要获取哪些维度和指标)?

谢谢你。

4

2 回答 2

-1

您需要像对每个单独的 google api 一样实现 OAuth 请求(如果您使用 codeigniter,请使用 Phil Sturgeon 的 OAuth2.0 协议,实现良好。)或任何 oauth2 客户端脚本都可以。

google api 库在这里: https ://github.com/googleapis/google-api-php-client-services 。使用 composer 安装这些库。

adsense 课程在这里:https ://github.com/googleapis/google-api-php-client-services/blob/master/src/Google/Service/AdSense.php

向 google 发出请求的类/函数必须设置一个 oauth 客户端并指定一个重定向 url(这又必须在 google api 控制台上注册)

范围是
../auth/adsense ../auth/adsense.readonly

一切都完成后,您可以提出请求。

我使用 Codeigniter 为 searchconsole、adsense 和其他有用的库实现了它,它们都非常棒。此外,我还连接了谷歌表格,因此我可以在需要时在谷歌表格中获得每份报告。

使用 oAuth 访问令牌,代码:

$client = new Google_Client();
$adsenseService = new Google_Service_AdSense(...);
$client->setApplicationName("Adsense Console");
                        $client->setDeveloperKey($apiKey);
                        $client->setAccessToken( $token->access_token );

$params = array('maxResults' => 1000, 'pageToken' => null, 'alt' => 'json', 'fields' => array(), 'prettyPrint' => true, 'quotaUser' => '', 'userIp' => '' );

$accounts = $adsenseService->accounts->listAccounts($params);
//this will print a json array 
echo '<pre>' ; print_r($accounts); echo '<pre>'; die();

对于广告客户,

$adsense->adclients->listAccountsAdclients($params);

参数参考在这里, https://developers.google.com/adsense/management/v1.4/reference/accounts/adclients/list#try-it

于 2019-03-20T18:10:10.290 回答