Search code examples
.netgoogle-apigoogle-ads-api

How to retrieve daily costs through Google AdWords API v201309?


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 campaign 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.


Solution

  • 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.