2

I'm trying to connect to AdSense API using a PHP script. I started using this tutorial by google: https://developers.google.com/api-client-library/php/start/get_started#build-the-client-object

However, I didn't manage to connect. This is what I've tried:

$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;
}

And I came across a few problems, the main one is that the code doesn't recognize the "Google_Service_AdSenseTest" class - even though the code suggested it. So my real question is this: What service should I use if I want to pull data from AdSense? And how do I set the needed parameters (meaning - which dimensions and metrics to get)?

Thank you.

Bramat
  • 979
  • 4
  • 24
  • 40

2 Answers2

-1

You need to implement OAuth requests as you do for every single google api, (use Phil Sturgeon's OAuth2.0 protocol if you use codeigniter, well implemented.) or any oauth2 client scripts will do.

The google api library is here : https://github.com/googleapis/google-api-php-client-services. Use composer to install these libraries.

The adsense class is here : https://github.com/googleapis/google-api-php-client-services/blob/master/src/Google/Service/AdSense.php

The class/function which makes the request to google must setup an oauth client and specify a redirect url (which in turn must be registered on google api console )

The scopes are
../auth/adsense ../auth/adsense.readonly

Once everything is done, you can make a request.

I implemented it with Codeigniter for searchconsole, adsense and other useful libraries they all works awesome. Besides i connected google sheets as well, so every report is available to me in google sheet as it is needed.

With oAuth Access token, The code :

$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();

for adclients,

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

The params ref is here, https://developers.google.com/adsense/management/v1.4/reference/accounts/adclients/list#try-it

Arun Panneerselvam
  • 2,263
  • 1
  • 17
  • 24