Skip to content

sambavade/google-api-adwords-php

 
 

Repository files navigation

AdWords and DoubleClick Ad Exchange Buyer API PHP Client Library

Google's AdWords and DoubleClick Ad Exchange Buyer API services lets developers design computer programs that interact directly with the AdWords and DoubleClick Ad Exchange Buyer platforms. With these applications, advertisers and third parties can more efficiently -- and creatively -- manage their large or complex AdWords and DoubleClick Ad Exchange Buyer accounts and campaigns.

The AdWords and DoubleClick Ad Exchange Buyer API PHP Client Library makes it easy to write PHP clients to programmatically access AdWords and DoubleClick Ad Exchange Buyer accounts. All client library classes and utilities are in the directory or sub-directory of "src/Google/Api/Ads/AdWords/".

The client library is compatible with all standard PHP 5.2.x and 5.3.x distributions. The library uses the native SoapClient class [http://us3.php.net/manual/en/book.soap.php], which needs to be enabled with the --enable-soap flag if building PHP from source. More information about compatibility can be found in the PHP Compatibility section of this README.

The complete documentation for AdWords and DoubleClick Ad Exchange Buyer API is available from http://www.google.com/apis/adwords/developer/index.html.

What's in the client library?

The client library provides full access to all the functionality of the AdWords and DoubleClick Ad Exchange Buyer API web services plus more. It includes:

  • Data classes: The client library provides all the necessary data classes. For example, it provides the Campaign data class for encapsulating campaign data. These classes are generated automatically from WSDLs.

  • AdWordsUser class: The AdWordsUser class provides methods for setting credentials for accessing AdWords and DoubleClick Ad Exchange Buyer accounts as well as for creating instances of the AdWords and DoubleClick Ad Exchange Buyer Service classes.

  • Helpful utilities: The utilities located under "src/Google/Api/Ads/Common/Util" help you manage XML and import images into the client library.

  • Logger class: This class provides simple methods for logging the SOAP XML messages of all requests and responses.

  • Examples: The PHP client library comes with code examples in the "examples/" directory. We encourage you to use code examples to get started writing your own application. All the code examples are runnable out of the box, but you will have to set your credentials in "src/Google/Api/Ads/AdWords/auth.ini" and you may be required to insert object IDs in where you see "INSERT_***_HERE".

Basic usage

For those of you who have already built PHP clients without using the client library, the AdWordsUser class has methods for setting username, password, client customer ID, application token, developer token, and useragent so that you don't have to write the code to set the request headers. The methods for creating new instances of service classes takes the place of the code for instantiating the stubs that connect to the web services.

In the following example, for using the default constructor,

$user = new AdWordsUser();

the credentials are loaded from the "src/Google/Api/Ads/AdWords/auth.ini" file.

The credentials can also be loaded in one of two ways: supplying an alternative authentication INI file or supplying credentials via the constructor's parameters.

If an authentication INI file is provided and successfully loaded, those values will be used unless a corresponding parameter overwrites it. If the authentication INI file is not provided (e.g. it is null) the class will attempt to load the default authentication file at the path of "../auth.ini" relative to this file's directory. Any corresponding parameter, which is not null will however, overwrite any parameter loaded from the default INI.

$user = new AdWordsUser(NULL, $email, $password, $developerToken, $applicationToken, $userAgent, $clientId);

or

// Used if the account is not using the MCC to log in. $user = new AdWordsUser(NULL, $email, $password, $developerToken, $applicationToken, $userAgent);

How do I start?

Depending on your PHP setup, you will need to extract this library into a directory on your system which is secure and has read/execute permissions to the user executing this library.

There is no need to worry about accessing the WSDLs for the web services; the classes in the client library do it for you. Demo programs in "examples/" directory can be used to get started writing your own client. They should work out of the box if you provide the right credentials; the default behavior is to use credentials from "../auth.ini" relative to the AdWordsUser.php file's directory.

To write a program that accesses AdWords and DoubleClick Ad Exchange Buyer accounts using the client library, do the following:

  1. Set the include path and the require the folowing PHP file:

    // You can set the include path to src directory or reference // AdWordsUser.php directly via require_once. // $path = '/path/to/pda_api_php_lib/src'; $path = dirname(FILE) . '/../../../src'; set_include_path(get_include_path() . PATH_SEPARATOR . $path);

    require_once 'Google/Api/Ads/AdWordsUser/Lib/AdWordsUser.php';

  2. Create an AdWordsUser instance, specifying the credentials at creation time. Or, you can use the default constructor after completing the INI file as described above.

    $user = new AdWordsUser(NULL, $email, $password, $developerToken, $applicationToken, $userAgent, $clientId);

  3. Optionally, enable logging to capture the content of the requests and responses. This example sends the information to a file:

    $user->LogDefaults();

  4. Instantiate the desired service class by calling the getXService method on the AdWordsUser instance. Getting the service will "require" the proper PHP file, so that all classes needed for that service will be loaded.

    $campaignService = $user->getCampaignService('v201206', 'https://adwords.google.com');

    or

    // Defaults to parameters above. $campaignService = $user->GetCampaignService();

    or

    // Uses the sandbox environment. $campaignService = $user->GetCampaignService('v201206', 'https://adwords-sandbox.google.com');

  5. Create data objects and invoke methods on the service class instance. The data objects and methods map directly to the data objects and requests for the corresponding web service.

    // Create new campaign structure. $campaign = new Campaign(); $campaign->name = 'Campaign #' . time(); $campaign->status = 'ACTIVE'; $campaign->biddingStrategy = new ManualCPC(); $campaign->budget = new Budget('DAILY', new Money(50000000), 'STANDARD');

    $operation = new CampaignOperation(); $operation->operand = $campaign; $operation->operator = 'ADD'; $operations[] = $operation;

    // Add campaign. $campaignReturnValue = $campaignService->mutate($operations);

Running the examples

Examples can be run by executing the following on command line from a sub-directory of the "examples/" directory,

$ php Example.php

Running in the sandbox environment

It is recommended that during development of your library, you use the sandbox envinroment:

http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html

To run in this enviroment, you can make one of two changes to your library:

  1. Change the default server (DEFAULT_SERVER) in the settings.ini file, located at "src/Google/Api/Ads/AdWords/settings.ini", to "https://adwords-sandbox.google.com" and then instantiate all service clients with no parameters i.e.

    // Defaults to parameters set in the settings INI file. $campaignService = $user->GetCampaignService();

  2. Include the sandbox server in all service client instantiations i.e.

    // Uses the sandbox environment. $campaignService = $user->GetCampaignService('v201206', 'https://adwords-sandbox.google.com');

Authentication Options

Authentication in the client library is handled by the AdWordsUser object, which has the following options.

  • Email and Password: The email and password of the AdWords account or MCC account is used. When the first service is created an AuthToken is generated using the ClientLogin API using these credentials. The email and password can be be stored in the auth.ini file, passed into the AdWordsUser constructor, or set individually using the SetEmail() and SetPassword() methods. If the AuthToken expires (they are valid for up to two weeks) it can be regenerated using the RegenerateAuthToken() method.

  • AuthToken: An existing AuthToken is used. It is recommended to reuse AuthTokens since too many requests to the ClientLogin API can lead to errors. You can pass the authToken in the contructor or set it using the SetAuthToken() method.

  • OAuth: The OAuth protocol is used. This protocol provides a way to access an AdWords and DoubleClick Ad Exchange Buyer account without needing possesion of the email or password. Instead a permanent OAuth token is requested, authorized by the user in their browser, and then upgraded for full access. The AdWordsUser provides the RequestOAuthToken(), GetOAuthAuthorizationUrl(), and UpgradeOAuthToken() methods to help simplify the process. Existing OAuth tokens can be used by passing them into the contructor or by using the SetOAuthInfo() method. See the example UseOAuth.php for an example of how to use these methods.

How do I enable logging?

The client library uses a custom class for all logging purposes and is exposed through the Logger.php file. There are two loggers within this class described below.

  • REQUEST_INFO_LOG: Logs all requests from the client library along with information such as the timestamp, email, service, method, request Id, response time and which server was used. The default behavior is to log this information to "logs/request_info.log" relative to your project's home directory.

  • SOAP_XML_LOG: Logs all incoming and outgoing SOAP requests/responses. The default behavior is to log this information to "logs/soap_xml.log" relative to your project's home directory. Sensitive information, such as authentication tokens, will be stripped.

Logging can be enabled using the following methods.

  • $user->LogDefaults(): Logs request information for all requests, but only logs SOAP XML for requests that resulted in an error.

  • $user->LogErrors(): Only logs request information and SOAP XML for requests that resulted in an error.

  • $user->LogAll(): Logs request information and SOAP XML for all requests.

You can use the methods of the Logger class directly for even more control over how requests are logged.

Encoding special characters

The AdWords and DoubleClick Ad Exchange Buyer API requires that all requests are UTF-8 encoded. Because UTF-8 is backwards compatible with ASCII, alphanumeric and punctuation characters from other ASCII based encodings (such as ISO 8859-1 or Windows-1252) are compatible and don't request any conversion. However, many special characters are not compatible between encodings and need to be manually converted before being passed in to the client library. This can be done using the PHP function iconv().

For example, to convert a Windows-1252 encoded string containing the euro sign to UTF-8 you could use the following code:

$price = iconv('WINDOWS-1252', 'UTF-8', '€40');

Alternatively you can choose to represent the special characters as XML character entities. For example, the euro sign (€) is represented as the XML entity "€". The format of the XML entity is "&#x" followed by the Unicode hex code point for the character. You can look up the code point for a given character using the charts on unicode.org (http://www.unicode.org/charts/).

The PHP SoapClient class, and hence the PHP client library, assumes that the values passed in to the services are unescaped and will automatically escape them. For XML entities like the one above this can have the unintended consequence of escaping the ampersand, breaking the entity. To work around this issue we recommend that you use the PHP function html_entity_decode() to to unescape these entities before passing them in to the client library.

For example, to unescape a string containing the XML character entity for the euro sign to a UTF-8 string you could use the following code:

$price = html_entity_decode('€40', ENT_QUOTES, 'UTF-8');

Error messages about Timezones

If you are getting warnings about setting your default timezone, you will need to do so in your php.ini file setting the field:

date.timezone=America/Los_Angeles

More information is available here: http://www.php.net/manual/en/timezones.php

Already defined classes

Since PHP 5.2 does not have namespaces, there is the possibility that one of the automatically generated classes used by the API has the same name as an existing class in your environment. Classes that were found to conflict with PHP native classes have already been renamed:

'DateTime' => 'AdWordsDateTime' 'Target' => 'AdWordsTarget'

If you find that there are additional conflicts in your environment you have the following options:

  1. Rename the class in the corresponding *Service.php file and update the mapping in *Service::$classmap to reference the new class name. Be aware that the same type can be defined in multiple services.

  2. Rename the conflicting class in your system. This will likely not be possible if the class is part of another library.

  3. Regenerate the classes from the WSDLs using pseudo-namespace support. See the section "Pseudo-namespace support" for more information.

Pseudo-namespace support

Pseudo-namespaces can be used to help avoid class or function name conflicts due to PHP 5.2's lack of native namespace support. This involves prepending all class names with a unique string. When generating classes from the WSDLs you have the option to enable pseudo-namespaces, so for example the type "Campaign" would produce a class called "GoogleApiAdsAdWords_Campaign".

For the sake of backwards compatibility this feature is not enabled by default. It can be enabled by setting wsdl2php.enablePseudoNamespaces to "true" in the build.properties file and running the "generate" target in build.xml. This requires the source build of the library.

Enabling pseudo-namespaces for an existing application make cause your code to break, as class names have changed. To avoid this you should use the following practices when writing your application:

  • Instead of calling the constructor directly, use the service's Create() method to construct new objects. This method only requires that you enter the original type name, and it takes an optional array or parameters which can be flat or associative.

    $keyword1 = $service->Create('Keyword'); $keyword2 = $service->Create('Keyword', array('mars', 'BROAD')); $keyword3 = $service->Create('Keyword', array('text' => 'jupiter', 'matchType' => 'BROAD'));

  • Instead of using "instanceof" to determine the type of an object returned by the API, test the value of its *Type field. All classes that extend a base class have this field available.

    if ($criterion->CriterionType == 'Keyword') { ... }

PHP Suhosin Patch

With some PHP installations, it has been found that the Suhosin patch prevents correct usage of the AdWords and DoubleClick Ad Exchange Buyer API PHP Client Library. It is believed that the patch is catching memory leaks caused by an underlying library, but we are still investigating the root cause. Errors caught by the Suhosin patch may look like the following:

ALERT - canary mismatch on efree() - heap overflow detected (attacker 'REMOTE_ADDR not set', file '...', line ...)

At this time we recommend using versions of PHP that do not have the Suhosin patch applied. More information about the Suhosin patch can be found here:

http://www.hardened-php.net/suhosin/index.html

Note: this patch is applied by default to many standard distributions, including the current Ubuntu distribution - 5.2.4-2ubuntu5.7.

PHP Compatiblity

The PHP client library supports most 5.2.x and 5.3.x distributions. If you find the library is not compatible with your setup, please let us know here:

http://code.google.com/p/google-api-adwords-php/wiki/PhpCompatibility

External dependencies

Run environment:

Build environment:

Where do I submit bug reports and feature requests?

Bug reports and feature requests can be submitted at http://code.google.com/p/google-api-adwords-php/issues/list.

Questions can be posted to the AdWords API forum: http://groups.google.com/group/adwords-api/

Authors: api.arogal@gmail.com (Adam Rogal) eric.koleda@google.com (Eric Koleda)

Maintainers: api.arogal@gmail.com (Adam Rogal) eric.koleda@google.com (Eric Koleda)

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • PHP 99.9%
  • XSLT 0.1%