How to Use Google AdWords API with PHP to get keyword CPC and monthly search volume

0
753

I wanted to use Google AdWords API to generate keyword idea for my research tool. I started searching online and read lots of forum posts. And it seems like its next to impossible to understand this whole process hence I wrote my own function with the help of google documentation.

Step 1: Choose or create an AdWords manager account

You must have an AdWords manager account to apply for access to the AdWords API. Remember Google would like to provide access to AdWords API access only to genuine users. So its always a good idea to create a business account (Business Email) first and then apply for a Manager Account.

Manager accounts cannot be created using the same email address as an existing AdWords account. You must, therefore, use an email address that hasn’t already been associated with an AdWords account to create your manager account.

Note that the manager account you select has no effect on the set of AdWords accounts that your API token can access. However, linking this manager account to your company’s active AdWords accounts will streamline the app review process, and reduce the number of times you need to go through the authentication process to manage your accounts via the API. For details, see the Help Center article about linking accounts.

Step 2: Make an Application to get access to AdWords API

When you start applying for API access you will be asked several questions. But the most important question they will ask you is what is your intention of use. I would strongly recommend that don’t lie. You know that Google knows everything. So tell them exactly what is your intent so that they can understand AdWords API will not be used outside there policies. Here you can learn more about permissible use of the AdWords API

Following is a list of permissible uses:

Permissible Use Description
Ad creation/management Provide access to all services of the API for creating and managing AdWords campaigns, ad groups, ads, and keywords.
Reporting Only make calls to the report service (i.e. read-only calls). This is for developers who only use the API to pull reports.
Researching keywords Allow the token to access TargetingIdeaService and TrafficEstimatorService. This is only used by tools requiring keyword suggestions or traffic to help facilitate the creation and management of AdWords campaigns.

 

Once you are done with your application. You will be given test access to your API’s

Access level Can access… Daily limit Daily request limit Level
Test account access Test accounts 10,000 operations / day 1,000 requests / day  Test
Basic access Test and production accounts 10,000 operations / day 1,000 requests / day  Basic
Standard access Test and production accounts Unlimited operations / day Unlimited requests / day  Standard

 

Standard access
Standard access allows the developer token to execute an unlimited number of operations and report requests per day. Standard access level will only be granted to developers who require unlimited AdWords API operations (typically large companies or tools which serve many users).

Applying for Standard access

If you currently have basic access level and you would like to apply for unlimited AdWords API operations, fill out the standard access application form.

If your tool is external, please be prepared to provide demo log-in access to your tool. Note that your tool must comply with the Required Minimum Functionality.

Step 3 Make Your First API Call

In this guide we’re going to get you to your first API call, breaking it down step by step. This will open the door to take full advantage of the AdWords API.

Overview of the process
You set up API access by obtaining a few required authentication credentials, creating some test accounts, and adding the authentication and account details to a configuration file for your client library.

Once the config file is set up, you’re ready to make calls against the API. Here are the steps to get going:

  1. Request a developer token.
  2. Create test accounts.
  3. Get a client library.
  4. Set up authentication via OAuth2.
  5. Get an OAuth2 refresh token and configure your client.
  6. Make your first API call.

 

Request a developer token
A developer token from Google allows your app to connect to the AdWords API. If you haven’t already, perform the steps in the Sign Up guide to obtain a developer token. After signing up, you’ll receive a developer token that is pending approval.

Note: While you’re waiting for your developer token to be approved, you can start developing immediately with the pending token you received during sign up, using a test manager account (see below).
Your pending developer token must be approved before using it with production AdWords accounts.

Create test accounts
Perform the following steps to create a test manager account, a test client account, and a few campaigns to populate the test client account.

Note: Calls to test accounts won’t serve ads, nor do they count against any limits.

  1. Go to the AdWords manager accounts page and create a test manager account.
  2. Use the AdWords web interface to create a test client account under the test manager account you created above. While logged in to AdWords as your test manager account, any client accounts you create will automatically be test accounts.
  3. Create a few test campaigns under the test client account in the AdWords UI.
  4. Take note of the client customer ID for the new test client account, and save it: You’ll add this to your config file later.

Note: The word “client” here refers to an AdWords client account – not the client application you will be creating.

Use the developer token of your production manager account when making requests against the test manager account. Even if it’s not approved yet, the token will still work on test accounts, including the ones you just created.

Get a client library
I understand that it gets frustrating when you see the word composer. So, friends, I have downloaded all dependencies and uploaded the file as a new git. Please download the whole Google AdWords API code from this git repo.

Set up OAuth2 authentication
Your app will need to access user data and contact other Google services on your behalf. Authentication via OAuth2 allows your app to operate on behalf of your account.

To enable your app to access the API, you need an OAuth2 client ID and client secret.

Note: “Client” in this case means your client app, not an AdWords client account.

  1. While logged in with your manager account credentials, open the Google API Console Credentials page.
  2. From the project drop-down, choose Create a new project, enter a name for the project, and click Create.
  3. Select Create credentials and choose OAuth client ID.
    You may be prompted to set a product name on the Consent screen; if so, click
  4. Configure Consent Screen, supply the requested information, and click Save to return to the Credentials screen.
  5. Under Application type, choose Other for this tutorial. Enter a name in the space provided.

For the AdWords API, Other is the option to choose for an installed application flow. Before you build your app, you’ll want to read up on the difference between installed and web applications, and choose the appropriate type for the app you’re building.
Click Create. The OAuth2 client ID and client secret appear. Copy and save these items. You will add them to your configuration file in the next step.

 

Step 4 Implement your API

For security reasons, Google AdWords API should only be accessed via HTTPS. However, the above code does not set appropriate SSL settings on the https:// stream context. It fails to assign Certificate Authority (CA), turns the verify_peer option to ON, specifies allowed ciphers etc. It uses the stream_context_get_default() function to get the default context, which on all PHP versions below PHP 5.6.x (see references), does not validate the CA by default.
Because of this, the application may retrieve data from untrusted sources pretending to be adwords.google.com.

Here is the Code below:

function GetKeywordIdeasExample(AdWordsUser $user) {
  // Get the service, which loads the required classes.
  $targetingIdeaService =
      $user->GetService('TargetingIdeaService', ADWORDS_VERSION);
  // Create seed keyword.
  $keyword = 'mars cruise';
  // Create selector.
  $selector = new TargetingIdeaSelector();
  $selector->requestType = 'IDEAS';
  $selector->ideaType = 'KEYWORD';
  $selector->requestedAttributeTypes = array('KEYWORD_TEXT', 'SEARCH_VOLUME',
      'CATEGORY_PRODUCTS_AND_SERVICES');
  // Create language search parameter (optional).
  // The ID can be found in the documentation:
  //   https://developers.google.com/adwords/api/docs/appendix/languagecodes
  // Note: As of v201302, only a single language parameter is allowed.
  $languageParameter = new LanguageSearchParameter();
  $english = new Language();
  $english->id = 1000;
  $languageParameter->languages = array($english);
  // Create related to query search parameter.
  $relatedToQuerySearchParameter = new RelatedToQuerySearchParameter();
  $relatedToQuerySearchParameter->queries = array($keyword);
  $selector->searchParameters[] = $relatedToQuerySearchParameter;
  $selector->searchParameters[] = $languageParameter;
  // Set selector paging (required by this service).
  $selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
  do {
    // Make the get request.
    $page = $targetingIdeaService->get($selector);
    // Display results.
    if (isset($page->entries)) {
      foreach ($page->entries as $targetingIdea) {
        $data = MapUtils::GetMap($targetingIdea->data);
        $keyword = $data['KEYWORD_TEXT']->value;
        $search_volume = isset($data['SEARCH_VOLUME']->value)
            ? $data['SEARCH_VOLUME']->value : 0;
        $categoryIds =
            implode(', ', $data['CATEGORY_PRODUCTS_AND_SERVICES']->value);
        printf("Keyword idea with text '%s', category IDs (%s) and average "
            . "monthly search volume '%s' was found.\n",
            $keyword, $categoryIds, $search_volume);
      }
    } else {
      print "No keywords ideas were found.\n";
    }
    // Advance the paging index.
    $selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
  } while ($page->totalNumEntries > $selector->paging->startIndex);
}

 

Here is the results:

Keyword: cooling capacity window, match: EXACT, cpc: $0.00, vol: 0
Keyword: capacity window air, match: EXACT, cpc: $0.00, vol: 0
Keyword: oral-b professional deep sweep 4000 electric rechargeable toothbrush, match: EXACT, cpc: $0.00, vol: 0
Keyword: oral, match: EXACT, cpc: $0.00, vol: 347
Keyword: professional, match: EXACT, cpc: $0.00, vol: 721
Keyword: sweep, match: EXACT, cpc: $0.00, vol: 101
Keyword: toothbrush, match: EXACT, cpc: $0.16, vol: 17746
Keyword: oral b, match: EXACT, cpc: $0.26, vol: 17768
Keyword: b professional, match: EXACT, cpc: $0.00, vol: 0