Sunday, September 8, 2013

How to integrate Google Adwords API into Codeigniter?

One blogger gave me idea
Just add all the api documents to the third_party folder and require the library from your controller or library and voilà!

Figure: Google Adwords API Hierarchy

After many hours of searching, reading and testing I was successful to integrate AdWords API PHP Client Library into Codeigniter 2.X.

Step by step guide on how to integrate Google Adwords API into Codeigniter.
Google Adwords API into Codeigniter
# Steps Description
1. Download AdWords API PHP Client Library This client library makes it easier to write PHP applications that programmatically access the AdWords API or DoubleClick Ad Exchange Buyer API. I have downloaded version 4.5.1(adwords_api_php_4.5.1)
2. Extract the compressed archive (.zip or .tar.gz) and paste the src folder inside codeigniter's third_party folder. Grab only src folder from the compressed files. Create a folder called Adwords inside CodeIgniter’s application/third_party/ and paste src folder inside CodeIgniter’s application/third_party/Adwords/ folder. Your application/third_party/ folder will look like application/third_party/Adwords/src/...
3. Create a php file inside Codeigniter's library folder. Create new PHP file inside Codeigniter’s application/libraries/ name it My_adwords.php
4. Set the correct path to access Adwords API. Check the source code below on how to set the correct path on application/libraries/My_adwords.php. I have added GetCampaigns function (copied from Example folder of google adwords php client library) to check later if it returns any values.
5. Now you can use My_Adwords library in your CodeIgniter’s controller code. Now you can easily access the My_Adwords library from the Codeigniter's controller like any other library methods. I have created a controller called adwords.php inside application/controller/ and call the function to fetch all the active campaigns. You can get the source of controller adwords.php
6. Test the controller and enjoy. Type the 'localhost/your_project_folder/adwords/' in your browser and you can see the result. You can see my result in the end.

Set the correct path on application/libraries/My_adwords.php
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
define('SRC_PATH', APPPATH.'/third_party/Adwords/src/');
define('LIB_PATH', 'Google/Api/Ads/AdWords/Lib');
define('UTIL_PATH', 'Google/Api/Ads/Common/Util');
define('AW_UTIL_PATH', 'Google/Api/Ads/AdWords/Util');

define('ADWORDS_VERSION', 'v201306');

// Configure include path
ini_set('include_path', implode(array(
    ini_get('include_path'), PATH_SEPARATOR, SRC_PATH))

// Include the AdWordsUser file
require_once SRC_PATH.LIB_PATH. '/AdWordsUser.php';

class My_adwords extends AdWordsUser { 
    public function __construct() { 
 function GetCampaigns() {
   // Get the service, which loads the required classes.
   $campaignService = $this->GetService('CampaignService', ADWORDS_VERSION);
   // Create selector.
   $selector = new Selector();
   $selector->fields = array('Id', 'Name');
   $selector->ordering[] = new OrderBy('Name', 'ASCENDING');
   // Create paging controls.
   $selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
   do {
     // Make the get request.
     $page = $campaignService->get($selector);
     // Display results.
     if (isset($page->entries)) {
       foreach ($page->entries as $campaign) {
         printf("Campaign with name '%s' and ID '%s' was found.\n",
             $campaign->name, $campaign->id);
     } else {
       print "No campaigns were found.\n";
     // Advance the paging index.
     $selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
   } while ($page->totalNumEntries > $selector->paging->startIndex);
source code: application/controllers/adwords.php
error_reporting(E_STRICT | E_ALL);
ini_set('display_errors', '1');

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Adwords extends CI_Controller{

function __construct()
  //load our new Adwords library


 function index()
   $user = new My_adwords();

Campaign with name 'Campaign test #1' and ID '150648975' was found. Campaign with name 'Interplanetary Cruise #52299d09d8493' and ID '150652815' was found. Campaign with name 'Interplanetary Cruise #52299d09d8517' and ID '150652935' was found.
Hope you will like my solution. If it helped you to save your time, feedback will be deeply appreciated. :)


  1. Hi. Where I put the Adwords access parameters?

  2. Hi Marc,

    You should put the Adwords access parameters in auth.ini file.

    The path to the auth.ini file is " third_party/Adwords/src/Google/Api/Ads/AdWords/auth.ini"


  3. Hello Anup,

    I follow your instruction, but now get presented with an error:

    Error parsing /application/libraries/third_party/Adwords/src/Google/Api/Ads/AdWords/Lib/ on line 15

    Do you have any ideas what might be causing this?

    1. Hello Sander,

      I saw that your file structure is wrong. You have put third_party inside libraries folder (/application/libraries/third_party/).

      - third_party folder should be inside application/third_party not inside libraries folder.

      - libraries folder should be inside application/libraries.

      Let me know if it helped.

      Anup Shakya

  4. Hello Anup,

    I corrected the code and include path to reflect define('SRC_PATH', APPPATH.'/third_party/Adwords/src/'); but I still get an unsual error:

    A PHP Error was encountered

    Severity: Warning

    Message: Error parsing /application/third_party/Adwords/src/Google/Api/Ads/AdWords/Lib/ on line 15

    Filename: Util/ApiPropertiesUtils.php

    Line Number: 34

    Do you have anymore suggestions perhaps? I am really stuck on this..

  5. Hello Anup,

    It looks like there is a problem with parsing the ini file as it is called in ApiPropertiesUtils.php. The path is fine because the file can be foud, only an error with parsing this file as an ini file i think:

    public static function ParseApiPropertiesFile($propsFilePath) {
    return parse_ini_file($propsFilePath);

    This is not CI related I think ?

    1. Hello Sander,

      Somebody have reported exact same error at . So you are not the one who had that problem.

      In my case, i didn't get any error using above code. It is perfectly working so far.

      Which version of the library are you using?

  6. Hi!

    First of all, thanks for this post!

    getCampaignExample doesn't exist so I changed it to getCampaign(); and I have this error:
    HP Fatal error: Uncaught exception 'OAuth2Exception' with message '{
    "error" : "invalid_grant"
    }' in /Applications/MAMP/htdocs/Project/application/third_party/Adwords/src/Google/Api/Ads/Common/Util/SimpleOAuth2Handler.php:115

    I think it is because I don't set refresh token in auth.ini (I have an approved developer token and I create a Client ID for web applications using localhost). But in this version, I think that getRefreshToken.php doesn't exist so, how can i solve this error?

    Thanks a lot!!

    1. extract the adwords_api_php_4.5.1 zip folder and look into examples folder. You can find 'Auth' folder inside 'examples/Adwords/Auth'. Inside Auth folder, there are two files GetRefreshToken.php and init.php. From this location you can generate refresh token. I generated it from command prompt.
      Hope you will fix it. :)

    2. I have the same problem as titolancreo, and I'm being crazy trying to use GetRefreshToken.php in codeigniter.

      How can i use it?


    3. To be able to generate refresh token, all the setting must be correct in auth.ini. Once it is correct, you can run the php file GetRefreshToken.php from command prompt, and you will get code without problem.

      I tried four-five times, before i was succeeded.

  7. I have all correct in auth.ini, and I don't know how to do it from command prompt, but if I go t GetRefreshToken in my browser, I noticed that my problem is at first "if"...
    _FILE_ is empty and realpath($_SERVER['PHP_SELF']) contains /Applications/MAMP/htdocs/adwords/examples/AdWords/Auth/GetRefreshToken.php

    So it always goes to return and it never starts try-catch

    if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
    try {

    // Get the client ID and secret from the auth.ini file. If you do not have a
    // client ID or secret, please create one of type "installed application" in
    // the Google API console:
    // and set it in the auth.ini file.

    $user = new AdWordsUser();


    1. GetRefreshToken.php needs to be run through the command line.
      Go to terminal.
      type following command in the terminal. It should return code

      php /Applications/MAMP/htdocs/adwords/examples/AdWords/Auth/GetRefreshToken.php

      Best of luck

    2. Thanks a lot! But I have my final question (sorry, I feel embarrased about this..) .
      I see this error: redirect_uri_mismatch, so I changed $redirectUri = NULL; to $redirectUri = "http://localhost/oauth2callback";

      What should I put in http://localhost/oauth2callback in order to get that authorization code??

      Thanks a lot again!

  8. I finally get my refresh token, the problem was that I used POST["code"] insted of GET["code"]

    But now, I have this problem when it goes to getCampaigns, do anyone knows how to solved it??

    PHP Fatal error: Uncaught SoapFault exception: [soap:Server] [AuthenticationError.NOT_ADS_USER @ ; trigger:''] in /Applications/MAMP/htdocs/AdwordsProject/application/third_party/Adwords/src/Google/Api/Ads/Common/Lib/AdsSoapClient.php:216
    Stack trace:
    #0 /Applications/MAMP/htdocs/AdwordsProject/application/third_party/Adwords/src/Google/Api/Ads/Common/Lib/AdsSoapClient.php(216): SoapClient->__soapCall('get', Array, NULL, Array, Array)
    #1 /Applications/MAMP/htdocs/AdwordsProject/application/third_party/Adwords/src/Google/Api/Ads/AdWords/v201306/CampaignService.php(6454): AdsSoapClient->__soapCall('get', Array)
    #2 /Applications/MAMP/htdocs/AdwordsProject/application/libraries/AdwordsApi.php(42): CampaignService->get(Object(Selector))
    #3 /Applications/MAMP/htdocs/AdwordsProject/application/controllers/adwords.php(35): adwordsApi->GetCampaigns()
    #4 /Applications/MAMP/htdocs/AdwordsProject/application/controllers/adwords.php(18): Adwords->results()
    #5 [internal function]: Adwords->index()
    #6 /Applications/MAMP/htdocs/AdwordsProject/system/core/CodeIgniter.php in /Applications/MAMP/htdocs/AdwordsProject/application/third_party/Adwords/src/Google/Api/Ads/Common/Lib/AdsSoapClient.php on line 216

    1. Hi Anup!

      Thanks for this tuto, it is helping my a lot!

      I have the same problem as Carlos Javier, but I think it is because I don't know how to put Adwords access parameters. I read that we have to write them at auth.ini, but how?

      I also need to change this parameters, because I have several Adwords accounts, do you know how can I change it? Maybe exist something like $user->adwordsUserID("123456789"); or something like this, but I didn't find it.

    2. This is a exact copy of my

      Open your auth.ini and copy the following code and paste it. Replace with your credentials.

      ; Detailed descriptions of these properties can be found at:

      developerToken = "your token key"
      userAgent = "Localhost adwords integration"
      ; Uncomment to make requests against a client customer account.
      clientCustomerId = "your_customer_id"


      ; If you do not have a client ID or secret, please create one of type
      ; "installed application" in the Google API console:
      client_id = ""
      client_secret = "your_secret_key"

      ; If you already have a refresh token, enter it below. Otherwise run
      ; GetRefreshToken.php.
      refresh_token = "your_refresh_token"

      ; (DEPRECATED) Uncomment the following to use ClientLogin.
      ; For more information, see:

      ; password = "INSERT_PASSWORD_HERE"
      ; Uncomment the following to use an existing ClientLogin AuthToken (optional).
      ; authToken = "INSERT_AUTH_TOKEN_HERE"

    3. You can set up adwords account as follow

      //set Adwords Client Id

      I haven't tested yet. I found this solution @

  9. Hi Anup!

    I read that website before this one, and it didn't work for me, but I finally got it!

    My problem was that in adwords, at top right, we have a Customer ID, but that is NOT the one that you have to write in auth.ini. If we look at the table, every client has, at bottom, another Customer ID (XXX-XXX-XXXX), and that is te number (without -) that we need to put in our auth.ini.

    If we need to change that number, in older versions, we used SetClientId (or i think so...), but, in v201306, we can set Client id with:

    I hope this will help someone else.

    1. You are right. The customer ID in the top right is customer ID not a clientCustomerID. Like you said, you have to create account at bottom, and use that customerID in as clientCustomerID in

      In case of the developer token, you must use it from real account(MCC) not from test account (MCC).

      Thanks to Arranz for giving valuable tips on how to set ClientID.


  10. hi, thanks for post.
    i have a path problem can u help me pls

    Severity: Warning

    Message: require_once(D:\LocalServer\www\adwords\application\third_party\adwords\src\Google\Api\Ads\AdWords\Lib/../v201306/CampaignService.php): failed to open stream: No such file or directory

    Filename: Lib/AdWordsSoapClientFactory.php

    Line Number: 70

    1. I can clearly see that your path is wrong.

      Set the correct path on application/libraries/My_adwords.php and check your

  11. Hi,
    Thanks for this article.

    I have a question !
    How can I get all value from google adwords like this demo app ( ) using codeigniter ?
    Can you help please !

    Thanks in advance

  12. Hi Anup!

    I have this issue..

    Type: OAuth2Exception

    Message: { "error" : "invalid_grant" }

    I already put all the credentials but still invalid grant can you help me? :(

  13. Hi, probably our entry may be off topic but anyways, I have been surfing around your blog and it looks very professional. It’s obvious you know your topic and you appear fervent about it. I’m developing a fresh blog plus I’m struggling to make it look good, as well as offer the best quality content. I have learned much at your web site and also I anticipate alot more articles and will be coming back soon. Thanks you.

    Google App Integration Madurai

  14. Hi,

    i have this error when trying to access to your example :

    Severity: Warning

    Message: require_once(Google/Api/Ads/Common/Util/AdsUtilityRegistry.php): failed to open stream: No such file or directory

    Filename: Lib/AdsUser.php

    Line Number: 28


    File: C:\wamp\www\handle-budget\application\third_party\Google\Api\Ads\Common\Lib\AdsUser.php
    Line: 28
    Function: _error_handler

    File: C:\wamp\www\handle-budget\application\third_party\Google\Api\Ads\Common\Lib\AdsUser.php
    Line: 28
    Function: require_once

    File: C:\wamp\www\handle-budget\application\third_party\Google\Api\Ads\AdWords\Lib\AdWordsUser.php
    Line: 30
    Function: require_once

    File: C:\wamp\www\handle-budget\application\libraries\MY_adwords.php
    Line: 21
    Function: require_once

    File: C:\wamp\www\handle-budget\application\controllers\adwords.php
    Line: 17
    Function: __construct

    File: C:\wamp\www\handle-budget\index.php
    Line: 315
    Function: require_once

    my structure :


    thanks :)

  15. Hi Anup, Is it working for present version ( 2017) .

    1. I haven't tried with latest version. It might or it might not work.

    2. plz update for google ads 2017 api.

  16. Hello,

    Before 6 months,Initially I have installed adword API v201609 in my project, which is in codeignier by following this example and its working fine. Now, as this adword API v201609 is depreciated, so i have updated/configured new adword v201708 Client library in my proejct. I can run examples in terminal.

    Please help me in integrating this new library with codeigniter.

    Waiting for you reply.

    Thanks in advance.

    1. Hi Vishal, I am facing same issue. If you've some solution please guide me.
      Thank You.

  17. Hi Vishal, I've done following code:

    define('SRC_PATH', APPPATH.'/third_party/Googleads/googleads-php-lib/src/');
    define('COMMON_PATH', 'Google/AdsApi/Common/');
    define('ADWORDS_PATH', 'Google/AdsApi/AdWords/');
    define('ADWORDS_VERSION', 'v201710');

    // Configure include path
    ini_set('include_path', implode(array(
    ini_get('include_path'), PATH_SEPARATOR, SRC_PATH))

    // Include the AdWordsUser file

    require_once SRC_PATH.ADWORDS_PATH. '/AdWordsSession.php';
    require_once SRC_PATH.ADWORDS_PATH. '/AdWordsSessionBuilder.php';
    require_once SRC_PATH.ADWORDS_PATH. '/Reporting\v201710\ReportDownloader.php';
    require_once SRC_PATH.ADWORDS_PATH. '/Reporting\v201710\DownloadFormat.php';
    require_once SRC_PATH.ADWORDS_PATH. '/ReportSettingsBuilder.php';
    require_once SRC_PATH.COMMON_PATH. '/OAuth2TokenBuilder.php';

    class My_adwords {
    public function __construct() {

    function GetCampaignsCost() {
    // Get the service, which loads the required classes.
    $oAuth2Credential = (new OAuth2TokenBuilder())


    But getting following errors:
    Fatal error: Interface 'Google\AdsApi\Common\AdsSession' not found in /var/www/html/crm2017/application/third_party/Googleads/googleads-php-lib/src/Google/AdsApi/AdWords/AdWordsSession.php on line 26

    Please help.