Tutorials

How to Access Google Adsense Reports

So, Admob was acquired a while ago by Google and it was recently announced that the publisher reports by Admob would no longer be available through the old APIs. Instead, they now have to be retrieved through the AdSense API — which is based on OAuth 2.0 and thus a real pain for those just getting started.

Turns out, the process is quite straight-forward but extremely poorly documented. You can go through the AdSense reporting docs, the Google API library and the OAuth 2.0 specs but you would soon be lost. After spending a couple of days decoding the requirements, I found out the bare-metal approach to accessing the stats. And here is how.

First, you really should read up on the OAuth 2.0 flow but the basic idea is that you first try to get an access token. When you do, the user is presented with a consent screen where they click on ‘Allow’ and the browser is redirected back so that you can save the access token. Of course, this means that you cannot access the data without the user being present. To do that, you need to request offline access. When you do, you are given a refresh token instead of an access token (and the user is warned that offline access is being requested).

If the user consents, you can save the refresh token and use it to get an access token later on. So, the deal is, request for a refresh token, save it somewhere and later, use it to request an access token and use that to get the reports.

The code below shows the two steps in two functions.

set_include_path(get_include_path() . PATH_SEPARATOR . 
      dirname(__FILE__) . '/google-api-php-client/src');

require_once('Google/Client.php');
require_once('Google/Service/AdSense.php');

That part is just to set up the google-api-php-client that you can get from over here.

The first function gets the refresh token that you can save anywhere.

 
public function get_refresh_token() {
    $client_id = 'YOUR_CLIENT_ID'; 
    // looks like: yyYzz-zzZzz.apps.googleusercontent.com
    $client_secret = 'YOUR_CLIENT_SECRET'; 
    // looks like xxxx-xxxxxxxxxxxxxxxxxxxxx
    $redirect_uri = 'http://' .  $_SERVER['SERVER_NAME'] . '/adsenseauth.php'; 

    $client = new Google_Client();
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->addScope('https://www.googleapis.com/auth/adsense.readonly'); 
    $client->setAccessType('offline');

    if(isset($_GET['code']) && $_GET['code'] != '') { 
        $code = $_GET['code'];

        // sleep(30); // This can help if your server time is off a bit 
        $client->authenticate($code);
        $access_token = $client->getAccessToken();
        $tokens = json_decode($access_token, true);
        $refresh_token = $tokens['refresh_token'];

        echo $refresh_token; // or save it somewhere 

        return;
    }

    $authUrl = $client->createAuthUrl();
    redirect($authUrl);

    return ;
}

To get a client_id and client_secret, you need to create an API Project in your Google Management Console. Make sure you give it a correct name and email along with all the other required information or you will get weird errors during authorization. Here’s what you need for that:

  1. Go to https://console.developers.google.com/
  2. Enable AdSense Management API from APIs & Auth -> APIs
  3. Edit Consent Screen from the same menu and enter required information
  4. In Credentials screen, create a new Client ID and take note of the ID and secret from there

Also make sure you set the $redirect_uri to this same page (the one which has this function and make sure you call this function in that page, of course. After that, you can go to this page and should be taken to the OAuth consent screen.

Once that is done, it’s time to access the stats using the following function.

 
public function get_stats() { 

    $ch = start_curl_session();

    $start_date = 'YYYY-mm-dd';
    $end_date = 'YYYY-mm-dd';

    $client = new Google_Client();
    $client->setClientId($this->client_id);
    $client->setClientSecret($this->client_secret);

    // the refresh token saved by get_refresh_token() 
    $refresh_token = $refresh_token;

    try {
        $client->refreshToken($refresh_token);
        $access_token = $client->getAccessToken();
        $client->setAccessToken($access_token);

        $service = new Google_Service_AdSense($client);

        /* If you want to get the account list, you can use the following: 
        $accounts = $service->accounts->listAccounts(); 
            foreach($accounts as $account) { 
        } 
        */ 

        $opt_params = array(
            'metric' => array('earnings', 
                              'clicks', 
                              'individual_ad_impressions'), 
            'dimension' => array('date', 'ad_unit_name')
        );

        $reports = $service->reports->generate($start_date, $end_date, $opt_params);

        $rows = $reports['rows'];

    }  catch(Exception $e) {
        // do whatever 
    } 
} 

It’s pretty self-explanatory. The only thing is to request the correct metrics and dimensions that you can see here.

Advertisements

1 thought on “How to Access Google Adsense Reports”

  1. Hi, can you email the complete code, and the tutorial to use it.
    I was puzzled here… Pleaseeee
    Thanks
    Linda Chun

Comments are closed.