├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── phpunit.xml └── src ├── AdWords.php ├── AdWordsFacade.php ├── AdWordsService.php ├── AdWordsServiceFactory.php ├── AdWordsServiceProvider.php ├── Commands └── GenerateRefreshTokenCommand.php ├── Exceptions └── InvalidConfiguration.php ├── ExponentialBackoff.php ├── Responses ├── Keyword.php └── MonthlySearchVolume.php └── config └── adwords-targeting-idea-service.php /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All Notable changes to `Laravel AdWords Targeting Idea Service` will be documented in this file. 4 | ## [1.9.0] - 2022-03-20 5 | - Add Compatibility With Laravel 9 6 | - Drop support for Laravel 8 7 | - Minimum PHP 8.0.2 8 | - Using version 56.0 of googleads/googleads-php-lib 9 | - reduce laravel dependencies to specific packages (console,support) 10 | 11 | 12 | ## [1.8.0] - 2021-04-11 13 | - Add Compatibility With PHP 8.0 14 | - Using version 52.0 of googleads/googleads-php-lib 15 | - Throw Exceptions for API errors with Code 0 16 | 17 | ## [1.7.0] - 2020-10-27 18 | - Add Compatibility With Laravel 8 19 | - Drop support for Laravel 7 20 | - Minimum PHP 7.4 21 | - Using version 49.0 of googleads/googleads-php-lib 22 | 23 | ## [1.6.0] - 2020-04-12 24 | - Add Compatibility With Laravel 7 25 | - Drop support for Laravel 6 26 | - Minimum PHP 7.2.5 27 | 28 | ## [1.5.0] - 2019-09-15 29 | - add support for Laravel 6 30 | 31 | ## [1.4.1] - 2019-03-10 32 | - fix dependencies for carbon v2 33 | 34 | ## [1.4.0] - 2019-02-27 35 | - drop support for Laravel 5.7 and lower 36 | - drop support for PHP 7.1 and lower 37 | 38 | ## [1.3.4] - 2019-02-27 39 | - Add compatibility with Laravel 5.8 40 | - Using version 40.0 of googleads/googleads-php-lib 41 | - Implemented Exponential Backoff for RateExceededError 42 | 43 | ## [1.3.3] - 2018-10-30 44 | - Using version 37.1.0 of googleads/googleads-php-lib 45 | - Add compatibility with Laravel 5.7 46 | - Using v201809 of AdsApi 47 | 48 | ## [1.3.2] - 2018-03-04 49 | - Using version 33.1.0 of googleads/googleads-php-lib 50 | - Using v201802 of AdsApi 51 | - Add compatibility with Laravel 5.6 52 | 53 | ## [1.3.1] - 2018-01-29 54 | - Using version 32.1.0 of googleads/googleads-php-lib 55 | - Using v201710 of AdsApi 56 | 57 | ## [1.3.0] - 2017-12-27 58 | - Using version 32.0.0 of googleads/googleads-php-lib 59 | - Require Laravel 5.5 60 | - Removed unused files 61 | - Updated Readme 62 | 63 | 64 | ## [1.2.0] - 2017-07-25 65 | ### Added 66 | - Fluent method to convert null values to 0 or empty collection 67 | ### Changed 68 | - Using version 28.0.0 of googleads/googleads-php-lib 69 | 70 | ## [1.1.0] - 2017-06-20 71 | ### Added 72 | - Configurable SoapLogger 73 | - Console Command For Generating Refresh Token 74 | - Auto Discovery For L5.5 75 | 76 | ## [1.0.0] - 2017-06-06 77 | - Initial Release 78 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 46 | 47 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. 48 | 49 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 50 | 51 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 52 | 53 | **Happy coding**! -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Felix Schulze 4 | 5 | > Permission is hereby granted, free of charge, to any person obtaining a copy 6 | > of this software and associated documentation files (the "Software"), to deal 7 | > in the Software without restriction, including without limitation the rights 8 | > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | > copies of the Software, and to permit persons to whom the Software is 10 | > furnished to do so, subject to the following conditions: 11 | > 12 | > The above copyright notice and this permission notice shall be included in 13 | > all copies or substantial portions of the Software. 14 | > 15 | > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | > THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A Laravel API Wrapper For Google AdWords. 2 | 3 | [![Latest Version](https://img.shields.io/github/release/schulzefelix/laravel-adwords-targeting-idea-service.svg?style=flat-square)](https://github.com/schulzefelix/laravel-adwords/releases) 4 | [![Software License][ico-license]](LICENSE.md) 5 | [![Build Status][ico-travis]][link-travis] 6 | [![Quality Score][ico-code-quality]][link-code-quality] 7 | [![StyleCI](https://styleci.io/repos/92534151/shield)](https://styleci.io/repos/92534151) 8 | [![Latest Version on Packagist][ico-version]][link-packagist] 9 | [![Total Downloads][ico-downloads]][link-downloads] 10 | 11 | 12 | ## Install 13 | 14 | This package can be installed through Composer. 15 | 16 | ``` bash 17 | $ composer require schulzefelix/laravel-adwords-targeting-idea-service 18 | ``` 19 | 20 | The package will autoregister the service provider. If package discovery is disabled add the following. 21 | 22 | ```php 23 | // config/app.php 24 | 'providers' => [ 25 | ... 26 | SchulzeFelix\AdWords\AdWordsServiceProvider::class, 27 | ... 28 | ]; 29 | ``` 30 | 31 | The package will autoregister the facade. If package discovery is disabled add the following. 32 | 33 | ```php 34 | // config/app.php 35 | 'aliases' => [ 36 | ... 37 | 'AdWords' => SchulzeFelix\AdWords\AdWordsFacade::class, 38 | ... 39 | ]; 40 | ``` 41 | 42 | 43 | You can publish the config file of this package with this command: 44 | 45 | ``` bash 46 | php artisan vendor:publish --provider="SchulzeFelix\AdWords\AdWordsServiceProvider" 47 | ``` 48 | 49 | ### Generate Refresh Token 50 | This requires that the `clientId` and `clientSecret` are from a **native application**. 51 | 52 | Google Console: [https://console.developers.google.com/apis/credentials](https://console.developers.google.com/apis/credentials) 53 | 54 | ``` bash 55 | $ php artisan adwords:token 56 | ``` 57 | Open the authorization url. Grant access to the app and input the 58 | access token in the console. Copy the refresh token into your configuration `config/adwords-targeting-idea-service.php` 59 | 60 | ## Usage 61 | All methods will return an `Illuminate\Support\Collection`-instance. 62 | 63 | Here are two basic example to retrieve search volumes for several keywords and new keyword ideas for a given word. 64 | ### Search Volumes 65 | 66 | ```php 67 | $searchVolumes = AdWords::searchVolumes(['cheesecake', 'coffee']); 68 | ``` 69 | 70 | ### Keyword Ideas 71 | 72 | ```php 73 | $keywordIdeas = AdWords::keywordIdeas('coffee'); 74 | ``` 75 | 76 | ## Provided fluent configuration 77 | 78 | ### Set Location 79 | For Criteria ID see [https://developers.google.com/adwords/api/docs/appendix/geotargeting](https://developers.google.com/adwords/api/docs/appendix/geotargeting) 80 | ```php 81 | AdWords::location(2276)->searchVolumes(['cheesecake', 'coffee']); 82 | ``` 83 | 84 | ### Set Language 85 | For Criteria ID see [https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages](https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages) 86 | ```php 87 | AdWords::location(2276)->language(1001)->searchVolumes(['cheesecake', 'coffee']); 88 | ``` 89 | 90 | ### Include Targeted Monthly Searches 91 | ```php 92 | AdWords::withTargetedMonthlySearches()->searchVolumes(['cheesecake', 'coffee']); 93 | ``` 94 | 95 | ### Convert NULL values to Zero 96 | ```php 97 | AdWords::convertNullToZero()->location(2276)->language(1001)->searchVolumes(['cheesecake', 'coffee']); 98 | ``` 99 | 100 | ### Include And Exclude Words For Keyword Ideas 101 | ```php 102 | AdWords::location(2642)->exclude(['iphone'])->include(['apple'])->keywordIdeas('iphone'); 103 | ``` 104 | 105 | 106 | 107 | ## Change log 108 | 109 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 110 | 111 | ## Testing 112 | 113 | ``` bash 114 | $ vendor/bin/phpunit 115 | ``` 116 | 117 | ## Contributing 118 | 119 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 120 | 121 | ## Security 122 | 123 | If you discover any security related issues, please email github@schulze.co instead of using the issue tracker. 124 | 125 | ## Credits 126 | 127 | - [Felix Schulze][link-author] 128 | - [All Contributors][link-contributors] 129 | 130 | ## License 131 | 132 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 133 | 134 | [ico-version]: https://img.shields.io/packagist/v/schulzefelix/laravel-adwords-targeting-idea-service.svg?style=flat-square 135 | [ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square 136 | [ico-travis]: https://img.shields.io/travis/schulzefelix/laravel-adwords-targeting-idea-service/master.svg?style=flat-square 137 | [ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/schulzefelix/laravel-adwords-targeting-idea-service.svg?style=flat-square 138 | [ico-code-quality]: https://scrutinizer-ci.com/g/schulzefelix/laravel-adwords-targeting-idea-service/badges/quality-score.png?b=master 139 | [ico-downloads]: https://img.shields.io/packagist/dt/schulzefelix/laravel-adwords-targeting-idea-service.svg?style=flat-square 140 | 141 | [link-packagist]: https://packagist.org/packages/schulzefelix/laravel-adwords-targeting-idea-service 142 | [link-travis]: https://travis-ci.org/schulzefelix/laravel-adwords-targeting-idea-service 143 | [link-scrutinizer]: https://scrutinizer-ci.com/g/schulzefelix/laravel-adwords-targeting-idea-service/code-structure 144 | [link-code-quality]: https://scrutinizer-ci.com/g/schulzefelix/laravel-adwords-targeting-idea-service 145 | [link-downloads]: https://packagist.org/packages/schulzefelix/laravel-adwords-targeting-idea-service 146 | [link-author]: https://github.com/schulzefelix 147 | [link-contributors]: ../../contributors 148 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "schulzefelix/laravel-adwords-targeting-idea-service", 3 | "description": "Laravel wrapper for the AdWords Targeting Idea Service", 4 | "keywords": [ 5 | "SchulzeFelix", 6 | "Laravel AdWords", 7 | "AdWords", 8 | "Laravel", 9 | "Targeting Idea Service" 10 | ], 11 | "homepage": "https://github.com/schulzefelix/laravel-adwords-targeting-idea-service", 12 | "license": "MIT", 13 | "authors": [ 14 | { 15 | "name": "Felix Schulze", 16 | "email": "github@schulze.co", 17 | "homepage": "https://schulze.co", 18 | "role": "Developer" 19 | } 20 | ], 21 | "require": { 22 | "php": "^8.0.2", 23 | "illuminate/console": "^9.0", 24 | "illuminate/support": "^9.0", 25 | "googleads/googleads-php-lib": "^56.0", 26 | "schulzefelix/laravel-data-transfer-object": "^1.5.0" 27 | }, 28 | "require-dev": { 29 | "mockery/mockery": "^1.4", 30 | "orchestra/testbench": "^7.0", 31 | "phpunit/phpunit": "^9.4" 32 | }, 33 | "autoload": { 34 | "psr-4": { 35 | "SchulzeFelix\\AdWords\\": "src" 36 | } 37 | }, 38 | "autoload-dev": { 39 | "psr-4": { 40 | "SchulzeFelix\\AdWords\\Tests\\": "tests" 41 | } 42 | }, 43 | "config": { 44 | "sort-packages": true 45 | }, 46 | "extra": { 47 | "laravel": { 48 | "providers": [ 49 | "SchulzeFelix\\AdWords\\AdWordsServiceProvider" 50 | ], 51 | "aliases": { 52 | "AdWords": "SchulzeFelix\\AdWords\\AdWordsFacade" 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | tests 15 | 16 | 17 | 18 | 19 | src/ 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/AdWords.php: -------------------------------------------------------------------------------- 1 | service = $service; 48 | } 49 | 50 | /** 51 | * @param array $keywords 52 | * 53 | * @return Collection 54 | */ 55 | public function searchVolumes(array $keywords) 56 | { 57 | $keywords = $this->prepareKeywords($keywords); 58 | $requestType = RequestType::STATS; 59 | 60 | $searchVolumes = new Collection(); 61 | $chunks = array_chunk($keywords, self::CHUNK_SIZE); 62 | 63 | foreach ($chunks as $index => $keywordChunk) { 64 | $results = $this->service->performQuery($keywordChunk, $requestType, $this->language, $this->location, $this->withTargetedMonthlySearches); 65 | if ($results->getEntries() !== null) { 66 | foreach ($results->getEntries() as $targetingIdea) { 67 | $keyword = $this->extractKeyword($targetingIdea); 68 | $searchVolumes->push($keyword); 69 | } 70 | } 71 | } 72 | 73 | $missingKeywords = array_diff($keywords, $searchVolumes->pluck('keyword')->toArray()); 74 | 75 | foreach ($missingKeywords as $missingKeyword) { 76 | $missingKeywordInstance = new Keyword([ 77 | 'keyword' => $missingKeyword, 78 | 'search_volume' => $this->convertNullToZero ? 0 : null, 79 | 'cpc' => $this->convertNullToZero ? 0 : null, 80 | 'competition' => $this->convertNullToZero ? 0 : null, 81 | ]); 82 | 83 | if ($this->withTargetedMonthlySearches) { 84 | $missingKeywordInstance->targeted_monthly_searches = $this->convertNullToZero ? collect() : null; 85 | } 86 | 87 | $searchVolumes->push($missingKeywordInstance); 88 | } 89 | 90 | return $searchVolumes; 91 | } 92 | 93 | public function keywordIdeas($keyword) 94 | { 95 | $keyword = $this->prepareKeywords([$keyword]); 96 | $requestType = RequestType::IDEAS; 97 | 98 | $keywordIdeas = new Collection(); 99 | 100 | $results = $this->service->performQuery($keyword, $requestType, $this->language, $this->location, $this->withTargetedMonthlySearches, $this->include, $this->exclude); 101 | if ($results->getEntries() !== null) { 102 | foreach ($results->getEntries() as $targetingIdea) { 103 | $keyword = $this->extractKeyword($targetingIdea); 104 | $keywordIdeas->push($keyword); 105 | } 106 | } 107 | 108 | return $keywordIdeas; 109 | } 110 | 111 | /** 112 | * Include Targeted Monthly Searches. 113 | * 114 | * @return $this 115 | */ 116 | public function withTargetedMonthlySearches() 117 | { 118 | $this->withTargetedMonthlySearches = true; 119 | 120 | return $this; 121 | } 122 | 123 | /** 124 | * Convert Null Values To Zero. 125 | * 126 | * @return $this 127 | */ 128 | public function convertNullToZero() 129 | { 130 | $this->convertNullToZero = true; 131 | 132 | return $this; 133 | } 134 | 135 | /** 136 | * Add Language Search Parameter. 137 | * 138 | * @return $this 139 | */ 140 | public function language($language = null) 141 | { 142 | $this->language = $language; 143 | 144 | return $this; 145 | } 146 | 147 | /** 148 | * Add Location Search Parameter. 149 | * 150 | * @return $this 151 | */ 152 | public function location($location = null) 153 | { 154 | $this->location = $location; 155 | 156 | return $this; 157 | } 158 | 159 | public function include(array $words) 160 | { 161 | $this->include = $this->prepareKeywords($words); 162 | 163 | return $this; 164 | } 165 | 166 | public function exclude(array $words) 167 | { 168 | $this->exclude = $this->prepareKeywords($words); 169 | 170 | return $this; 171 | } 172 | 173 | /** 174 | * @return TargetingIdeaService 175 | */ 176 | public function getTargetingIdeaService(): TargetingIdeaService 177 | { 178 | return $this->service->getTargetingIdeaService(); 179 | } 180 | 181 | /** 182 | * Private Functions. 183 | */ 184 | private function prepareKeywords(array $keywords) 185 | { 186 | $keywords = array_map('trim', $keywords); 187 | $keywords = array_map('mb_strtolower', $keywords); 188 | $keywords = array_filter($keywords); 189 | $keywords = array_unique($keywords); 190 | $keywords = array_values($keywords); 191 | 192 | return $keywords; 193 | } 194 | 195 | /** 196 | * @param $targetingIdea 197 | * 198 | * @return Keyword 199 | */ 200 | private function extractKeyword($targetingIdea) 201 | { 202 | $data = MapEntries::toAssociativeArray($targetingIdea->getData()); 203 | $keyword = $data[AttributeType::KEYWORD_TEXT]->getValue(); 204 | $search_volume = 205 | ($data[AttributeType::SEARCH_VOLUME]->getValue() !== null) 206 | ? $data[AttributeType::SEARCH_VOLUME]->getValue() : 0; 207 | 208 | $average_cpc = 209 | ($data[AttributeType::AVERAGE_CPC]->getValue() !== null) 210 | ? $data[AttributeType::AVERAGE_CPC]->getValue()->getMicroAmount() : 0; 211 | $competition = 212 | ($data[AttributeType::COMPETITION]->getValue() !== null) 213 | ? $data[AttributeType::COMPETITION]->getValue() : 0; 214 | 215 | $result = new Keyword([ 216 | 'keyword' => $keyword, 217 | 'search_volume' => $search_volume, 218 | 'cpc' => $average_cpc, 219 | 'competition' => $competition, 220 | 'targeted_monthly_searches' => null, 221 | ]); 222 | 223 | if ($this->withTargetedMonthlySearches) { 224 | $targeted_monthly_searches = 225 | ($data[AttributeType::TARGETED_MONTHLY_SEARCHES]->getValue() !== null) 226 | ? $data[AttributeType::TARGETED_MONTHLY_SEARCHES]->getValue() : 0; 227 | $targetedMonthlySearches = collect($targeted_monthly_searches) 228 | ->transform(function ($item, $key) { 229 | return new MonthlySearchVolume([ 230 | 'year' => $item->getYear(), 231 | 'month' => $item->getMonth(), 232 | 'count' => $item->getCount(), 233 | ]); 234 | }); 235 | 236 | $result->targeted_monthly_searches = $targetedMonthlySearches; 237 | } 238 | 239 | return $result; 240 | } 241 | } 242 | -------------------------------------------------------------------------------- /src/AdWordsFacade.php: -------------------------------------------------------------------------------- 1 | targetingIdeaService = $targetingIdeaService; 32 | } 33 | 34 | /** 35 | * Query the Google AdWords TargetingIdeaService with given parameters. 36 | * 37 | * @param array $keywords 38 | * @param $requestType 39 | * @param $language 40 | * @param $location 41 | * @param bool $withTargetedMonthlySearches 42 | * @param $included 43 | * @param $excluded 44 | * 45 | * @throws ApiException 46 | * 47 | * @return \Google\AdsApi\AdWords\v201809\o\TargetingIdeaPage 48 | */ 49 | public function performQuery(array $keywords, $requestType, $language = null, $location = null, $withTargetedMonthlySearches = false, $included = null, $excluded = null) 50 | { 51 | 52 | // Create selector. 53 | $selector = new TargetingIdeaSelector(); 54 | $selector->setRequestType($requestType); 55 | $selector->setIdeaType(IdeaType::KEYWORD); 56 | $selector->setRequestedAttributeTypes($this->getRequestedAttributeTypes($withTargetedMonthlySearches)); 57 | $selector->setPaging(new Paging(0, self::PAGE_LIMIT)); 58 | $selector->setSearchParameters($this->getSearchParameters($keywords, $language, $location, $included, $excluded)); 59 | 60 | return (new ExponentialBackoff(10))->execute(function () use ($selector) { 61 | return $this->targetingIdeaService->get($selector); 62 | }); 63 | } 64 | 65 | /** 66 | * @return TargetingIdeaService 67 | */ 68 | public function getTargetingIdeaService() 69 | { 70 | return $this->targetingIdeaService; 71 | } 72 | 73 | /** 74 | * @param bool $withTargetedMonthlySearches 75 | * 76 | * @return array 77 | */ 78 | private function getRequestedAttributeTypes($withTargetedMonthlySearches = false) 79 | { 80 | if ($withTargetedMonthlySearches) { 81 | return [ 82 | AttributeType::KEYWORD_TEXT, 83 | AttributeType::SEARCH_VOLUME, 84 | AttributeType::COMPETITION, 85 | AttributeType::AVERAGE_CPC, 86 | AttributeType::TARGETED_MONTHLY_SEARCHES, 87 | ]; 88 | } 89 | 90 | return [ 91 | AttributeType::KEYWORD_TEXT, 92 | AttributeType::SEARCH_VOLUME, 93 | AttributeType::COMPETITION, 94 | AttributeType::AVERAGE_CPC, 95 | ]; 96 | } 97 | 98 | /** 99 | * @param array $keywords 100 | * @param $languageId 101 | * @param $locationId 102 | * @param $included 103 | * @param $excluded 104 | * 105 | * @return array 106 | */ 107 | private function getSearchParameters(array $keywords, $languageId, $locationId, $included, $excluded) 108 | { 109 | $searchParameters = []; 110 | 111 | //Create Language Parameter 112 | if (! is_null($languageId)) { 113 | $languageParameter = new LanguageSearchParameter(); 114 | $language = new Language(); 115 | $language->setId($languageId); 116 | $languageParameter->setLanguages([$language]); 117 | $searchParameters[] = $languageParameter; 118 | } 119 | 120 | //Create Location Parameter 121 | if (! is_null($locationId)) { 122 | $locationParameter = new LocationSearchParameter(); 123 | $location = new Location(); 124 | $location->setId($locationId); 125 | $locationParameter->setLocations([$location]); 126 | $searchParameters[] = $locationParameter; 127 | } 128 | 129 | //Network Settings 130 | $networkSetting = new NetworkSetting(); 131 | $networkSetting->setTargetGoogleSearch(true); 132 | $networkSetting->setTargetSearchNetwork(false); 133 | $networkSetting->setTargetContentNetwork(false); 134 | $networkSetting->setTargetPartnerSearchNetwork(false); 135 | 136 | $networkSearchParameter = new NetworkSearchParameter(); 137 | $networkSearchParameter->setNetworkSetting($networkSetting); 138 | $searchParameters[] = $networkSearchParameter; 139 | 140 | // Create related to query search parameter. 141 | $relatedToQuerySearchParameter = new RelatedToQuerySearchParameter(); 142 | $relatedToQuerySearchParameter->setQueries($keywords); 143 | $searchParameters[] = $relatedToQuerySearchParameter; 144 | 145 | if (! is_null($included) || ! is_null($excluded)) { 146 | $ideaTextFilterSearchParameter = new IdeaTextFilterSearchParameter(); 147 | if (! is_null($included)) { 148 | $ideaTextFilterSearchParameter->setIncluded($included); 149 | } 150 | if (! is_null($excluded)) { 151 | $ideaTextFilterSearchParameter->setExcluded($excluded); 152 | } 153 | $searchParameters[] = $ideaTextFilterSearchParameter; 154 | } 155 | 156 | return $searchParameters; 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /src/AdWordsServiceFactory.php: -------------------------------------------------------------------------------- 1 | get($session, TargetingIdeaService::class); 23 | 24 | return self::createTargetingIdeaService($targetingIdeaService); 25 | } 26 | 27 | /** 28 | * @param array $config 29 | * 30 | * @return AdWordsSession 31 | * 32 | * Generate a refreshable OAuth2 credential for authentication. 33 | * Construct an API session 34 | */ 35 | protected static function createAuthenticatedAdWordsSessionBuilder(array $config): AdWordsSession 36 | { 37 | $oAuth2Credential = (new OAuth2TokenBuilder()) 38 | ->withClientId($config['client_id']) 39 | ->withClientSecret($config['client_secret']) 40 | ->withRefreshToken($config['client_refresh_token']) 41 | ->build(); 42 | 43 | $soapLogger = (new AdsLoggerFactory()) 44 | ->createLogger( 45 | self::$DEFAULT_SOAP_LOGGER_CHANNEL, 46 | Arr::get($config, 'soap_log_file_path', null), 47 | Arr::get($config, 'soap_log_level', 'ERROR') 48 | ); 49 | 50 | $session = (new AdWordsSessionBuilder()) 51 | ->withOAuth2Credential($oAuth2Credential) 52 | ->withDeveloperToken($config['developer_token']) 53 | ->withUserAgent($config['user_agent']) 54 | ->withClientCustomerId($config['client_customer_id']) 55 | ->withSoapLogger($soapLogger) 56 | ->build(); 57 | 58 | return $session; 59 | } 60 | 61 | protected static function createTargetingIdeaService(TargetingIdeaService $targetingIdeaService): AdWordsService 62 | { 63 | return new AdWordsService($targetingIdeaService); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/AdWordsServiceProvider.php: -------------------------------------------------------------------------------- 1 | publishes([ 19 | __DIR__.'/config/adwords-targeting-idea-service.php' => config_path('adwords-targeting-idea-service.php'), 20 | ]); 21 | } 22 | 23 | /** 24 | * Register the service provider. 25 | */ 26 | public function register() 27 | { 28 | $this->mergeConfigFrom(__DIR__.'/config/adwords-targeting-idea-service.php', 'adwords-targeting-idea-service'); 29 | 30 | $adwordsConfig = config('adwords-targeting-idea-service'); 31 | 32 | $this->app->bind('command.adwords:token', GenerateRefreshTokenCommand::class); 33 | $this->commands([ 34 | 'command.adwords:token', 35 | ]); 36 | 37 | $this->app->bind(AdWordsService::class, function () use ($adwordsConfig) { 38 | return AdWordsServiceFactory::createForConfig($adwordsConfig); 39 | }); 40 | 41 | $this->app->bind(AdWords::class, function () use ($adwordsConfig) { 42 | $this->guardAgainstInvalidConfiguration($adwordsConfig); 43 | 44 | $adWordsService = app(AdWordsService::class); 45 | 46 | return new AdWords($adWordsService); 47 | }); 48 | 49 | $this->app->alias(AdWords::class, 'laravel-adwords-targeting-idea-service'); 50 | } 51 | 52 | protected function guardAgainstInvalidConfiguration(array $adwordsConfig = null) 53 | { 54 | if (empty($adwordsConfig['developer_token'])) { 55 | throw InvalidConfiguration::developerTokenNotSpecified(); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Commands/GenerateRefreshTokenCommand.php: -------------------------------------------------------------------------------- 1 | config()) { 43 | $this->error('Please provide a valid configuration.'); 44 | 45 | return false; 46 | } 47 | 48 | $clientId = $config['client_id']; 49 | $clientSecret = $config['client_secret']; 50 | $scopes = self::ADWORDS_API_SCOPE; 51 | 52 | $oauth2 = new OAuth2([ 53 | 'authorizationUri' => self::AUTHORIZATION_URI, 54 | 'redirectUri' => self::REDIRECT_URI, 55 | 'tokenCredentialUri' => CredentialsLoader::TOKEN_CREDENTIAL_URI, 56 | 'clientId' => $clientId, 57 | 'clientSecret' => $clientSecret, 58 | 'scope' => $scopes, 59 | ]); 60 | 61 | $this->info("Please sign in to your AdWords account, and open following url:\n"); 62 | $this->line(sprintf( 63 | '%s', 64 | $oauth2->buildFullAuthorizationUri([ 65 | 'access_type' => 'offline', 66 | ]) 67 | )); 68 | 69 | $accessToken = $this->ask('Insert your access token'); 70 | 71 | try { 72 | $oauth2->setCode($accessToken); 73 | $authToken = $oauth2->fetchAuthToken(); 74 | } catch (Exception $exception) { 75 | $this->error($exception->getMessage()); 76 | 77 | return false; 78 | } 79 | 80 | if (! isset($authToken)) { 81 | $this->error('Error fetching the refresh token'); 82 | 83 | return false; 84 | } 85 | 86 | $this->comment('Insert the refresh token in your adwords configuration file (config/adwords-targeting-idea-service.php)'); 87 | 88 | $this->info(sprintf( 89 | 'Refresh token: "%s"', 90 | $authToken['refresh_token'] 91 | )); 92 | } 93 | 94 | /** 95 | * Configuration. 96 | * 97 | * @return bool|array 98 | */ 99 | private function config() 100 | { 101 | /** @var null|array $config */ 102 | $config = config('adwords-targeting-idea-service'); 103 | if (is_null($config) || ! count($config)) { 104 | return false; 105 | } 106 | 107 | return $config; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/Exceptions/InvalidConfiguration.php: -------------------------------------------------------------------------------- 1 | retries = $retries !== null ? (int) $retries : 3; 34 | $this->retryFunction = $retryFunction; 35 | $this->delayFunction = function ($delay) { 36 | usleep($delay); 37 | }; 38 | } 39 | 40 | /** 41 | * Executes the retry process. 42 | * 43 | * @param callable $function 44 | * @param array $arguments [optional] 45 | * @return mixed 46 | * @throws \Exception The last exception caught while retrying. 47 | */ 48 | public function execute(callable $function, array $arguments = []) 49 | { 50 | $delayFunction = $this->delayFunction; 51 | $retryAttempt = 0; 52 | $exception = null; 53 | 54 | while (true) { 55 | try { 56 | return call_user_func_array($function, $arguments); 57 | } catch (\Exception $exception) { 58 | if ($this->retryFunction) { 59 | if (! call_user_func($this->retryFunction, $exception)) { 60 | throw $exception; 61 | } 62 | } 63 | 64 | if (in_array($exception->getCode(), [0, 400, 403])) { 65 | break; 66 | } 67 | 68 | 69 | if ($retryAttempt >= $this->retries) { 70 | break; 71 | } 72 | 73 | $delayFunction($this->calculateDelay($retryAttempt)); 74 | $retryAttempt++; 75 | } 76 | } 77 | 78 | throw $exception; 79 | } 80 | 81 | /** 82 | * @param callable $delayFunction 83 | * @return void 84 | */ 85 | public function setDelayFunction(callable $delayFunction) 86 | { 87 | $this->delayFunction = $delayFunction; 88 | } 89 | 90 | /** 91 | * Calculates exponential delay. 92 | * 93 | * @param int $attempt 94 | * @return int 95 | */ 96 | private function calculateDelay($attempt) 97 | { 98 | return min( 99 | mt_rand(0, 1000000) + (pow(2, $attempt) * 1000000), 100 | self::MAX_DELAY_MICROSECONDS 101 | ); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/Responses/Keyword.php: -------------------------------------------------------------------------------- 1 | 'string', 11 | 'search_volume' => 'integer', 12 | 'cpc' => 'float', 13 | 'competition' => 'float', 14 | 'targeted_monthly_searches' => 'collection', 15 | ]; 16 | } 17 | -------------------------------------------------------------------------------- /src/Responses/MonthlySearchVolume.php: -------------------------------------------------------------------------------- 1 | 'integer', 11 | 'month' => 'integer', 12 | 'count' => 'integer', 13 | ]; 14 | } 15 | -------------------------------------------------------------------------------- /src/config/adwords-targeting-idea-service.php: -------------------------------------------------------------------------------- 1 | env('ADWORDS_DEVELOPER_TOKEN'), 11 | 12 | /* 13 | |-------------------------------------------------------------------------- 14 | | OAUTH2 Credentials 15 | |-------------------------------------------------------------------------- 16 | */ 17 | 18 | 'client_id' => env('ADWORDS_CLIENT_ID'), 19 | 'client_secret' => env('ADWORDS_CLIENT_SECRET'), 20 | 'client_refresh_token' => env('ADWORDS_CLIENT_REFRESH_TOKEN'), 21 | 22 | /* 23 | |-------------------------------------------------------------------------- 24 | | Client Customer ID 25 | |-------------------------------------------------------------------------- 26 | */ 27 | 28 | 'client_customer_id' => env('ADWORDS_CLIENT_CUSTOMER_ID'), 29 | 30 | /* 31 | |-------------------------------------------------------------------------- 32 | | User Agent 33 | |-------------------------------------------------------------------------- 34 | */ 35 | 36 | 'user_agent' => env('ADWORDS_USER_AGENT', ''), 37 | 38 | /* 39 | |-------------------------------------------------------------------------- 40 | | Logging - Path 41 | |-------------------------------------------------------------------------- 42 | | 43 | | Supported: 44 | | 45 | | null (Console Output stderr) 46 | | storage_path('logs/soap.log') 47 | | 48 | */ 49 | 50 | 'soap_log_file_path' => null, 51 | 52 | /* 53 | |-------------------------------------------------------------------------- 54 | | Logging - Level 55 | |-------------------------------------------------------------------------- 56 | | 57 | | http://www.php-fig.org/psr/psr-3/#psrlogloglevel 58 | | Default: ERROR 59 | | 60 | */ 61 | 62 | 'soap_log_level' => env('ADWORDS_SOAP_LOG_LEVEL', 'ERROR'), 63 | ]; 64 | --------------------------------------------------------------------------------