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


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

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',
  // Create language search parameter (optional).
  // The ID can be found in the documentation:
  // 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


  1. … [Trackback]

    […] There you will find 16616 more Infos: […]

  2. Мы ппредоставим любую запасная часть быстро прямо в пункт выдачи оптовые поставщики автозапчастей для иномарок – дом автозапчастей.
    Помимо желания предоставить колосольный комплект авто аксессуаров, наши сотрудники постоянно выполняем работы над конечным качеством обслуживания . Из-за многообразия параметров и вариантов автомашин каждой марки, наши сотрудники использовали пошаговую систему заявки. Этим способом, мы хотим исключить упущений и покупок несвоевременных запасных частей.
    Выберите у нас запасные части и дополнительно получайте дискаунт на другой заказ!

  3. Springtime cleaning is actually not only commonplace to remove dirt as well as filth. But our experts need to have to administer an review of winter months clothes. Coming from unnecessary things to do away with, you need to have to clean and identify the storage space. Get rid of the trash and also provide your own self yet another guarantee certainly not to spare unneeded junk. Well-maintained the wall structures and also ceilings, clean the home windows, allow the spring right into your house, drive off the inactivity.

    Washing in NYC – is the arrangement of specialized solutions for spring cleansing of facilities and also adjoining locations, along with preserving sanitation. The blend of high-grade work and also inexpensive rates is actually a particular feature that differentiates our cleansing firm in the NJ cleaning services market.
    Our motto: ” The very best top quality – affordable price!” and also you could be sure of that! In our company, really budget-friendly costs for all types of cleaning company.
    Our company guarantee you the provision of professional cleaning services at a high level. Pros skillfully learn the strategies of cleaning along with using modern state-of-the-art equipment and specialized chemicals. Along with all this, the prices for our companies are actually considerably less than the major cleansing companies.

    Getting such a solution as “Spring Cleaning” in our business, you receive the option of high quality cleaning of the neighboring territory of your house. Our team deliver cleaning up where others may certainly not deal. Our experts will certainly concern you even if you are at the some others end of the world as well as do the cleansing at the highest level. Merely give us a call.

    Detailed house cleaning Greenwich Village – spring cleaning

  4. I not to mention my buddies appeared to be digesting the best
    information located on your web blog while unexpectedly I had an awful feeling I had not thanked the
    site owner for those secrets. The boys appeared to be absolutely happy to
    see them and already have really been tapping into
    these things. We appreciate you truly being well considerate and also for having these kinds of fabulous themes most people are
    really desirous to learn about. My honest apologies for not
    expressing gratitude to earlier.

  5. Наша компания занимается расскруткой продвижение сайта буржунет совершенно не дорого. В случае, если у вас существует свой бизнес, тогда рано или поздно вы лично осознаете, что без оптимизация и продвижение сайтов сшау вас нет возможности работать дальше. Сейчас фирма, которая подумывают о собственном будущем развитии, должна иметь веб-сайт для seo продвижение сайтов google. продвижение англоязычного сайта в google- способ, используя который возможно приобретать новых покупателей, и дополнительно получить проценты, с тем чтобы рассказать об наличии вашей собственной производственной компании, её продуктах, функциях. Специализированная международная фирма сделать для вашей фирмы инструмент, с помощью которого вы сможете залучать правильных партнеров, получать прибыль и расти.Продающийся сайт- лицо фирмы, в связи с этим имеет значение, кому вы доверяете создание своего веб страницы. Мы – команда профи, которые имеют обширный практический опыт конструирования электронную коммерцию с нуля, направления, разработанного типа. Сотрудники нашей фирмы неизменно действуем по результатом. Международная компания сумеет предоставить всем нашим заказчикам профессиональное сопровождение по доступной антикризисной расценке.Вы можете сделать заказ онлайн-визитку, рекламный сайт. Не сомневайтесь, что ваш портал будет разработан высококлассно, с разными самыми новыми технологиями.

    продвижение англоязычного сайта в google

  6. MKsOrb

    […]that may be the end of this post. Right here you’ll obtain some web sites that we believe you’ll value, just click the links over[…]

  7. [url=]prazosin 2[/url] [url=]best price cialis generic[/url] [url=]how to get cialis in australia[/url] [url=]ivermectin buy[/url] [url=]quineprox 900[/url] [url=]can you buy viagra over the counter in canada[/url]

  8. General professional manhattan

    The duty of General construction New York is actually to transfer to the client the entire facility in its entirety, and certainly not such as separately conducted job. Of specific relevance is actually the duty of the overall professional during the course of the big construction of flats of domestic style, commercial facilities, commercial centers.

    custom bathroom vanities;
    Industrial properties.

    Today, the checklist of construction companies includes several company interior decoration. An client as well as a client may spend a ton of time-solving on all company concerns. A more logical solution is to delegate this duty to General building NY.