Adrien Hingert
Adrien Hingert

Reputation: 1516

AdWords API get costs

I am looking for a simple solution to extract daily costs from Google AdWords via the API. I've looked at Apility and the official AdWords API, but the first is not maintained any more while the second is an overkill - I mean 76MB of uncompressed code to only get the daily costs?

Does anybody know of a simple solution to get the costs from Google AdWords?

Upvotes: 2

Views: 6596

Answers (4)

Use

composer require googleads/googleads-php-lib

Script for Laravel 5.8

Google Ads v201809

<?php namespace App\Console\Commands\Google;

use App\Model\AdvExpense;
use App\Model\Campaign;
use App\Model\Source;
use App\Service\Xml;
use Carbon\Carbon;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Reporting\v201809\DownloadFormat;
use Google\AdsApi\AdWords\Reporting\v201809\ReportDefinition;
use Google\AdsApi\AdWords\Reporting\v201809\ReportDefinitionDateRangeType;
use Google\AdsApi\AdWords\Reporting\v201809\ReportDownloader;
use Google\AdsApi\AdWords\v201809\cm\CampaignService;
use Google\AdsApi\AdWords\v201809\cm\DateRange;
use Google\AdsApi\AdWords\v201809\cm\OrderBy;
use Google\AdsApi\AdWords\v201809\cm\Paging;
use Google\AdsApi\AdWords\v201809\cm\ReportDefinitionReportType;
use Google\AdsApi\AdWords\v201809\cm\Selector;
use Google\AdsApi\AdWords\v201809\cm\SortOrder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Illuminate\Console\Command;

class Expenses extends Command
{
    /**
     * The name and signature of the console command
     *
     * @var string
     */
    protected $signature = 'google:expenses';
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'Import Google Ads Expenses';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Import Google Ads Expenses";

    public function handle()
    {
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile(storage_path('adsapi_php.ini'))->build();
        $session = (new AdWordsSessionBuilder())->fromFile(storage_path('adsapi_php.ini'))->withOAuth2Credential($oAuth2Credential)->build();

        $date = Carbon::yesterday();

        $this->saveExpenses($session, $date);
    }

    public function saveExpenses($session, $date)
    {
// Create selector.
        $selector = new Selector();
        $selector->setFields(['CampaignId', 'CampaignName', 'Clicks', 'Cost']);
        $selector->setDateRange(new DateRange(
            $date->format('Ymd'),
            $date->format('Ymd')
        ));

// Create report definition.
        $reportDefinition = new ReportDefinition();
        $reportDefinition->setSelector($selector);
        $reportDefinition->setReportName('Expenses report ' . uniqid());
        $reportDefinition->setDateRangeType(ReportDefinitionDateRangeType::CUSTOM_DATE);
        $reportDefinition->setReportType(ReportDefinitionReportType::CAMPAIGN_PERFORMANCE_REPORT);
        $reportDefinition->setDownloadFormat(DownloadFormat::XML);

// Download report.
        $reportDownloader = new ReportDownloader($session);
        $reportDownloadResult = $reportDownloader->downloadReport($reportDefinition);
        $result = $reportDownloadResult->getAsString();

        $report = Xml::namespacedXMLToArray($result);
        foreach ($report['table']['row'] as $item) {
            $campaign_id = $item['@attributes']['campaignID'];
            $campaign_name = $item['@attributes']['campaign'];
            $cost = $item['@attributes']['cost'];

            if ($cost > 0) {
                $dbCampaign = Campaign::where('code', $campaign_id)->get()->first();

                if ($dbCampaign) {
                    $price = round($cost / 1000000);
                    if ($price) {
                        $dbCost = AdvExpense::updateOrCreate(
                            [
                                'campaign_id' => $dbCampaign->id,
                                'date' => $date,
                            ],
                            [
                                'price' => $price,
                            ]
                        );

                        if ($dbCost->exists) {
                            $this->info($dbCampaign->name . ' - ' . $date->format('Y-m-d') . ' - ' . $price . ' OK');
                        } else {
                            $this->error($dbCampaign->name . ' - ' . $date->format('Y-m-d') . ' - ' . $price . ' ERROR');
                        }
                    }
                } else {
                    $this->error('Campaign ' . $campaign_name . ' not found!');
                }
            }
        }
    }
}

Upvotes: 1

iluxa
iluxa

Reputation: 6969

I'd recommend AdWords Scripts, https://developers.google.com/adwords/scripts/. Write Javascript directly in AdWords UI, handles basic stuff pretty well.

Upvotes: 0

Ewan Heming
Ewan Heming

Reputation: 4648

You shouldn't use APILity as the API version it supports was depreciated several years ago. The project was halted in favour of the new official PHP AdWords API Library. Some functions of it still work (such as the AdWords Reporting Service) but that won't last for too long now.

I would recommend using the official library if possible because it makes development and upgrading so much simpler but if you really need a lighter footprint you can try constructing the API calls yourself using the standard PHP Soap extension.

Upvotes: 0

Saketh
Saketh

Reputation: 21

If you're referring to API costs, there's the GetUnits call, used in the AdWords API Tutorial.

If you're referring to running campaign costs, you can use a StatsSelector. You will want the cost/microAmount.

Upvotes: 2

Related Questions