AdSense API from Scratch Part 1 - Getting Started

Wednesday, June 15, 2011 | 12:54 PM

Labels: , ,

One of the most common issues AdSense API developers face is how to get started, particularly due to the challenges posed by using SOAP.

This blog post is the first in a series that will teach you how to build an AdSense API application from scratch. This is our attempt at providing some improved starter documentation, by describing the whole process from zero to an AccountService-enabled implementation of the AdSense API, using best practices.

Our choice of technology for this series is PHP 5 with native SOAP support, for several reasons:

  • it’s one of the easiest to set up;
  • it’s one of the most common choices for existing AdSense API developers;
  • it has the benefit of clear and concise code examples that should be readable to most web developers.

It should still be useful to other developers, however, even if they’re not using these technologies; the best practices we discuss are language-independent.


Prerequisites

To follow this guide, you will need:
  • PHP version 5.2 or higher (this guide was developed with version 5.3.2)
  • SoapClient (may require compiling PHP with --enable-soap or installing a separate package, depending on your setup)
  • SSL support (may require compiling PHP with --with-ssl or installing a separate package, depending on your setup)

To ensure that you’re set up correctly, try the following:

$ php --re soap
$ php --re openssl


If neither of these commands returns an error, you’re on the right track.

Now let’s try to make a request to make sure we can connect to the AdSense API. For this first part, we’ll attempt to create a publisher account with the AccountService.


Accessing the AccountService

In order to handle the mapping between SOAP and PHP objects in a user-friendly manner, SoapClient requires a WSDL. We’ll also need to configure the namespace that AdSense API SOAP objects exist in, so that they may be instanced correctly.

$wsdl = 'https://sandbox.google.com/api/adsense/v3/AccountService?wsdl';
$namespace = 'http://www.google.com/api/adsense/v3';


However, we don’t want to retrieve a new version of this WSDL every time we connect to a service, so we’ll need to do some caching. Fortunately, SoapClient has features to handle caching automatically, which we’ll use:

$options = array(
  'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
  'encoding' => 'utf-8',
  'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP,
  'user_agent' => 'PHP-SOAP/'. phpversion() . ',gzip',
  'cache_wsdl' => WSDL_CACHE_BOTH);
$accountService = new SoapClient($wsdl, $options);


We’re also enabling GZip compression, so that all communication between our application and the AdSense API servers can be compressed.


Request headers

In the AdSense API, authentication is performed via the use of SOAP headers. For account creation, we only need to provide the developer email and password. We’ll set the display locale as well, to show how easy it is to get the AdSense API to work in your language.

Using SoapClient, the setup is relatively straightforward:

$developer_email_header = new SoapHeader($namespace, 'developer_email',
    'INSERT_DEVELOPER_EMAIL_HERE');
$developer_password_header = new SoapHeader($namespace, 'developer_password',
    'INSERT_DEVELOPER_PASSWORD_HERE');
$display_locale_header = new SoapHeader($namespace, 'display_locale',
    'en_US');
$accountService->__setSoapHeaders(array($developer_email_header,
    $developer_password_header, $display_locale_header));



Making the request

All that’s left now is making the actual request, according to the reference documentation for createAccount:

try {
  $result = $accountService->createAccount(array(
      'loginEmail' => 'INSERT_PUBLISHER_EMAIL_HERE',
      'entityType' => array('value' => 'Individual'),
      'websiteUrl' => 'http://www.test.com',
      'websiteLocale' => 'en',
      'usersPreferredLocale' => 'en_US',
      'emailPromotionsPreference' => true,
      'synServiceTypes' => array(
        array('value' => 'ContentAds'),
        array('value' => 'SearchAds')),
      'developerUrl' => 'code.google.com'));
} catch (SoapFault $e) {
  print_r($e);
  exit(1);
}


This will attempt to create an account with two syndication service types, and print out an exception if it fails. If it doesn’t, we can display the results by doing:

if (isset($result->return)) {
  foreach ($result->return as $ad_client) {
    print "Ad client of type \"" . $ad_client->type->value . "\" and id \""
        . $ad_client->id . "\" was added.\n";
  }
}


That’s it for our first API call! You can find the full example here.


Account Association

Association is very similar to creation, with the difference that instead of creating a new AdSense account, you’re simply linking to an existing AdSense account belonging to your user. The request takes different parameters, namely the phone number and postal code hints:

if (isset($result->return)) {
  foreach ($result->return as $ad_client) {
    print "Ad client of type \"" . $ad_client->type->value . "\" and id \""
        . $ad_client->id . "\" was added.\n";
  }
}


Next steps

Next week we’ll be taking a deeper look at account creation and association, with a focus on error handling and other best practices.

In the meantime, if you have any questions or comments, be sure to let us know in the forum!