[SoapFault] Unmarshalling Error: cvc-elt.4.3: Type 'ns1:AdGroupLabelOperation' is not validly derived from the type definition, 'AdGroupOperation', of element 'ns1:operations' #21
I get keeping the following message:
[SoapFault] Unmarshalling Error: cvc-elt.4.3: Type 'ns1:AdGroupLabelOperation' is not validly derived from the type definition, 'AdGroupOperation', of element 'ns1:operations'
But I can't find what I'm doing wrong with the AdGroupLabelOperations. I get the same when I want to use CampaignLabelOperation. Same message... I can get, update, remove campaigns, ad groups, ads and keywords without any problems. But add labels to campaigns, ad groups, ads en keywords aren't working.
It's not the best code, but it does the job for now.
This is my code:
`<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use League\Csv\Reader;
use Illuminate\Support\Facades\Log;
use App\Adwords\Product;
use App\Adwords\Ad;
use App\Adwords\AdKeyword;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\v201609\cm\ApiException;
use Google\AdsApi\AdWords\v201609\cm\Predicate;
use Google\AdsApi\AdWords\v201609\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201609\cm\Selector;
use Google\AdsApi\AdWords\v201609\cm\Operator;
use Google\AdsApi\AdWords\v201609\cm\Paging;
use Google\AdsApi\AdWords\v201609\cm\SortOrder;
use Google\AdsApi\AdWords\v201609\cm\OrderBy;
use Google\AdsApi\AdWords\v201609\cm\Campaign;
use Google\AdsApi\AdWords\v201609\cm\CampaignService;
use Google\AdsApi\AdWords\v201609\cm\CampaignOperation;
use Google\AdsApi\AdWords\v201609\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201609\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201609\cm\AdGroupAdStatus;
use Google\AdsApi\AdWords\v201609\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201609\cm\AdGroupCriterion;
use Google\AdsApi\AdWords\v201609\cm\Criterion;
use Google\AdsApi\AdWords\v201609\cm\AdGroup;
use Google\AdsApi\AdWords\v201609\cm\AdGroupAd;
use Google\AdsApi\AdWords\v201609\cm\AdGroupService;
use Google\AdsApi\AdWords\v201609\cm\AdGroupAdService;
use Google\AdsApi\AdWords\v201609\cm\AdGroupStatus;
use Google\AdsApi\AdWords\v201609\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201609\cm\CpcBid;
use Google\AdsApi\AdWords\v201609\cm\Money;
use Google\AdsApi\AdWords\v201609\cm\AdGroupAdOperation;
use Google\AdsApi\AdWords\v201609\cm\KeywordMatchType;
use Google\AdsApi\AdWords\v201609\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201609\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201609\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201609\cm\Budget;
use Google\AdsApi\AdWords\v201609\cm\BudgetBudgetDeliveryMethod;
use Google\AdsApi\AdWords\v201609\cm\BudgetOperation;
use Google\AdsApi\AdWords\v201609\cm\BudgetService;
use Google\AdsApi\AdWords\v201609\cm\LabelService;
use Google\AdsApi\AdWords\v201609\cm\Label;
use Google\AdsApi\AdWords\v201609\cm\CampaignLabel;
use Google\AdsApi\AdWords\v201609\cm\CampaignLabelOperation;
use Google\AdsApi\AdWords\v201609\cm\AdGroupLabel;
use Google\AdsApi\AdWords\v201609\cm\AdGroupLabelOperation;
use Google\AdsApi\AdWords\v201609\cm\AdGroupAdLabel;
use Google\AdsApi\AdWords\v201609\cm\AdGroupAdLabelOperation;
// Get all products
$func = function ($row) {
return new Product($row);
};
$this->productCollection = collect($this->products->fetchAll($func));
$this->info('['.date('Y-m-d H:i:s').'] '.$this->productCollection->count().' products loaded');
// Get all brands
$this->line('['.date('Y-m-d H:i:s').'] Loading brands...');
$func = function ($row) {
$product = new Product($row);
return $product->getAttribute('brand');
};
$this->brandCollection = collect($this->products->fetchAll($func))->unique();
$this->info('['.date('Y-m-d H:i:s').'] '.$this->brandCollection->count().' brands loaded');
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile()
->build();
// Construct an API session configured from a properties file and the OAuth2
// credentials above.
$this->adwordsSession = (new AdWordsSessionBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
$this->brandCollection->each(function ($brand, $key) {
if($brand == 'Brand'){ return; }
try {
// Check if campaign for this brand already exists
if( !($campaign = $this->campaignCollection->where('name',sprintf($this->campaignNameTemplate,$brand))->first()) ) {
$this->line('['.date('Y-m-d H:i:s').'] Campaign does not exists: '.sprintf($this->campaignNameTemplate,$brand));
// Create new campaign
$campaign = $this->addCampaign($brand);
}
$this->currentCampaigns[] = $campaign['id'];
$adGroupAdOperations = array();
$keywordOperations = array();
$this->productCollection->each(function ($product, $key) use ($brand, $campaign, &$adGroupAdOperations, &$keywordOperations){
if( $product->getAttribute('brand') == $brand ){
foreach( $this->adGroupKeys as $adGroupKey ){
// Check if the Ad Group exists
if( !($adGroup = $this->adGroupExists($campaign['id'],$product->getAttribute($adGroupKey))) ){
// Create new Ad Group
$adGroup = $this->addAdGroup($campaign['id'],$product->getAttribute($adGroupKey));
// Create ad
$ad = new Ad($product,$campaign,$adGroup,$adGroupKey);
$adGroupAdOperations[] = $ad->getOperation();
} else {
// Remove existing ads
$adGroupAdOperations = array_merge($adGroupAdOperations,$this->getAdRemovalOperations($adGroup));
// Create ad
$ad = new Ad($product,$campaign,$adGroup,$adGroupKey);
$adGroupAdOperations[] = $ad->getOperation();
}
$this->currentAdGroups[] = $adGroup['id'];
// Check if the Keyword exists in ad group
if( !($keyword = $this->keywordExists($adGroup['id'],$product->getAttribute($adGroupKey))) ){
// Create keyword
$keyword = new AdKeyword($adGroup['id'],$product->getAttribute($adGroupKey));
if(strlen($product->getAttribute($adGroupKey)) >= 6){
$keyword->addAdGroupCriterion(KeywordMatchType::BROAD);
}
$keyword->addAdGroupCriterion(KeywordMatchType::EXACT);
$keywordOperations = array_merge($keywordOperations,$keyword->getOperations());
$keyword = new AdKeyword($adGroup['id'],$product->getAttribute('brand').' '.$product->getAttribute($adGroupKey));
$keyword->addAdGroupCriterion(KeywordMatchType::EXACT);
$keywordOperations = array_merge($keywordOperations,$keyword->getOperations());
$keyword = new AdKeyword($adGroup['id'],$product->getAttribute($adGroupKey).' '.$product->getAttribute('brand'));
$keyword->addAdGroupCriterion(KeywordMatchType::EXACT);
$keywordOperations = array_merge($keywordOperations,$keyword->getOperations());
$keyword = new AdKeyword($adGroup['id'],$product->getAttribute($adGroupKey).' '.$product->getAttribute('brand').' '.$product->getAttribute('series'));
$keyword->addAdGroupCriterion(KeywordMatchType::EXACT);
$keywordOperations = array_merge($keywordOperations,$keyword->getOperations());
$keyword = new AdKeyword($adGroup['id'],$product->getAttribute('brand').' '.$product->getAttribute('series').' '.$product->getAttribute($adGroupKey));
$keyword->addAdGroupCriterion(KeywordMatchType::EXACT);
$keywordOperations = array_merge($keywordOperations,$keyword->getOperations());
} else {
$this->line('['.date('Y-m-d H:i:s').'] Keyword exists: '.$product->getAttribute($adGroupKey));
$this->currentKeywords[] = $keyword['id'];
}
}
}
});
// Create and remove ads on server Adwords
if( count($adGroupAdOperations) > 0 ){
try {
$adGroupAdResult = $this->adGroupAdService->mutate($adGroupAdOperations);
foreach ($adGroupAdResult->getValue() as $adGroupAd) {
$this->currentAds[] = $adGroupAd->getAd()->getId();
$this->info('['.date('Y-m-d H:i:s').'] Ads updated for ad group '.$adGroupAd->getAdGroupId());
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] An error occured while updating ads ('.$e->getMessage().')');
}
}
// Create and remove keywords on server Adwords
if( count($keywordOperations) > 0 ){
try {
$keywordResult = $this->adGroupCriterionService->mutate($keywordOperations);
foreach ($keywordResult->getValue() as $keyword) {
$this->currentKeywords[] = $keyword->getCriterion()->getId();
$this->info('['.date('Y-m-d H:i:s').'] Keyword updated for ad group '.$keyword->getAdGroupId().', keyword: '.$keyword->getCriterion()->getText());
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] An error occured while updating ads ('.$e->getMessage().')');
}
}
} catch (Exception $e){
Log::error($e->getMessage());
$this->error('['.date('Y-m-d H:i:s').'] An error occured while creating/updating campaigns, ad groups, ads and keywords ('.$e->getMessage().')');
}
});
$this->addLabels();
$this->cleanup();
}
private function cleanup(){
$this->removeKeywords();
$this->removeAdGroupAds();
$this->removeAdGroups();
$this->removeCampaigns();
}
private function addLabels(){
$this->addAdGroupLabels();
$this->addCampaignLabels();
$this->addAdGroupAdLabels();
$this->addKeywordLabels();
}
private function addCampaignLabels(){
$this->info('['.date('Y-m-d H:i:s').'] Start add default label to campaigns...');
$label = $this->getDefaultLabel();
// Add labels to campaigns
$operations = array();
foreach( $this->currentCampaigns as $campaignId ){
$campaignLabel = new CampaignLabel();
$campaignLabel->setCampaignId($campaignId);
$campaignLabel->setLabelId($label->getId());
$operation = new CampaignLabelOperation();
$operation->setOperand($campaignLabel);
$operation->setOperator(Operator::SET);
$operations[] = $operation;
}
$totalNumEntries = 0;
$collection = collect($operations);
if( count($operations) > 0 ){
$chunks = $collection->chunk(2000);
foreach($chunks as $chunk){
$operations = $chunk->toArray();
try {
$result = $this->campaignService->mutate($operations);
foreach ($result->getValue() as $value) {
$this->info('['.date('Y-m-d H:i:s').'] Campaign label '.$value->getName().' added');
$totalNumEntries++;
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Some labels can not be added to campaigns');
}
}
}
$this->line('['.date('Y-m-d H:i:s').'] Campaign label summary:');
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' labels added to campaigns');
if( $totalNumEntries<$collection->count() ){
$this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' labels can not be added to campaigns');
}
}
private function addAdGroupLabels(){
$this->info('['.date('Y-m-d H:i:s').'] Start add default label to ad groups...');
$label = $this->getDefaultLabel();
// Add labels to ad groups
$operations = array();
foreach( $this->currentAdGroups as $adGroupId ){
$adGroupLabel = new AdGroupLabel();
$adGroupLabel->setAdGroupId($adGroupId);
$adGroupLabel->setLabelId($label->getId());
$operation = new AdGroupLabelOperation();
$operation->setOperand($adGroupLabel);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;
}
$totalNumEntries = 0;
$collection = collect($operations);
if( count($operations) > 0 ){
$chunks = $collection->chunk(2000);
foreach($chunks as $chunk){
$operations = $chunk->toArray();
try {
$result = $this->adGroupService->mutate($operations);
foreach ($result->getValue() as $value) {
$this->info('['.date('Y-m-d H:i:s').'] Ad group label '.$value->getName().' added');
$totalNumEntries++;
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Some labels can not be added to ad groups');
}
}
}
$this->line('['.date('Y-m-d H:i:s').'] Ad group label summary:');
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' labels added to ad groups');
if( $totalNumEntries<$collection->count() ){
$this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' labels can not be added to ad groups');
}
}
private function addAdGroupAdLabels(){
$this->info('['.date('Y-m-d H:i:s').'] Start add default label to campaigns...');
$label = $this->getDefaultLabel();
// Add labels to campaigns
$operations = array();
foreach( $this->currentCampaigns as $campaignId ){
$campaignLabel = new CampaignLabel();
$campaignLabel->setCampaignId($campaignId);
$campaignLabel->setLabelId($label->getId());
$operation = new CampaignLabelOperation();
$operation->setOperand($campaignLabel);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;
}
$totalNumEntries = 0;
$collection = collect($operations);
if( count($operations) > 0 ){
$chunks = $collection->chunk(2000);
foreach($chunks as $chunk){
$operations = $chunk->toArray();
try {
$result = $this->campaignService->mutate($operations);
foreach ($result->getValue() as $value) {
$this->info('['.date('Y-m-d H:i:s').'] Campaign label '.$value->getName().' added');
$totalNumEntries++;
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Some labels can not be added to campaigns');
}
}
}
$this->line('['.date('Y-m-d H:i:s').'] Campaign label summary:');
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' labels added to campaigns');
if( $totalNumEntries<$collection->count() ){
$this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old campaigns can not be removed');
$this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' labels can not be added to campaigns');
}
}
private function addKeywordLabels(){
$this->info('['.date('Y-m-d H:i:s').'] Start add default label to campaigns...');
$label = $this->getDefaultLabel();
// Add labels to campaigns
$operations = array();
foreach( $this->currentCampaigns as $campaignId ){
$campaignLabel = new CampaignLabel();
$campaignLabel->setCampaignId($campaignId);
$campaignLabel->setLabelId($label->getId());
$operation = new CampaignLabelOperation();
$operation->setOperand($campaignLabel);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;
}
$totalNumEntries = 0;
$collection = collect($operations);
if( count($operations) > 0 ){
$chunks = $collection->chunk(2000);
foreach($chunks as $chunk){
$operations = $chunk->toArray();
try {
$result = $this->campaignService->mutate($operations);
foreach ($result->getValue() as $value) {
$this->info('['.date('Y-m-d H:i:s').'] Campaign label '.$value->getName().' added');
$totalNumEntries++;
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Some labels can not be added to campaigns');
}
}
}
$this->line('['.date('Y-m-d H:i:s').'] Campaign label summary:');
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' labels added to campaigns');
if( $totalNumEntries<$collection->count() ){
$this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old campaigns can not be removed');
$this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' labels can not be added to campaigns');
}
}
private function getAdRemovalOperations($adGroup){
$operations = array();
$results = $this->adGroupAdCollection->where('adGroupId',$adGroup['id']);
$results->each(function ($adGroupAd, $key) use (&$operations){
$operation = new AdGroupAdOperation();
$operation->setOperand($adGroupAd['adGroupAd']);
$operation->setOperator(Operator::REMOVE);
$operations[] = $operation;
});
return $operations;
}
$chunks = $collection->chunk(2000);
foreach($chunks as $chunk){
$operations = $chunk->toArray();
try {
$result = $this->campaignService->mutate($operations);
foreach ($result->getValue() as $value) {
$this->info('['.date('Y-m-d H:i:s').'] Campaign '.$value->getName().' removed');
$totalNumEntries++;
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Some campaigns can not be removed ('.$e->getMessage().')');
}
}
}
$this->line('['.date('Y-m-d H:i:s').'] Campaigns summary:');
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' old campaigns removed');
if( $totalNumEntries<$collection->count() ){
$this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old campaigns can not be removed');
}
}
private function loadAdGroups(){
$this->line('['.date('Y-m-d H:i:s').'] Loading ad groups...');
$this->adGroupCollection = collect();
// Get all current ad groups
$this->adGroupService = $this->adWordsServices->get($this->adwordsSession, AdGroupService::class);
$selector = new Selector();
$selector->setFields(['Id', 'Name','CampaignId']);
$selector->setOrdering([new OrderBy('Id', SortOrder::ASCENDING)]);
$selector->setPaging(new Paging(0,500));
$selector->setPredicates([
new Predicate('Status', PredicateOperator::IN, [AdGroupStatus::ENABLED,AdGroupStatus::PAUSED])
]);
$totalNumEntries = 0;
try {
do {
// Make the get request.
$page = $this->adGroupService->get($selector);
// Display results.
if ($page->getEntries() !== null) {
$totalNumEntries = $page->getTotalNumEntries();
foreach ($page->getEntries() as $adGroup) {
$this->adGroupCollection->push(array('id' => $adGroup->getId(), 'name' => $adGroup->getName(), 'campaignId' => $adGroup->getCampaignId(),'adGroup' => $adGroup));
}
}
// Advance the paging index.
$selector->getPaging()->setStartIndex(
$selector->getPaging()->getStartIndex()+500);
} while ($selector->getPaging()->getStartIndex() < $totalNumEntries);
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Error loading ad groups ('.$e->getMessage().')');
}
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' ad groups loaded');
return $this->adGroupCollection;
}
private function removeAdGroups(){
$this->line('['.date('Y-m-d H:i:s').'] Start removing old ad groups...');
// Get all current ad groups
$this->loadAdGroups();
$chunks = $collection->chunk(2000);
foreach($chunks as $chunk){
$operations = $chunk->toArray();
try {
$result = $this->adGroupService->mutate($operations);
foreach ($result->getValue() as $value) {
$this->info('['.date('Y-m-d H:i:s').'] Ad group '.$value->getName().' removed');
$totalNumEntries++;
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Some ad groups can not be removed ('.$e->getMessage().')');
}
}
}
$this->line('['.date('Y-m-d H:i:s').'] Ad groups summary:');
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' old ad groups removed');
if( $totalNumEntries<$collection->count() ){
$this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old ad groups can not be removed');
}
$chunks = $collection->chunk(2000);
foreach($chunks as $chunk){
$operations = $chunk->toArray();
try {
$result = $this->adGroupAdService->mutate($operations);
foreach ($result->getValue() as $value) {
$this->info('['.date('Y-m-d H:i:s').'] Ad '.$value->getAd()->getId().' removed');
$totalNumEntries++;
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Some ads can not be removed ('.$e->getMessage().')');
}
}
}
$this->line('['.date('Y-m-d H:i:s').'] Ads summary:');
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' old ads removed');
if( $totalNumEntries<$collection->count() ){
$this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old ads can not be removed');
}
// Get all current ads
$this->keywordService = $this->adWordsServices->get($this->adwordsSession, AdGroupCriterionService::class);
$selector = new Selector();
$selector->setFields(['Id', 'KeywordText','AdGroupId']);
$selector->setOrdering([new OrderBy('Id', SortOrder::ASCENDING)]);
$selector->setPaging(new Paging(0,500));
$totalNumEntries = 0;
try {
do {
// Make the get request.
$page = $this->keywordService->get($selector);
// Display results.
if ($page->getEntries() !== null) {
$totalNumEntries = $page->getTotalNumEntries();
foreach ($page->getEntries() as $keyword) {
$this->keywordCollection->push(array('id' => $keyword->getCriterion()->getId(),'text' => $keyword->getCriterion()->getText(), 'adGroupId' => $keyword->getAdGroupId(), 'object' => $keyword->getCriterion(), 'keyword' => $keyword));
}
}
// Advance the paging index.
$selector->getPaging()->setStartIndex(
$selector->getPaging()->getStartIndex()+500);
} while ($selector->getPaging()->getStartIndex() < $totalNumEntries);
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Error loading ads ('.$e->getMessage().')');
}
$chunks = $collection->chunk(2000);
foreach($chunks as $chunk){
$operations = $chunk->toArray();
try {
$result = $this->adGroupCriterionService->mutate($operations);
foreach ($result->getValue() as $value) {
$this->info('['.date('Y-m-d H:i:s').'] Keyword '.$value->getCriterion()->getId().' removed');
$totalNumEntries++;
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Some keywords can not be removed ('.$e->getMessage().')');
}
}
}
$this->line('['.date('Y-m-d H:i:s').'] Keywords summary:');
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' old keywords removed');
if( $totalNumEntries<$collection->count() ){
$this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old keywords can not be removed');
}
}
protected function adGroupExists($campaignId,$adGroupName){
$this->line('['.date('Y-m-d H:i:s').'] Start check if ad group already exsists...');
foreach( $this->adGroupCollection as $adGroup ){
if( $adGroup['campaignId'] == $campaignId && $adGroup['name'] == $adGroupName ){
$this->line('['.date('Y-m-d H:i:s').'] Ad group found: '.$adGroup['id']);
return $adGroup;
}
}
$this->line('['.date('Y-m-d H:i:s').'] No ad group found for: '.$adGroupName);
return false;
}
protected function keywordExists($adGroupId,$keywordText){
$this->line('['.date('Y-m-d H:i:s').'] Start check if ad group already exsists...');
protected function addAdGroup($campaignId,$adGroupName){
$this->line('['.date('Y-m-d H:i:s').'] Start creating ad group...');
// Create an ad group with required settings and specified status.
$adGroup = new AdGroup();
$adGroup->setCampaignId($campaignId);
$adGroup->setName($adGroupName);
$adGroup->setStatus(AdGroupStatus::ENABLED);
// Set bids (required).
$bid = new CpcBid();
$money = new Money();
$money->setMicroAmount(100000000);
$bid->setBid($money);
$biddingStrategyConfiguration = new BiddingStrategyConfiguration();
$biddingStrategyConfiguration->setBids([$bid]);
$adGroup->setBiddingStrategyConfiguration($biddingStrategyConfiguration);
// Create an ad group operation and add it to the operations list.
$operations = array();
$operation = new AdGroupOperation();
$operation->setOperand($adGroup);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;
// Create the ad groups on the server and print out some information for
// each created ad group.
try {
$result = $this->adGroupService->mutate($operations);
foreach ($result->getValue() as $adGroup) {
$this->info('['.date('Y-m-d H:i:s').'] Ad group created: '.$adGroup->getName());
return array(
'id' => $adGroup->getId(),
'name' => $adGroup->getName(),
'campaignId' => $adGroup->getCampaignId(),
);
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Ad group creation failed ('.$e->getMessage().')');
}
}
protected function addCampaign($brand){
$this->line('['.date('Y-m-d H:i:s').'] Start creating campaign...');
// Create a campaign with only required settings.
$campaign = new Campaign();
$campaign->setName(sprintf($this->campaignNameTemplate,$brand));
$campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH);
// Set shared budget (required).
$campaign->setBudget(new Budget());
$campaign->getBudget()->setBudgetId($this->getDefaultBudget()->getBudgetId());
// Set bidding strategy (required).
$biddingStrategyConfiguration = new BiddingStrategyConfiguration();
$biddingStrategyConfiguration->setBiddingStrategyType(
BiddingStrategyType::TARGET_SPEND);
$campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);
$campaign->setStatus(CampaignStatus::ENABLED);
// Create a campaign operation and add it to the operations list.
$operations = array();
$operation = new CampaignOperation();
$operation->setOperand($campaign);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;
// Create the campaigns on the server and print out some information for
// each created campaign.
try {
if($result = $this->campaignService->mutate($operations)->getValue()){
$this->info('['.date('Y-m-d H:i:s').'] Campaign created: '.sprintf($this->campaignNameTemplate,$result[0]->getName()));
return array(
'id' => $result[0]->getId(),
'name' => $result[0]->getName(),
);
} else {
throw new ApiException(sprintf('['.date('Y-m-d H:i:s').'] Campaign creation failed: %s',$campaign->getName()));
}
} catch(ApiException $e){
$this->error('['.date('Y-m-d H:i:s').'] Campaign creation failed ('.$e->getMessage().')');
}
}
// Get current default budget
protected function getDefaultBudget(){
I get keeping the following message: [SoapFault] Unmarshalling Error: cvc-elt.4.3: Type 'ns1:AdGroupLabelOperation' is not validly derived from the type definition, 'AdGroupOperation', of element 'ns1:operations'
But I can't find what I'm doing wrong with the AdGroupLabelOperations. I get the same when I want to use CampaignLabelOperation. Same message... I can get, update, remove campaigns, ad groups, ads and keywords without any problems. But add labels to campaigns, ad groups, ads en keywords aren't working.
It's not the best code, but it does the job for now.
This is my code: `<?php
namespace App\Console\Commands;
use Illuminate\Console\Command; use League\Csv\Reader; use Illuminate\Support\Facades\Log;
use App\Adwords\Product; use App\Adwords\Ad; use App\Adwords\AdKeyword;
use Google\AdsApi\AdWords\AdWordsSessionBuilder; use Google\AdsApi\Common\OAuth2TokenBuilder; use Google\AdsApi\AdWords\AdWordsServices; use Google\AdsApi\AdWords\v201609\cm\ApiException;
use Google\AdsApi\AdWords\v201609\cm\Predicate; use Google\AdsApi\AdWords\v201609\cm\PredicateOperator; use Google\AdsApi\AdWords\v201609\cm\Selector; use Google\AdsApi\AdWords\v201609\cm\Operator; use Google\AdsApi\AdWords\v201609\cm\Paging; use Google\AdsApi\AdWords\v201609\cm\SortOrder; use Google\AdsApi\AdWords\v201609\cm\OrderBy;
use Google\AdsApi\AdWords\v201609\cm\Campaign; use Google\AdsApi\AdWords\v201609\cm\CampaignService; use Google\AdsApi\AdWords\v201609\cm\CampaignOperation; use Google\AdsApi\AdWords\v201609\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201609\cm\AdGroupCriterionService; use Google\AdsApi\AdWords\v201609\cm\AdGroupAdStatus; use Google\AdsApi\AdWords\v201609\cm\AdGroupCriterionOperation; use Google\AdsApi\AdWords\v201609\cm\AdGroupCriterion; use Google\AdsApi\AdWords\v201609\cm\Criterion;
use Google\AdsApi\AdWords\v201609\cm\AdGroup; use Google\AdsApi\AdWords\v201609\cm\AdGroupAd; use Google\AdsApi\AdWords\v201609\cm\AdGroupService; use Google\AdsApi\AdWords\v201609\cm\AdGroupAdService; use Google\AdsApi\AdWords\v201609\cm\AdGroupStatus; use Google\AdsApi\AdWords\v201609\cm\AdGroupOperation; use Google\AdsApi\AdWords\v201609\cm\CpcBid; use Google\AdsApi\AdWords\v201609\cm\Money; use Google\AdsApi\AdWords\v201609\cm\AdGroupAdOperation; use Google\AdsApi\AdWords\v201609\cm\KeywordMatchType;
use Google\AdsApi\AdWords\v201609\cm\AdvertisingChannelType; use Google\AdsApi\AdWords\v201609\cm\BiddingStrategyConfiguration; use Google\AdsApi\AdWords\v201609\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201609\cm\Budget; use Google\AdsApi\AdWords\v201609\cm\BudgetBudgetDeliveryMethod; use Google\AdsApi\AdWords\v201609\cm\BudgetOperation; use Google\AdsApi\AdWords\v201609\cm\BudgetService;
use Google\AdsApi\AdWords\v201609\cm\LabelService; use Google\AdsApi\AdWords\v201609\cm\Label; use Google\AdsApi\AdWords\v201609\cm\CampaignLabel; use Google\AdsApi\AdWords\v201609\cm\CampaignLabelOperation; use Google\AdsApi\AdWords\v201609\cm\AdGroupLabel; use Google\AdsApi\AdWords\v201609\cm\AdGroupLabelOperation; use Google\AdsApi\AdWords\v201609\cm\AdGroupAdLabel; use Google\AdsApi\AdWords\v201609\cm\AdGroupAdLabelOperation;
class BlauwproUpdateAdwords extends Command { /**
@var string */ protected $signature = 'blauwpro:adwords:update';
/**
Own variables */ protected $campaignNameTemplate = 'API %s';
protected $defaultBudgetName = 'API default budget'; protected $defaultBudget;
protected $defaultLabelName = 'API'; protected $defaultLabel;
protected $products = array();
protected $adwordsSession; protected $campaignService; protected $budgetService; protected $labelService; protected $adGroupAdService; protected $adGroupCriterionService;
protected $campaignCollection; protected $adGroupCollection; protected $productCollection; protected $brandCollection; protected $adGroupAdCollection; protected $keywordCollection;
protected $adGroupKeys = array('manufacturerProductId','gtin'); protected $operations = array(); protected $keywordOperations = array(); protected $adGroupAdOperations = array();
protected $currentCampaigns = array(); protected $currentAdGroups = array(); protected $currentAds = array(); protected $currentKeywords = array();
/**
@var string */ protected $description = 'Create or update Blauwpro product ads';
/**
@return void */ public function construct() { parent::construct();
$this->campaignCollection = collect(); $this->adGroupCollection = collect(); $this->productCollection = collect(); $this->brandCollection = collect(); $this->adGroupAdCollection = collect(); $this->keywordCollection = collect();
}
/**
@return mixed */ public function handle() { $this->info('['.date('Y-m-d H:i:s').'] Start creating Adwords ads for Blauwpro');
// Load the CSV document $this->line('['.date('Y-m-d H:i:s').'] Loading products...'); $filePath = storage_path('app/blauwpro-products-10a.csv'); $this->products = Reader::createFromPath($filePath); $this->products->setDelimiter(';'); $this->products->setOffset(1);
// Get all products $func = function ($row) { return new Product($row); }; $this->productCollection = collect($this->products->fetchAll($func)); $this->info('['.date('Y-m-d H:i:s').'] '.$this->productCollection->count().' products loaded');
// Get all brands $this->line('['.date('Y-m-d H:i:s').'] Loading brands...'); $func = function ($row) { $product = new Product($row); return $product->getAttribute('brand'); }; $this->brandCollection = collect($this->products->fetchAll($func))->unique(); $this->info('['.date('Y-m-d H:i:s').'] '.$this->brandCollection->count().' brands loaded');
// Generate a refreshable OAuth2 credential for authentication. $oAuth2Credential = (new OAuth2TokenBuilder()) ->fromFile() ->build();
// Construct an API session configured from a properties file and the OAuth2 // credentials above. $this->adwordsSession = (new AdWordsSessionBuilder()) ->fromFile() ->withOAuth2Credential($oAuth2Credential) ->build();
// Create AdwordsServices $this->adWordsServices = new AdwordsServices(); $this->adGroupCriterionService = $this->adWordsServices->get($this->adwordsSession, AdGroupCriterionService::class);
$this->loadCampaigns(); $this->loadAdGroups(); $this->loadAdGroupAds(); $this->loadKeywords();
$this->brandCollection->each(function ($brand, $key) { if($brand == 'Brand'){ return; } try { // Check if campaign for this brand already exists
if( !($campaign = $this->campaignCollection->where('name',sprintf($this->campaignNameTemplate,$brand))->first()) ) {
});
$this->addLabels(); $this->cleanup();
}
private function cleanup(){ $this->removeKeywords(); $this->removeAdGroupAds(); $this->removeAdGroups(); $this->removeCampaigns();
}
private function addLabels(){ $this->addAdGroupLabels(); $this->addCampaignLabels(); $this->addAdGroupAdLabels(); $this->addKeywordLabels();
}
private function addCampaignLabels(){
$this->info('['.date('Y-m-d H:i:s').'] Start add default label to campaigns...');
$label = $this->getDefaultLabel();
// Add labels to campaigns $operations = array(); foreach( $this->currentCampaigns as $campaignId ){ $campaignLabel = new CampaignLabel(); $campaignLabel->setCampaignId($campaignId); $campaignLabel->setLabelId($label->getId());
}
$totalNumEntries = 0;
$collection = collect($operations); if( count($operations) > 0 ){ $chunks = $collection->chunk(2000); foreach($chunks as $chunk){ $operations = $chunk->toArray(); try {
$result = $this->campaignService->mutate($operations);
foreach ($result->getValue() as $value) { $this->info('['.date('Y-m-d H:i:s').'] Campaign label '.$value->getName().' added'); $totalNumEntries++; } } catch(ApiException $e){ $this->error('['.date('Y-m-d H:i:s').'] Some labels can not be added to campaigns'); } } }
$this->line('['.date('Y-m-d H:i:s').'] Campaign label summary:'); $this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' labels added to campaigns'); if( $totalNumEntries<$collection->count() ){ $this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' labels can not be added to campaigns'); }
}
private function addAdGroupLabels(){
$this->info('['.date('Y-m-d H:i:s').'] Start add default label to ad groups...');
$label = $this->getDefaultLabel();
// Add labels to ad groups $operations = array(); foreach( $this->currentAdGroups as $adGroupId ){ $adGroupLabel = new AdGroupLabel(); $adGroupLabel->setAdGroupId($adGroupId); $adGroupLabel->setLabelId($label->getId());
}
$totalNumEntries = 0;
$collection = collect($operations); if( count($operations) > 0 ){ $chunks = $collection->chunk(2000); foreach($chunks as $chunk){ $operations = $chunk->toArray(); try { $result = $this->adGroupService->mutate($operations); foreach ($result->getValue() as $value) { $this->info('['.date('Y-m-d H:i:s').'] Ad group label '.$value->getName().' added'); $totalNumEntries++; } } catch(ApiException $e){ $this->error('['.date('Y-m-d H:i:s').'] Some labels can not be added to ad groups'); } } }
$this->line('['.date('Y-m-d H:i:s').'] Ad group label summary:'); $this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' labels added to ad groups'); if( $totalNumEntries<$collection->count() ){ $this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' labels can not be added to ad groups'); }
}
private function addAdGroupAdLabels(){
$this->info('['.date('Y-m-d H:i:s').'] Start add default label to campaigns...');
$label = $this->getDefaultLabel();
// Add labels to campaigns $operations = array(); foreach( $this->currentCampaigns as $campaignId ){ $campaignLabel = new CampaignLabel(); $campaignLabel->setCampaignId($campaignId); $campaignLabel->setLabelId($label->getId());
}
$totalNumEntries = 0;
$collection = collect($operations); if( count($operations) > 0 ){ $chunks = $collection->chunk(2000); foreach($chunks as $chunk){ $operations = $chunk->toArray(); try { $result = $this->campaignService->mutate($operations); foreach ($result->getValue() as $value) { $this->info('['.date('Y-m-d H:i:s').'] Campaign label '.$value->getName().' added'); $totalNumEntries++; } } catch(ApiException $e){ $this->error('['.date('Y-m-d H:i:s').'] Some labels can not be added to campaigns'); } } }
$this->line('['.date('Y-m-d H:i:s').'] Campaign label summary:'); $this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' labels added to campaigns'); if( $totalNumEntries<$collection->count() ){ $this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old campaigns can not be removed'); $this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' labels can not be added to campaigns'); }
}
private function addKeywordLabels(){
$this->info('['.date('Y-m-d H:i:s').'] Start add default label to campaigns...');
$label = $this->getDefaultLabel();
// Add labels to campaigns $operations = array(); foreach( $this->currentCampaigns as $campaignId ){ $campaignLabel = new CampaignLabel(); $campaignLabel->setCampaignId($campaignId); $campaignLabel->setLabelId($label->getId());
}
$totalNumEntries = 0;
$collection = collect($operations); if( count($operations) > 0 ){ $chunks = $collection->chunk(2000); foreach($chunks as $chunk){ $operations = $chunk->toArray(); try { $result = $this->campaignService->mutate($operations); foreach ($result->getValue() as $value) { $this->info('['.date('Y-m-d H:i:s').'] Campaign label '.$value->getName().' added'); $totalNumEntries++; } } catch(ApiException $e){ $this->error('['.date('Y-m-d H:i:s').'] Some labels can not be added to campaigns'); } } }
$this->line('['.date('Y-m-d H:i:s').'] Campaign label summary:'); $this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' labels added to campaigns'); if( $totalNumEntries<$collection->count() ){ $this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old campaigns can not be removed'); $this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' labels can not be added to campaigns'); }
}
private function getAdRemovalOperations($adGroup){ $operations = array(); $results = $this->adGroupAdCollection->where('adGroupId',$adGroup['id']); $results->each(function ($adGroupAd, $key) use (&$operations){ $operation = new AdGroupAdOperation(); $operation->setOperand($adGroupAd['adGroupAd']); $operation->setOperator(Operator::REMOVE); $operations[] = $operation; }); return $operations; }
private function loadCampaigns(){
$this->line('['.date('Y-m-d H:i:s').'] Loading campaigns...');
$this->campaignCollection = collect();
// Get all current campaigns
$this->campaignService = $this->adWordsServices->get($this->adwordsSession, CampaignService::class); $selector = new Selector(); $selector->setFields(['Id', 'Name']); $selector->setOrdering([new OrderBy('Id', SortOrder::ASCENDING)]); $selector->setPaging(new Paging(0,500)); $selector->setPredicates([ new Predicate('Status', PredicateOperator::IN, [CampaignStatus::ENABLED,CampaignStatus::PAUSED]) ]);
$totalNumEntries = 0; try { do { // Make the get request. $page = $this->campaignService->get($selector); // Display results. if ($page->getEntries() !== null) { $totalNumEntries = $page->getTotalNumEntries(); foreach ($page->getEntries() as $campaign) { $this->campaignCollection->push(array('id' => $campaign->getId(), 'name' => $campaign->getName(),'campaign' => $campaign)); } } // Advance the paging index. $selector->getPaging()->setStartIndex( $selector->getPaging()->getStartIndex()+500); } while ($selector->getPaging()->getStartIndex() < $totalNumEntries); } catch(ApiException $e){ $this->error('['.date('Y-m-d H:i:s').'] Error loading campaigns ('.$e->getMessage().')'); }
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' campaigns loaded'); }
private function removeCampaigns(){
$this->line('['.date('Y-m-d H:i:s').'] Start removing old campaigns...');
// Get all current campaigns
$this->loadCampaigns();
$operations = array();
foreach($this->campaignCollection as $campaign){
if( !in_array($campaign['id'],$this->currentCampaigns) ){
}
$totalNumEntries = 0;
$collection = collect($operations); if( count($operations) > 0 ){
}
$this->line('['.date('Y-m-d H:i:s').'] Campaigns summary:'); $this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' old campaigns removed'); if( $totalNumEntries<$collection->count() ){ $this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old campaigns can not be removed'); } }
private function loadAdGroups(){
$this->line('['.date('Y-m-d H:i:s').'] Loading ad groups...');
$this->adGroupCollection = collect();
// Get all current ad groups $this->adGroupService = $this->adWordsServices->get($this->adwordsSession, AdGroupService::class);
$selector = new Selector(); $selector->setFields(['Id', 'Name','CampaignId']); $selector->setOrdering([new OrderBy('Id', SortOrder::ASCENDING)]); $selector->setPaging(new Paging(0,500)); $selector->setPredicates([ new Predicate('Status', PredicateOperator::IN, [AdGroupStatus::ENABLED,AdGroupStatus::PAUSED]) ]);
$totalNumEntries = 0; try { do { // Make the get request. $page = $this->adGroupService->get($selector); // Display results. if ($page->getEntries() !== null) { $totalNumEntries = $page->getTotalNumEntries(); foreach ($page->getEntries() as $adGroup) { $this->adGroupCollection->push(array('id' => $adGroup->getId(), 'name' => $adGroup->getName(), 'campaignId' => $adGroup->getCampaignId(),'adGroup' => $adGroup)); } } // Advance the paging index. $selector->getPaging()->setStartIndex( $selector->getPaging()->getStartIndex()+500); } while ($selector->getPaging()->getStartIndex() < $totalNumEntries); } catch(ApiException $e){ $this->error('['.date('Y-m-d H:i:s').'] Error loading ad groups ('.$e->getMessage().')'); }
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' ad groups loaded');
return $this->adGroupCollection; }
private function removeAdGroups(){
// Get all current ad groups
$this->loadAdGroups();
$operations = array();
foreach($this->adGroupCollection as $adGroup){
if( !in_array($adGroup['id'],$this->currentAdGroups) && in_array($adGroup['adGroup']->getCampaignId(),$this->currentCampaigns) ){
}
$totalNumEntries = 0; $collection = collect($operations); if( count($operations) > 0 ){
}
$this->line('['.date('Y-m-d H:i:s').'] Ad groups summary:'); $this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' old ad groups removed'); if( $totalNumEntries<$collection->count() ){ $this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old ad groups can not be removed'); }
}
private function loadAdGroupAds(){
$this->line('['.date('Y-m-d H:i:s').'] Loading ads...');
$this->adGroupAdCollection = collect();
// Get all current ads
$this->adGroupAdService = $this->adWordsServices->get($this->adwordsSession, AdGroupAdService::class); $selector = new Selector(); $selector->setFields(['Id', 'Name']); $selector->setOrdering([new OrderBy('Id', SortOrder::ASCENDING)]); $selector->setPaging(new Paging(0,500)); $selector->setPredicates([ new Predicate('Status', PredicateOperator::IN, [AdGroupAdStatus::ENABLED,AdGroupAdStatus::PAUSED]) ]);
$totalNumEntries = 0; try { do { // Make the get request. $page = $this->adGroupAdService->get($selector); // Display results. if ($page->getEntries() !== null) { $totalNumEntries = $page->getTotalNumEntries(); foreach ($page->getEntries() as $adGroupAd) { $this->adGroupAdCollection->push(array('id' => $adGroupAd->getAd()->getId(), 'adGroupId' => $adGroupAd->getAdGroupId(), 'object' => $adGroupAd->getAd(),'adGroupAd' => $adGroupAd)); } } // Advance the paging index. $selector->getPaging()->setStartIndex( $selector->getPaging()->getStartIndex()+500); } while ($selector->getPaging()->getStartIndex() < $totalNumEntries); } catch(ApiException $e){ $this->error('['.date('Y-m-d H:i:s').'] Error loading ads ('.$e->getMessage().')'); }
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' ads loaded'); }
private function removeAdGroupAds(){
$this->line('['.date('Y-m-d H:i:s').'] Start removing old ads...');
// Get all current ad groups
$this->loadAdGroupAds();
$operations = array();
foreach($this->adGroupAdCollection as $adGroupAd){
if( !in_array($adGroupAd['id'],$this->currentAdGroups) && in_array($adGroupAd['adGroupAd']->getAdGroupId(),$this->currentAdGroups) ){
}
$totalNumEntries = 0; $collection = collect($operations); if( count($operations) > 0 ){
}
$this->line('['.date('Y-m-d H:i:s').'] Ads summary:'); $this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' old ads removed'); if( $totalNumEntries<$collection->count() ){ $this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old ads can not be removed'); }
}
private function loadKeywords(){
$this->line('['.date('Y-m-d H:i:s').'] Loading keywords...');
$this->keywordCollection = collect();
// Get all current ads
$this->keywordService = $this->adWordsServices->get($this->adwordsSession, AdGroupCriterionService::class); $selector = new Selector(); $selector->setFields(['Id', 'KeywordText','AdGroupId']); $selector->setOrdering([new OrderBy('Id', SortOrder::ASCENDING)]); $selector->setPaging(new Paging(0,500));
$totalNumEntries = 0; try { do { // Make the get request. $page = $this->keywordService->get($selector); // Display results. if ($page->getEntries() !== null) { $totalNumEntries = $page->getTotalNumEntries(); foreach ($page->getEntries() as $keyword) { $this->keywordCollection->push(array('id' => $keyword->getCriterion()->getId(),'text' => $keyword->getCriterion()->getText(), 'adGroupId' => $keyword->getAdGroupId(), 'object' => $keyword->getCriterion(), 'keyword' => $keyword)); } } // Advance the paging index. $selector->getPaging()->setStartIndex( $selector->getPaging()->getStartIndex()+500); } while ($selector->getPaging()->getStartIndex() < $totalNumEntries); } catch(ApiException $e){ $this->error('['.date('Y-m-d H:i:s').'] Error loading ads ('.$e->getMessage().')'); }
$this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' keywords loaded'); }
private function removeKeywords(){
$this->line('['.date('Y-m-d H:i:s').'] Start removing old keywords...');
// Get all current keywords $this->loadKeywords();
$operations = array();
foreach($this->keywordCollection as $keyword){
if( !in_array($keyword['id'],$this->currentKeywords) && in_array($keyword['adGroupId'],$this->currentAdGroups) ){
}
$totalNumEntries = 0; $collection = collect($operations); if( count($operations) > 0 ){
}
$this->line('['.date('Y-m-d H:i:s').'] Keywords summary:'); $this->info('['.date('Y-m-d H:i:s').'] '.$totalNumEntries.' old keywords removed'); if( $totalNumEntries<$collection->count() ){ $this->error('['.date('Y-m-d H:i:s').'] '.($totalNumEntries-$collection->count()).' old keywords can not be removed'); }
}
protected function adGroupExists($campaignId,$adGroupName){
$this->line('['.date('Y-m-d H:i:s').'] Start check if ad group already exsists...');
if( !$this->adGroupCollection ){ $this->loadAdGroups(); }
foreach( $this->adGroupCollection as $adGroup ){ if( $adGroup['campaignId'] == $campaignId && $adGroup['name'] == $adGroupName ){ $this->line('['.date('Y-m-d H:i:s').'] Ad group found: '.$adGroup['id']); return $adGroup; } } $this->line('['.date('Y-m-d H:i:s').'] No ad group found for: '.$adGroupName); return false; }
protected function keywordExists($adGroupId,$keywordText){
$this->line('['.date('Y-m-d H:i:s').'] Start check if ad group already exsists...');
if( !$this->keywordCollection ){ $this->loadKeywords(); }
foreach( $this->keywordCollection as $keyword ){ if( $keyword['adGroupId'] == $adGroupId && $keyword['text'] == $keywordText ){ $this->line('['.date('Y-m-d H:i:s').'] Keyword found: '.$keywordText); return $keyword; } } $this->line('['.date('Y-m-d H:i:s').'] No keyword found for: '.$keywordText); return false; }
protected function addAdGroup($campaignId,$adGroupName){
}
protected function addCampaign($brand){
}
// Get current default budget protected function getDefaultBudget(){
$this->line('['.date('Y-m-d H:i:s').'] Start loading default budget ('.$this->defaultBudgetName.')...');
if( $this->defaultBudget ){ $this->info('['.date('Y-m-d H:i:s').'] Default budget loaded from memory'); return $this->defaultBudget; }
$this->budgetService = $this->adWordsServices->get($this->adwordsSession, BudgetService::class); $selector = new Selector(); $selector->setFields(['BudgetName']); $selector->setPredicates([ new Predicate('BudgetName', PredicateOperator::EQUALS, [$this->defaultBudgetName]) ]);
try { $budgets = $this->budgetService->get($selector)->getEntries(); if($budget = $budgets[0]){ $this->defaultBudget = $budget; $this->info('['.date('Y-m-d H:i:s').'] Default budget loaded'); return $budget; } else { throw new ApiException('['.date('Y-m-d H:i:s').'] Default budget not found'); } } catch(ApiException $e){ $this->error('['.date('Y-m-d H:i:s').'] Default budget not found ('.$e->getMessage().')'); }
}
private function getDefaultLabel(){
$this->info('['.date('Y-m-d H:i:s').'] Start loading default label ('.$this->defaultLabelName.')...');
if( $this->defaultLabel ){ $this->info('['.date('Y-m-d H:i:s').'] Default label loaded from memory'); return $this->defaultLabel; }
$this->labelService = $this->adWordsServices->get($this->adwordsSession, LabelService::class); $selector = new Selector(); $selector->setFields(['LabelName']); $selector->setPredicates([ new Predicate('LabelName', PredicateOperator::EQUALS, [$this->defaultLabelName]) ]);
try { $labels = $this->labelService->get($selector)->getEntries(); if($label = $labels[0]){ $this->defaultLabel = $label; $this->info('['.date('Y-m-d H:i:s').'] Default label loaded'); return $label; } else { throw new ApiException('['.date('Y-m-d H:i:s').'] Default label not found'); } } catch(ApiException $e){ $this->error('['.date('Y-m-d H:i:s').'] Default label not found ('.$e->getMessage().')'); }
}
} `