Getting CustomerId with PHP

408 views
Skip to first unread message

Mihai Iliescu

unread,
May 30, 2017, 7:05:09 AM5/30/17
to AdWords API Forum
I'm trying to get the Customer ID but I get this error:

PHP Fatal error:  Uncaught exception 'Google\\AdsApi\\AdWords\\v201702\\cm\\ApiException' with message '[AuthenticationError.CLIENT_CUSTOMER_ID_IS_REQUIRED @ ; trigger:'<null>']' in /var/www/html/adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/Common/Util/Reflection.php:39\nStack trace:\n#0 /var/www/html/adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/Common/Util/Reflection.php(39): ReflectionClass->newInstanceArgs(Array)\n#1 /var/www/html/adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/Common/AdsSoapClient.php(162): Google\\AdsApi\\Common\\Util\\Reflection->createInstance('Google\\\\AdsApi\\\\A...', '[Authentication...')\n#2 /var/www/html/adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/Common/AdsSoapClient.php(126): Google\\AdsApi\\Common\\AdsSoapClient->parseApiExceptionFromSoapFault(Object(SoapFault))\n#3 /var/www/html/adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/AdWords/v201702/mcm/ManagedCustomerService.php(103): Google\\AdsApi\\Common\\AdsSoapClient->__soapCall('get', Array)\n#4 in /var/www/html/adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/Common/Util/Reflection.php on line 39



The code I use is the one bellow. Any help would be appreciated.

namespace Google\AdsApi\Examples\AdWords\v201702\AccountManagement;
require_once __DIR__.'/vendor/autoload.php';
use Google\Auth\OAuth2;

session_start();

$oauth2 = new OAuth2([
    'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
    'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
    'redirectUri' => 'xxx',
    'clientId' => 'xxx',
    'clientSecret' => 'xxx',
]);

if (!isset($_GET['code'])) {
  // 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;


// Check given state against previously stored one to mitigate CSRF attack.
}elseif (empty($_GET['state'])
    || ($_GET['state'] !== $_SESSION['oauth2state'])) {
  unset($_SESSION['oauth2state']);
  exit('Invalid state.');
}

else {
  $oauth2->setCode($_GET['code']);
  $authToken = $oauth2->fetchAuthToken();



  //  echo 'successfully connected';
}

 ?><form  method="post" action="report.php"><select name="account"><?php
use Google\AdsApi\AdWords\v201702\mcm\ManagedCustomerService;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\Common\OAuth2TokenBuilder;


use Google\AdsApi\AdWords\v201702\cm\CampaignService;
use Google\AdsApi\AdWords\v201702\cm\OrderBy;
use Google\AdsApi\AdWords\v201702\cm\Paging;
use Google\AdsApi\AdWords\v201702\cm\Selector;
use Google\AdsApi\AdWords\v201702\cm\SortOrder;
use Google\AdsApi\AdWords\v201702\cm\Predicate;  
use Google\AdsApi\AdWords\v201702\cm\PredicateOperator; 
$session = (new AdWordsSessionBuilder())
    ->fromFile()
    ->withOAuth2Credential($oauth2)
    ->build();

$adWordsServices = new AdWordsServices();

$managedCustomerService = $adWordsServices->get($session, ManagedCustomerService::class);
$selector = new Selector();
    $selector->setFields(['CustomerId', 'Name']);
 $selector->setPredicates([new Predicate('CanManageClients', PredicateOperator::EQUALS, ['false'])]);  // exclude MCC top accounts
$page = $managedCustomerService->get($selector);
  foreach ($page->getEntries() as $account) {
          echo ('<option value="' . $account->getCustomerId().' ">'.$account->getCustomerId() . ' - ' . $account->getName().'</option>'); 
          }     
  
 ?>   </select><input type='submit' name='submit'/>

Shwetha Vastrad (AdWords API Team)

unread,
May 30, 2017, 11:28:17 AM5/30/17
to AdWords API Forum
Hi,

ManagedCustomerService requires the clientCustomerId to be set in the request header. If you are looking to get the CustomerId using the OAuth2 credentials, you could consider using CustomerService.getCustomers() method which returns a list of Customers which are directly accessible by the authenticated account. If no clientCustomerId is specified in a request, the response will contain multiple entries if more than one account is directly accessible by the authenticated account. If clientCustomerId is specified in the request header, only details of that customer will be returned. Once you have the clientCustomerId of the authenticated user, you can use ManagedCustomerService to get the child accounts under that account as shown in this example.

Regards,
Shwetha, AdWords API Team.

Mihai Iliescu

unread,
May 31, 2017, 8:25:16 AM5/31/17
to AdWords API Forum
Thanks Shwetha Vastrad.

Can someone help me with the code. I tried the one bellow but it does not seem to print anything out:

[...]
use Google\AdsApi\AdWords\v201702\mcm\CustomerService;
[...]
$adWordsServices = new AdWordsServices();
$CustomerService= $adWordsServices->get($session, CustomerService::class);
$cid=$CustomerService->getCustomers();
var_dump $cid;

Page appears empty.

[2017-05-31 15:22:07] AW_SOAP.INFO: clientCustomerId= operations=1 service=CustomerService method=getCustomers responseTime=460 requestId=000550d0f7ee23c00a1bb0dc1600bca3 server=adwords.google.com isFault=0 faultMessage=


Shwetha Vastrad (AdWords API Team)

unread,
May 31, 2017, 11:29:30 AM5/31/17
to AdWords API Forum
Hi, 

Could you try the code snippet provided below? 

$customerService = $adWordsServices->get($session, CustomerService::class);
$customers
= $customerService->getCustomers();
//assuming that only one AdWords account is directly accessible by the authenticated account
$customer
= $customers[0];
var_dump
($customer);

If the response is still empty, please enable logging and provide the request and response logs along with the email address used to generate the OAuth2 credentials used. Please use Reply privately to author when responding.

Joven Albarida

unread,
Sep 21, 2017, 4:35:51 PM9/21/17
to AdWords API Forum
You can also try this out, if you want to list individual items.. https://developers.google.com/adwords/api/docs/reference/v201705/CustomerService.Customer
$customerService = $adWordsServices->get($session, CustomerService::class);
$customers = $customerService->getCustomers();
foreach($customers as $k=>$v) {
     echo $v->getCustomerId();
     echo $v->getDescriptiveName();
}

Reply all
Reply to author
Forward
0 new messages