如何通过Google AdWords API v201309检索日常成本



自从大约一年以来,我成功地使用了这个SO解决方案,我的代码获得了我的谷歌广告词活动的日常成本,看起来像:

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

即,我正在使用campaignStats属性。

遗憾的是,在API的最新版本v201309中,此属性已不存在。

我搜索了官方.NET包装器的所有示例,也查看了API文档,但没有找到任何关于如何管理它的线索。

因此我的问题是:

如何通过最新的Google AdWords API检索AdWord广告活动的日常成本?

更新1:

我在AdWords API论坛上找到了这个讨论。他们建议生成一个报告,获取并解析这个报告。还有一个关于它的AdWords博客条目。

这里有一个PHP版本:

$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;

这是我提出的工作解决方案:

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;
}

也可通过Pastebin.com获得。

使用最新API v201506v201509PHP进行编码,以获得日期范围的成本总和。

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;
}

用法:

$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')));

相关内容

  • 没有找到相关文章

最新更新