How to Consume Adwords API after I get client Access token and Refresh Token? (using the latest Adwords PHP Library v201708)

789 views
Skip to first unread message

Joven Albarida

unread,
Sep 19, 2017, 9:51:26 AM9/19/17
to AdWords API Forum
Hi Team,

I know that theres new Update in Adwords API Php Library.. I'm in-process of upgrading my old source code to latest version of the v201708

But it looks like the new library was written from ground up, and some of the functions are now similar to the old source code i have..

So im currently stuck with ...  (By the way the purpose of my program is to Access the AdWords Account of Customer on there behalf..)

Code:
<?php
error_reporting
(E_ALL); ini_set('display_errors', 1);
require("vendor/autoload.php");
use Google\Auth\OAuth2;


use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201708\cm\CampaignService;
use Google\AdsApi\AdWords\v201708\cm\OrderBy;
use Google\AdsApi\AdWords\v201708\cm\Paging;
use Google\AdsApi\AdWords\v201708\cm\Selector;
use Google\AdsApi\AdWords\v201708\cm\SortOrder;
use Google\AdsApi\Common\OAuth2TokenBuilder;


use Google\AdsApi\AdWords\v201708\mcm\CustomerService;
use Google\AdsApi\AdWords\v201708\mcm\ManagedCustomerService;


session_start
();
$oauth2
= new OAuth2([
             
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
             
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
             
'redirectUri' => 'http://dev.xxxxx.com/testing.php',
             
'clientId' => '826982.....ontent.com',
             
'clientSecret' => 'dJCcn......S1T8I',
             
'scope' => 'https://www.googleapis.com/auth/adwords'
]);


if (isset($_GET['sign_in'])) {
   
// Create a 'state' token to prevent request forgery.
   
// Store it in the session for later validation.
    $oauth2
->setState(sha1(openssl_random_pseudo_bytes(1024)));
    $_SESSION
['oauth2state'] = $oauth2->getState();


   
// Redirect the user to the authorization URL.
    $config
= [
       
// Set to 'offline' if you require offline access.
       
'access_type' => 'offline'
   
];
    header
('Location: ' . $oauth2->buildFullAuthorizationUri($config));
   
exit;
}
elseif
(isset($_GET['code']))  {
    $oauth2
->setCode($_GET['code']);
    $authToken
= $oauth2->fetchAuthToken();
 
   
TestCall::run($oauth2);


}
elseif
(isset($_GET['try_again'])) {
 
TestCall::run($oauth2);
}
elseif
(empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
  unset
($_SESSION['oauth2state']);
 
exit('Invalid state.');
}




/* Test Class */
class TestCall {
 
public static function run(OAuth2 $oauth2) {
    $session
= (new AdWordsSessionBuilder())
       
->fromFile('/var/www/html/dev.xxxxxxx.com/adsapi_php.ini')
       
->withOAuth2Credential($oauth2)
       
->withClientCustomerId('932-275-9700')
       
->build();
 
    $adWordsServices
= new AdWordsServices();


    $campaignService
= $adWordsServices->get($session, CampaignService::class);
 
   
// Create selector.
    $selector
= new Selector();
    $selector
->setFields(['Id', 'Name']);
    $selector
->setOrdering([new OrderBy('Name', SortOrder::ASCENDING)]);
    $selector
->setPaging(new Paging(0, 500));


    $totalNumEntries
= 0;
   
do {
     
// Make the get request.
      $page
= $campaignService->get($selector);


     
// Display results.
     
if ($page->getEntries() !== null) {
        $totalNumEntries
= $page->getTotalNumEntries();
       
foreach ($page->getEntries() as $campaign) {
          printf
(
             
"Campaign with ID %d and name '%s' was found.\n",
              $campaign
->getId(),
              $campaign
->getName()
         
);
       
}
     
}


     
// Advance the paging index.
      $selector
->getPaging()->setStartIndex(
          $selector
->getPaging()->getStartIndex() + 500);
   
} while ($selector->getPaging()->getStartIndex() < $totalNumEntries);


    printf
("Number of results found: %d\n", $totalNumEntries);
 
}
 
}


Feel free to try this Test Endpoints... (this URL will be deleted soon)

http://dev.negativekeywordpro.com/testing.php?sign_in      (this will prompt user for OAuth, to get Auth Code)

It will redirect correctly on to my redirect_uri (that include the Auth Code, and on background I will process that auth code to request for Access and Refresh token)

In background I will try to get the Client Account Campaigns and list its (this works fine in first load, but of course when you reload it will throw an error that Auth Code already redeemed)

So on my understanding... after you redeemed the Access and Refresh token, that access token will automatically appended on the OAuth, so I will just open this OAuth2 and the library will handle the whole process?
This the test url (after you redeemed the tokens) 
session_start();
$oauth2
= new OAuth2([
             
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
             
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
             
'redirectUri' => 'http://dev.xxxxx.com/testing.php',
             
'clientId' => '826982.....ontent.com',
             
'clientSecret' => 'dJCcn......S1T8I',
             
'scope' => 'https://www.googleapis.com/auth/adwords'
]);

But I guess there still missing or wrong on my logic? I hope somebody can enlightened me on this...

This the error after I call again the services: http://dev.negativekeywordpro.com/testing.php?try_again

Fatal error: Uncaught exception 'DomainException' with message 'Missing authorization code' in /var/www/html/dev.xxx.com/xxxxxxl/vendor/google/auth/src/OAuth2.php on line 457
( ! ) DomainException: Missing authorization code in /var/www/html/dev.xxxxx.com/xxxxx/vendor/google/auth/src/OAuth2.php on line 457

Thank you very much

Shwetha Vastrad (AdWords API Team)

unread,
Sep 19, 2017, 2:15:50 PM9/19/17
to AdWords API Forum
Hi, 

Could you confirm that you followed the steps provided in this guide to set up authentication for web-flow? Once you get the refresh token, you need not go through the authorization step again. You just need to use the refresh token to get a new access token. You need to provide the refresh token in the OAuth2 object when you create the session. 

Regards,
Shwetha, AdWords API Team.

Joven Albarida

unread,
Sep 19, 2017, 5:09:37 PM9/19/17
to AdWords API Forum
Hi Shwetha,

Yes I do follow the instructions from that guide, I think i dont have problem with the web-flow.. 

About the refresh token, I would like to try that.. but thats odd, I cant see the "refresh_token" after i dump the results of 
authToken = $oauth2->fetchAuthToken();

this the only array of results returned..

{
  access_token
: "ya29.GlzLBI_GSypykk9KGt..........klItfLMxQh4QHA_ChjWl65MqIPQs-g",
  token_type
: "Bearer",
  expires_in
: 3599
}



Thank you,

Shwetha Vastrad (AdWords API Team)

unread,
Sep 19, 2017, 5:44:53 PM9/19/17
to AdWords API Forum
Hi Joven,

For Web flow type applications, the refresh token is only returned if the access_type HTTP query parameter is set to "offline" when you direct the user to Google's OAuth 2.0 server. I see that you have set this parameter. Could you check if this parameter is being passed correctly in the authorization URL? Could you check if a value is returned for "$authToken['refresh_token'];" when you authorize for the first time? 

Thanks,
Shwetha, AdWords API Team.

Joven Albarida

unread,
Sep 19, 2017, 5:58:21 PM9/19/17
to AdWords API Forum
Hi Swetha,

Thank you for your help, I think now found the solution.. (But I guess its not yet updated on that Web Flow Guide documentation)

To share with the other guys also that may encounter the same problem..

I successfully get the refresh_token after, I included this "prompt=consent" and change access_type "online" to "offline" 

Code
 // Redirect the user to the authorization URL.
    $config
= [
       
// Set to 'offline' if you require offline access.

       
'access_type' => 'offline',
       
'prompt' => 'consent',

   
];
    header
('Location: ' . $oauth2->buildFullAuthorizationUri($config));

Its now gave me the refresh_token :) then after getting refresh_token I temporarily stored it to Session (will change logic in Production)

then appended it to my opening of OAuth2 object

  $oauth2 = new OAuth2([
               
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
               
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',

               
'redirectUri' => 'http://dev.xxxx.com/testing.php',
               
'clientId' => '82698.....ontent.com',
               
'clientSecret' => 'dJCc.....1T8I',
               
'scope' => 'https://www.googleapis.com/auth/adwords',

               
'refresh_token' => $_SESSION['refresh_token']
 
]);

Though i'm not sure if this the correct way to do it..  This works perfectly to me! 

Again thank you for your help..
Reply all
Reply to author
Forward
0 new messages