문제

Successfully using this SO solution since about a year, my code to get the daily costs of my Google AdWords campaign looks like:

sum += campaign.campaignStats.cost.microAmount / 1000000m;

I.e. I'm using the campaignStats property.

Unfortunately in the latest version v201309 of the API, this property does not exist anymore.

I've searched all the examples of the official .NET wrapper and also looked through the API documentation just to not find a single clue on how to manage this.

Therefore my question is:

How to retrieve the daily costs of an AdWord campain through the latest Google AdWords API?

Update 1:

I've found this discussion in the AdWords API forum. They suggest to generate a report, fetch and parse this report. There is also an AdWords blog entry about it.

도움이 되었습니까?

해결책 2

This is the working solution I came up with:

private static decimal coreGetAdwordsSumInRange(DateTime start, DateTime end)
{
    var reportDefinition =
        new ReportDefinition
        {
            reportName = string.Format(@"Campaign performance report #{0}", DateTime.Now.Ticks),
            dateRangeType = ReportDefinitionDateRangeType.CUSTOM_DATE,
            reportType = ReportDefinitionReportType.CAMPAIGN_PERFORMANCE_REPORT,
            downloadFormat = DownloadFormat.XML,
            includeZeroImpressions = false,
            selector = new Selector
            {
                fields = new[] { @"Cost" },
                dateRange = new DateRange {min = start.ToString(@"yyyyMMdd"), max = end.ToString(@"yyyyMMdd")}
            }
        };

    // --

    var sum = decimal.Zero;

    var tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + @".xml");
    try
    {
        var utils = new ReportUtilities(new AdWordsUser()) { ReportVersion = @"v201309" };
        utils.DownloadClientReport(reportDefinition, true, tempFilePath);

        var doc = new XmlDocument();
        doc.Load(tempFilePath);

        var costNodes = doc.SelectNodes(@"/report/table/row/@cost");
        if (costNodes != null)
        {
            foreach (XmlNode costNode in costNodes)
            {
                var cost = Convert.ToDecimal(costNode.InnerText);
                sum += cost/1000000m;
            }
        }
    }
    finally
    {
        File.Delete(tempFilePath);
    }

    return sum;
}

Also available via Pastebin.com.

다른 팁

Here's a PHP version:

$filePath = tempnam('/tmp','adwordsreport');

    $user = new AdWordsUser(NULL, NULL,   NULL,      $developerToken,  $applicationToken, $userAgent, $ClientID, NULL, NULL,       $oauth2Info);

    $user->SetClientId($ClientID);

    // Log SOAP XML request and response.
    $user->LogDefaults();

    $user->LoadService('ReportDefinitionService', 'v201402');

    // Create selector.
    $selector = new Selector();
    $selector->fields = array('CampaignId', 'AdGroupId', 'Id', 'Criteria',
        'CriteriaType', 'Impressions', 'Clicks', 'Cost');

    // Filter out deleted criteria.
    $selector->predicates[] = new Predicate('Status', 'NOT_IN', array('DELETED'));

    // Create report definition.
    $reportDefinition = new ReportDefinition();
    $reportDefinition->selector = $selector;
    $reportDefinition->reportName = 'Criteria performance report #' . uniqid();
    $reportDefinition->dateRangeType = 'ALL_TIME';
    $reportDefinition->reportType = 'CRITERIA_PERFORMANCE_REPORT';
    $reportDefinition->downloadFormat = 'XML';

    // Exclude criteria that haven't recieved any impressions over the date range.
    $reportDefinition->includeZeroImpressions = FALSE;

    // Set additional options.
    $options = array('version' => 'v201402', 'returnMoneyInMicros' => TRUE);

    // Download report.
    ReportUtils::DownloadReport($reportDefinition, $filePath, $user, $options);


    printf("Report with name '%s' was downloaded to '%s'.\n",
        $reportDefinition->reportName, $filePath);


    $doc = new DOMDocument();
    $doc->loadXML(file_get_contents($filePath));
    $xp = new DOMXPath($doc);
    $q = $xp->query("/report/table/row/@cost");
    $cost = 0;
    foreach($q as $el) {
      $v = $el->textContent;
      $cost += $v / 1000000;
    }

    echo $cost;

Code with PHP for latest API v201506 and v201509 to get sum of the cost on date range.

function getAdwordSumOfCost(AdWordsUser $user, $filePath, $startDate=null, $endDate=null, $campaignId = null) {
    $basePath = __DIR__."/../../";//path to google ads api
    // Load the service, so that the required classes are available.
    $user->LoadService('ReportDefinitionService', 'v201509');
    include_once($basePath.'vendor/googleads/googleads-php-lib/src/Google/Api/Ads/AdWords/v201509/CampaignService.php');
    $selector = new Selector();
    $selector->fields = array('CampaignId', 'AdGroupId', 'Id', 'Criteria',
        'CriteriaType', 'Impressions', 'Clicks', 'Cost');

    if($campaignId)
        $selector->predicates[] = new Predicate('CampaignId', 'IN', array($campaignId));

    if($startDate && $endDate) {
        $selector->dateRange = new DateRange($startDate, $endDate);
    }

    // Create report definition.
    include_once($basePath.'vendor/googleads/googleads-php-lib/src/Google/Api/Ads/AdWords/Util/v201509/ReportClasses.php');
    $reportDefinition = new ReportDefinition();
    $reportDefinition->selector = $selector;
    $reportDefinition->reportName = 'Criteria performance report #' . uniqid();
    $reportDefinition->dateRangeType = 'CUSTOM_DATE';
    $reportDefinition->reportType = 'CRITERIA_PERFORMANCE_REPORT';
    $reportDefinition->downloadFormat = 'XML';

    // Exclude criteria that haven't recieved any impressions over the date range.
    $reportDefinition->includeZeroImpressions = false;

    // Set additional options.
    $options = array('version' => 'v201509');

    // Download report.
    include_once($basePath.'vendor/googleads/googleads-php-lib/src/Google/Api/Ads/AdWords/Util/v201509/ReportUtils.php');
    ReportUtils::DownloadReport($reportDefinition, $filePath, $user, $options);

    $doc = new DOMDocument();
    $doc->loadXML(file_get_contents($filePath));
    $xp = new DOMXPath($doc);
    $q = $xp->query("/report/table/row/@cost");
    $cost = 0.00;
    foreach($q as $el) {
        $v = $el->textContent;
        $cost += $v / 1000000;
    }

    return $cost;
}

Usage:

$adwordsUser = new AdWordsUser();

//pass Adwords clientID, you can also pas campaign id as well if you want to get calculation only for a single campaign
$adwords = new Adwords('111-111-111');

//Will give you cost for yesterday
$cost = $adwords->getAdwordSumOfCost($adwordsUser, '/path/to/storage/result.xml', date('Ymd', strtotime('-1 day')), date('Ymd', strtotime('-1 day')));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top