I've been using Adwords API to show campaign data for a few months now, and
there hadn't really been too much of an issue. Suddenly, and without any
code changes, the result is an empty string. I'm not seeing anyone suddenly
coming up with the same result, so I'm a bit confused.
$reportQuery = $this->getQuery();
// Download report as a string.
$reportDownloader = new ReportDownloader($session);
$reportDownloadResult = $reportDownloader->downloadReportWithAwql(
$reportQuery,
DownloadFormat::XML
);
$result = $reportDownloadResult->getAsString();
Here is $result
string(0) ""
Here's my log for the request.
[2017-09-26 20:07:52] AW_REPORT_DOWNLOADER.INFO: ADMINRG-0VC3H2Q
GuzzleHttp/6.2.1 curl/7.50.1 PHP/7.0.11 - [26/Sep/2017:20:07:52 +0000]
"POST /api/adwords/reportdownload/v201702 HTTP/1.1" 200 0
[2017-09-26 20:07:52] AW_REPORT_DOWNLOADER.DEBUG: >>>>>>>>
POST /api/adwords/reportdownload/v201702 HTTP/1.1
Authorization: REDACTED
User-Agent: GuzzleHttp/6.2.1 curl/7.50.1 PHP/7.0.11
Content-Type: application/x-www-form-urlencoded
Host: adwords.google.com
developerToken: gYud6DzW_HhKqGlbt7HPKg
clientCustomerId: 915-314-1684
skipReportHeader: true
skipColumnHeader: true
skipReportSummary: true
useRawEnumValues: false
includeZeroImpressions: true
__rdquery=SELECT AdGroupId, AdGroupName, AdGroupDesktopBidModifier,
AdGroupMobileBidModifier, AdGroupStatus, AdGroupTabletBidModifier,
AdGroupType, BaseAdGroupId, CampaignId, CampaignName, CampaignStatus,
EnhancedCpcEnabled, EnhancedCpvEnabled, TargetCpa, TargetCpaBidSource,
BaseCampaignId, BiddingStrategyName, BiddingStrategyType, BidType,
ConversionRate, Conversions, CostPerConversion, Ctr, EngagementRate,
Engagements, Impressions, InteractionRate, Interactions,
PercentNewVisitors, ViewThroughConversions FROM ADGROUP_PERFORMANCE_REPORT
WHERE Impressions > 0 DURING TODAY&__fmt=XML
<<<<<<<<
HTTP/1.1 200 OK
Content-Type: application/xml; charset=UTF-8
Content-Length: 0
Content-Disposition:
/bigstore/aw3-webapi-report-download/216827009cfe5f971-2fb3-41f3-8685-7ed3017dd84f/fileId-null-uuid-cfe5f971-2fb3-41f3-8685-7ed3017dd84f-cid-216827009.tmp.xml
Date: Tue, 26 Sep 2017 20:07:50 GMT
Expires: Tue, 26 Sep 2017 20:07:50 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alt-Svc: quic=":443"; ma=2592000; v="39,38,37,35"
Connection: close
--------
NULL
Here's the code I'm using:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Reporting\v201702\ReportDownloader;
use Google\AdsApi\AdWords\Reporting\v201702\DownloadFormat;
use Google\AdsApi\AdWords\ReportSettingsBuilder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\Common\Configuration;
use App\Adwords\Account;
use App\Adwords\AccountKey;
class AdwordsCommand extends Command
{
protected $args;
public function __construct()
{
parent::__construct();
}
public function setTerms($terms)
{
static::$TERMS = $terms;
return $this;
}
protected static $TERMS = ['AdvertisingChannelSubType',
'AdvertisingChannelType', 'BaseCampaignId',
'BiddingStrategyName', 'BiddingStrategyType', 'BidType',
'BudgetId', 'CampaignId', 'CampaignName',
'CampaignTrialType', 'StartDate', 'ServingStatus',
'ConversionRate',
'Conversions',
'CostPerConversion',
'Ctr',
'EngagementRate',
'Engagements',
'Impressions',
'InteractionRate',
'Interactions',
'InvalidClicks',
'InvalidClickRate',
'PercentNewVisitors',
'ViewThroughConversions','CampaignStatus'
];
public static $FROM = "CAMPAIGN_PERFORMANCE_REPORT";
public function handle($args = [], $callback = null)
{
$this->args = $args;
$accounts = Account::where('canManageClients', 0)->where('active',
1)->get();
$returnArr = [];
foreach ($accounts as &$account) {
$key = AccountKey
::where('id', $account->parent_id)
->first();
// Set the config variables.
$config = [];
$config['ADWORDS'] = [];
$config['ADWORDS_REPORTING'] = [];
$config['OAUTH2'] = [];
$config['ADWORDS']['developerToken'] = $key->developerToken;
$config['ADWORDS']['clientCustomerId'] = $account->referenceId;
$config['OAUTH2']['clientId'] = $key->clientId;
$config['OAUTH2']['clientSecret'] = $key->clientSecret;
$config['OAUTH2']['refreshToken'] = $key->refreshToken;
$config['LOGGING']['soapLogFilePath'] = "/soap/soap.log";
$config['LOGGING']['soapLogLevel'] = "LOGGING";
$config['LOGGING']['reportDownloaderLogFilePath'] =
"/soap/report-downloader.log";
$config['LOGGING']['reportDownloaderLogLevel'] = "LOGGING";
if (isset($argc)) {
printf("Doing API request on account %s.\n",
$key->account_reference);
}
$cfg = new Configuration($config);
$oAuth2Credential = (new OAuth2TokenBuilder())
->from($cfg)
->build();
$reportSettings = (new ReportSettingsBuilder())
->from($cfg)
->skipReportSummary(true)
->skipReportHeader(true)
->includeZeroImpressions(true)
->skipColumnHeader(true)
->build();
$session = (new AdWordsSessionBuilder())
->from($cfg)
->withOAuth2Credential($oAuth2Credential)
->withReportSettings($reportSettings)
->build();
$returnArr[] = $this->startQuery($account, $key, $session,
$callback);
}
return $returnArr;
}
/**
* Starts a query, and starts using data from the inheriting command.
*/
public function startQuery($account, $key, $session, $callback)
{
$reportQuery = $this->getQuery();
// Download report as a string.
$reportDownloader = new ReportDownloader($session);
$reportDownloadResult = $reportDownloader->downloadReportWithAwql(
$reportQuery,
DownloadFormat::XML
);
$result = $reportDownloadResult->getAsString();
// header("content-type:text/plain");
// var_dump($result);exit;
$result = $this->xmlToObj($result);
if (!is_null($callback)) {
return $callback($result, $account);
}
return $this->handleReport($result, $account);
}
/**
* Processes the CSV from Google into a clean object.
*/
protected static function xmlToObj($result)
{
if(empty($result)) {
echo "{'status':0,'error':'result is an empty string'}";exit;
}
$stack = [];
$xml = simplexml_load_string($result);
$returnData = [];
foreach ($xml->table->children() as $child) {
$item = new \stdclass;
$attributes = $child->attributes();
foreach ($attributes as $key => $value) {
// Make the names the same as adwords API.
$key = ucfirst($key);
$item->{$key} = (string) $value;
}
$returnData[] = $item;
}
foreach ($returnData as &$item) {
// The number of nulls per row in the file.
$nullCount = 0;
if (isset($item->Cost)) {
$item->Cost = $item->Cost / 1000000;
}
if (isset($item->CostConv)) {
$item->CostConv = $item->CostConv / 1000000;
}
foreach ($item as $key => &$value) {
// Check for nulls, and set it as null if it exists.
// Also, increase the null count.
if (trim($value, " -") == "") {
$nullCount++;
// $value = null;
$value = 0;
}
// If the number is a float, well... Let's make it a float.
if (is_float($value) || is_numeric($value)) {
$value = (float) $value;
continue;
}
if (empty($value) && $value !== 0) {
$value = null;
}
}
$stack[] = $item;
}
return $stack;
}
protected static $DURING = "TODAY";
public static function setDuring($during)
{
$allowedValues =
array('TODAY','YESTERDAY','LAST_7_DAYS','THIS_WEEK_SUN_TODAY','THIS_WEEK_MON_TODAY','LAST_WEEK','LAST_14_DAYS','LAST_30_DAYS','LAST_BUSINESS_WEEK','LAST_WEEK_SUN_SAT','THIS_MONTH',"ALL_TIME");
if (in_array($during, $allowedValues)) {
static::$DURING = $during;
return true;
}
return true;
}
protected static function getQuery()
{
$terms = implode(', ', static::$TERMS);
$during = static::$DURING;
$from = static::$FROM;
if (static::$DURING=="ALL_TIME") {
return "SELECT $terms FROM $from WHERE Impressions > 0";
} else {
return "SELECT $terms FROM $from WHERE Impressions > 0 DURING
$during";
}
}
protected function handleReport($obj, $account)
{
throw new \Exception("Tell Steven you've seen this. lol.");
var_dump($obj);
}
}
--
--
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
Also find us on our blog and Google+:
https://googleadsdeveloper.blogspot.com/
https://plus.google.com/+GoogleAdsDevelopers/posts
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
You received this message because you are subscribed to the Google
Groups "AdWords API Forum" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/adwords-api?hl=en
---
You received this message because you are subscribed to the Google Groups
"AdWords API Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
Visit this group at https://groups.google.com/group/adwords-api.
To view this discussion on the web visit
https://groups.google.com/d/msgid/adwords-api/ec461c48-662e-49d3-8abe-a586a83804e4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.