如何通过 Google AdWords API v201309 检索每日费用?

Posted

技术标签:

【中文标题】如何通过 Google AdWords API v201309 检索每日费用?【英文标题】:How to retrieve daily costs through Google AdWords API v201309? 【发布时间】:2013-11-21 06:47:45 【问题描述】:

自大约一年以来成功使用this SO solution,我获取 Google AdWords 广告系列每日费用的代码如下所示:

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

即我正在使用campaignStats property。

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

我搜索了the official .NET wrapper 的所有示例,还查看了 API 文档,但没有找到关于如何管理它的任何线索。

因此我的问题是:

如何通过最新的 Google AdWords API 检索 AdWord 活动的每日费用?

更新 1:

我找到了this discussion in the AdWords API forum。他们建议生成一份报告,获取并解析这份报告。还有an AdWords blog entry关于它。

【问题讨论】:

【参考方案1】:

这是一个 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;

【讨论】:

【参考方案2】:

这是我想出的可行解决方案:

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.

【讨论】:

【参考方案3】:

使用PHP 编码最新API v201506v201509 以获得日期范围内的成本总和。

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

【讨论】:

以上是关于如何通过 Google AdWords API v201309 检索每日费用?的主要内容,如果未能解决你的问题,请参考以下文章

Google Adwords API 响应解析

如何通过 python adwords API 与 gclids 一起获得 adwords 转换?

通过 Google Adwords API 获取可用于特定 Adwords 报告的字段列表

如何获取 Google Adwords api 的 developerToken?

在 PHP 中使用 Google Adwords API

Google Adwords 是不是通过该服务提供访问权限