Giter VIP home page Giter VIP logo

laravel-google-ads's Introduction

Laravel 5.1+ Lumen 5.1+ Total Downloads License Build Status Code Climate Test Coverage

Google Ads API for Laravel

Integration of googleads/googleads-php-lib in Laravel and Lumen (version >5).

Setup

  • Run $ composer require spotonlive/laravel-google-ads

Laravel

  • (Only for Laravel 5.4 or minor) Add provider to config/app.php
'providers' => [
    LaravelGoogleAds\LaravelGoogleAdsProvider::class,
],
  • Run $ php artisan vendor:publish to publish the configuration file config/google-ads.php and insert:
    • developerToken
    • clientId & clientSecret
    • refreshToken

Lumen

  • Add provider to bootstrap/app.php
$app->register(LaravelGoogleAds\LaravelGoogleAdsProvider::class);
  • Copy vendor/spotonlive/laravel-google-ads/config/config.php to config/google-ads.php and insert:

    • developerToken
    • clientId & clientSecret
    • refreshToken
  • Add config to bootstrap/app.php

$app->configure('google-ads');

Generate refresh token

This requires that the clientId and clientSecret is from a native application.

Run $ php artisan googleads:token:generate and open the authorization url. Grant access to the app, and input the access token in the console. Copy the refresh token into your configuration config/google-ads.php

Basic usage

The following example is for AdWords, but the general code applies to all products.

<?php

namespace App\Services;

use LaravelGoogleAds\Services\AdWordsService;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\CampaignService;
use Google\AdsApi\AdWords\v201806\cm\OrderBy;
use Google\AdsApi\AdWords\v201806\cm\Paging;
use Google\AdsApi\AdWords\v201806\cm\Selector;

class Service
{
    /** @var AdWordsService */
    protected $adWordsService;
    
    /**
     * @param AdWordsService $adWordsService
     */
    public function __construct(AdWordsService $adWordsService)
    {
        $this->adWordsService = $adWordsService;
    }

    public function campaigns()
    {
        $customerClientId = 'xxx-xxx-xx';

        $campaignService = $this->adWordsService->getService(CampaignService::class, $customerClientId);

        // Create selector.
        $selector = new Selector();
        $selector->setFields(array('Id', 'Name'));
        $selector->setOrdering(array(new OrderBy('Name', 'ASCENDING')));

        // Create paging controls.
        $selector->setPaging(new Paging(0, 100));

        // Make the get request.
        $page = $campaignService->get($selector);
    }
}

Best practices

Features, requirements, support etc.

See googleads/googleads-php-lib

Dependencies

  • googleads/googleads-php-lib hosts the PHP client library for the various SOAP-based Ads APIs (AdWords, AdExchange Buyer, and DFP) at Google.

Credits

laravel-google-ads's People

Contributors

amaelftah avatar bilobait-lorenz avatar ebisbe avatar einkoro avatar finagin avatar matthewnessworthy avatar nikolajlovenhardt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-google-ads's Issues

googleads/googleads-php-lib": "^39.0.0"

Please update the package for comfortable googleads/googleads-php-lib": "^39.0.0" this version.
Because this version need this requirement to use this version
requires

php: >=5.6
ext-mbstring: *
ext-openssl: *
ext-soap: *
google/auth: ^1.0.0
guzzlehttp/guzzle: ^6.0
guzzlehttp/psr7: ^1.2
monolog/monolog: ^1.17.1
phpdocumentor/reflection-docblock: ^4.0.0 || ^3.0.3
symfony/serializer: ^2.8.0 || ^3.0.3 || ^4.0.0
requires (dev)

php: >=5.6
phpunit/phpunit: ^4.8.35 || ^5.7
squizlabs/php_codesniffer: ^2.9 || ^3.2
suggests

php-64bit: >=5.6

Class Google\AdsApi\AdWords\v201806\cm\CampaignService does not exist

Hi Friends,

I am using https://github.com/spotonlive/laravel-google-ads package for Google Ads. And I got the above error. Can anyone help me to resolve this?

My code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use LaravelGoogleAds\Services\AdWordsService;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201806\cm\CampaignService;
use Google\AdsApi\AdWords\v201806\cm\OrderBy;
use Google\AdsApi\AdWords\v201806\cm\Paging;
use Google\AdsApi\AdWords\v201806\cm\Selector;

class AdController extends Controller
{
    /** @var AdWordsService */
    protected $adWordsService;

    /**
     * @param AdWordsService $adWordsService
     */
    public function __construct(AdWordsService $adWordsService)
    {
        $this->adWordsService = $adWordsService;
    }


    public function index()
    {
        $customerClientId = '697-169-9937';

        $campaignService = $this->adWordsService->getService(CampaignService::class, $customerClientId);
         dd($campaignService);
        // Create selector.
        $selector = new Selector();
        $selector->setFields(array('Id', 'Name'));
        $selector->setOrdering(array(new OrderBy('Name', 'ASCENDING')));

        // Create paging controls.
        $selector->setPaging(new Paging(0, 100));

        // Make the get request.
        $page = $campaignService->get($selector);
    }
}

oauth2 OOB Deprecation

I've received an email from Google stating that the Out-Of-Band (OOB) Flow is being deprecated very soon (September/October 2022)

Is there a plan to update this repository to use a different authentication method that's supported?

https://developers.google.com/identity/protocols/oauth2/resources/oob-migration

For now I think I may need to fork the repo and make the changes myself but if anyone is able to let me know if/when this will be updated that would be amazing :) I'll create a PR of the changes if it's something you'd like to update here.

Laravel 5.4 support?

I'm getting the following error, which I guess is due to the dependencies' versions.

[InvalidArgumentException]                                                   
  Could not find package nikolajlovenhardt/laravel-google-ads at any version   
  for your minimum-stability (stable). Check the package spelling or your min  
  imum-stability 

Any plans on supporting 5.4 in the sort term?

Error on call Console Command

$ php artisan googleads:token:generate

[ReflectionException]
Method LaravelGoogleAds\Console\GenerateRefreshTokenCommand::handle() does not exist

Support for v201802

I was wondering how far will be the support for version v201802. Since v201705 and v201708 will be sunset on March 28, 2018. Thanks

Do you have plan for Google Dfp,?

I will looking for someone who working with Google-ads-libraries integrated with laravel. Yeah!! I found you guy, But unfortunately your repository have working AdWords Only.

I want to know. Do you have plan for it? or not Can I do that?

Create a new tag for the 201809 update

Could you create a new tag for the current version of master so the most recent update (to use googleads/googleads-php-lib v37) is available via composer in a versioned format?

SoapFault - Could not connect to host

Hi!

When is try the sample code (on localhost), I get this error: SoapFault - Could not connect to host.
(I have .pem file in curl.cainfo, in php.ini)

What is the problem? Thanks!

when i run the composer require nikolajlovenhardt/laravel-google-ads command it failed i need solutions

Problem 1
- nikolajlovenhardt/laravel-google-ads 1.2.7 requires ext-soap * -> the requested PHP extension soap is missing from your system.
- nikolajlovenhardt/laravel-google-ads 1.2.6 requires ext-soap * -> the requested PHP extension soap is missing from your system.
- nikolajlovenhardt/laravel-google-ads 1.2.5 requires ext-soap * -> the requested PHP extension soap is missing from your system.
- nikolajlovenhardt/laravel-google-ads 1.2.4 requires ext-soap * -> the requested PHP extension soap is missing from your system.
- nikolajlovenhardt/laravel-google-ads 1.2.3 requires ext-soap * -> the requested PHP extension soap is missing from your system.
- nikolajlovenhardt/laravel-google-ads 1.2.2 requires ext-soap * -> the requested PHP extension soap is missing from your system.
- nikolajlovenhardt/laravel-google-ads 1.2.1 requires ext-soap * -> the requested PHP extension soap is missing from your system.
- nikolajlovenhardt/laravel-google-ads 1.2.0 requires ext-soap * -> the requested PHP extension soap is missing from your system.
- Installation request for nikolajlovenhardt/laravel-google-ads ^1.2 -> satisfiable by nikolajlovenhardt/laravel-google-ads[1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7].

To enable extensions, verify that they are enabled in your .ini files:
- C:\xampp\php\php.ini
You can also run php --ini inside terminal to see which files are used by PHP in CLI mode.

Installation failed, reverting ./composer.json to its original content.

Composer Install Issue with googleads-php-lib 13.0

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for nikolajlovenhardt/laravel-google-ads dev-master -> satisfiable by nikolajlovenhardt/laravel-google-ads[dev-master].
- nikolajlovenhardt/laravel-google-ads dev-master requires googleads/googleads-php-lib ~11.0.0 -> satisfiable by googleads/googleads-php-lib[11.0.0] but these conflict with your requirements or minimum-stability.

AdExchangeSeller Service

To be able to use AdExchangeSeller API, do I have to add the adExchangeSeller index to config/google-ads.php with all the configurations? Do I just copy the 'adWords' object?

Do I also have to add some files to src/LaravelGoogleAds?

how to can't execute example i got error

Argument 1 passed to App\Classes\Service::__construct() must be an instance of LaravelGoogleAds\Services\AdWordsService, none given, called in C:\xampp\htdocs\test_laravel_project\app\Http\Controllers\TestController.php on line 16 and defined

Logging not using provided path

Hey,

I entered the path here in the config/google-ads.php, but Google's logger is trying to set a /soap_xml.log as opposed to __LARAVEL_DIR__/storage/logs/soap_xml.log.

    'settings' => [
        'LOGGING' => [
            /*
             * Log directory is either an absolute path, or relative path from the AdWordsUser.php file.
             */
            'PATH_RELATIVE' => '0',
            'LIB_LOG_DIR_PATH' => storage_path().'/logs',
        ],

I ended up setting a path in Google's Logger.php

$fp = fopen(storage_path().'/logs/'.$handleLocation, 'a');

Am I doing something wrong (besides the hack)? Or, โ€ฆ

*I have verified that the $user = new AdWordsUser(); contains those settings, with the proper directory structure.

Update

Hi
googleads-php-lib pack update to v24 but your package is old and v14
please update your code!
Ali

A quesiton about class dependencies

Hi there,

I have integrated your service and I can see it works (I can get the return array of the user and all that)
But when I use your sample code for getting the Campaign I get the following error.

Class 'App\Events\Frontend\Api\BiddingStrategyConfiguration'

Basically it can run the new Campaign() but it falls on the class dependencies.
This probably has to do with how my project is set up, but I am running it circles at the moment.
Eventually I want to make use of the TargetingIdeasService

Hope to hear from you.
Thanks

InvalidArgumentException

Could not find package nikolajlovenhardt/laravel-google-ads at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

two different errors

Hi sr, thanks for your library.

im getting two different erros, first error was
error2

and then i thought maybe i needed to add the Lumen part of your readme, then after following those steps i got:

error3

i must be doing something wrong, im new to laravel and this api so im a little confuse.

i have set your code as a function inside a controller, like this:

http://pastebin.com/HDXkkZs7

but maybe im doing it wrong, i saw you have a class Service with this code but i actually don't understand what to do with that class, this is why i set a controller and then call it from a route (domain.com/controllerfunction) with your code.

config_path() not found

I'm on Lumen 5.2 trying to get your 0.0.6 beta working. It looks like you're trying to use a helper function that's not available. The error is as below:

PHP Fatal error: Call to undefined function LaravelGoogleAds\config_path() in /Users/ibreakshit/PhpstormProjects/sgworker/vendor/nikolajlovenhardt/laravel-google-ads/src/LaravelGoogleAds/LaravelGoogleAdsProvider.php on line 15

I'm sure I can find a way to work around this for now but you might want to fix this.

[SoapFault] Unmarshalling Error: cvc-elt.4.3: Type 'ns1:AdGroupLabelOperation' is not validly derived from the type definition, 'AdGroupOperation', of element 'ns1:operations'

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
{
/**
* The name and signature of the console 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();

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Create or update Blauwpro product ads';

/**
 * Create a new command instance.
 *
 * @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();
  
}

/**
 * Execute the console command.
 *
 * @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->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;
}

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) ){
		
	    $campaign = $campaign['campaign'];
	    $campaign->setStatus(CampaignStatus::REMOVED);
		
	    // Campaign can be removed
	    $operation = new CampaignOperation();
	    $operation->setOperand($campaign);
	    $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 '.$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();

  $operations = array();  
  foreach($this->adGroupCollection as $adGroup){	  
	if( !in_array($adGroup['id'],$this->currentAdGroups) && in_array($adGroup['adGroup']->getCampaignId(),$this->currentCampaigns) ){
		
	    $adGroup = $adGroup['adGroup'];
	    $adGroup->setStatus(AdGroupStatus::REMOVED);
		
	    // Campaign can be removed
	    $operation = new AdGroupOperation();
	    $operation->setOperand($adGroup);
	    $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->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');
  }	  
  
}

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) ){
			    
	    $ad = new \Google\AdsApi\AdWords\v201609\cm\Ad();
	    $ad->setId($adGroupAd['id']);
	    
	    $adGroupId = $adGroupAd['adGroupId'];
	    
	    $adGroupAd = new AdGroupAd();
	    $adGroupAd->setAdGroupId($adGroupId);
	    $adGroupAd->setAd($ad);
		
	    // Campaign can be removed
	    $operation = new AdGroupAdOperation();
	    $operation->setOperand($adGroupAd);
	    $operation->setOperator(Operator::REMOVE);
	    $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->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');
  }	  
  
}

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) ){
		
	    $criterionId = $keyword['id'];
	    $adGroupId = $keyword['adGroupId'];
	    $keyword = $keyword['keyword'];
	    
	    $criterion = new Criterion();
	    $criterion->setId($criterionId);
	    
	    $adGroupCriterion = new AdGroupCriterion();
	    $adGroupCriterion->setAdGroupId($adGroupId);
	    $adGroupCriterion->setCriterion($criterion);
	    			
	    // Keyword can be removed
	    $operation = new AdGroupCriterionOperation();
	    $operation->setOperand($adGroupCriterion);
	    $operation->setOperator(Operator::REMOVE);
	    $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->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...');

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){
    
    $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(){

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

}
`

image

Any plans to upgrade to Laravel 5.3 ?

I am receiving error while using this package.

[InvalidArgumentException]
Could not find package nikolajlovenhardt/laravel-google-ads at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.