PHP code example of adprolabs / easy-adwords

1. Go to this page and download the library: Download adprolabs/easy-adwords library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

adprolabs / easy-adwords example snippets


$config = new ReportConfig([
    "adwordsConfigPath" => 'my_adwords_config_file_path',
    "clientCustomerId"  => 'my_client_customer_id',
    "refreshToken"      => 'my_oauth_refresh_token',
    "fields"            => ['Date', 'Clicks', 'Impressions'],
    "startDate"         => '2017-01-22',
    "endDate"           => '2017-01-25'
]);

// The report object is initialized.
$report = new AccountPerformanceReport($config);     

// Download the report and format it to a flat array.   
$report->download()->format();    

// Access the report property of the object.    
$report->getReport();

use EasyAdWords\AdWordsAuth\AdWordsAuth;
use Google\AdsApi\AdWords\v201609\mcm\CustomerService;

class MyAuth {

    public function __construct(){

        // Parameters for the authentication process.
        $authorizationURI = "https://accounts.google.com/o/oauth2/v2/auth";
        $redirectURI = "my_redirect_uri.com";
        $clientId = "my_client_id";
        $clientSecret = "my_client_secret";
        $scopes = ['https://www.googleapis.com/auth/adwords'];

        // Create oAuth config array.
        $config = [
            'authorizationUri' => $authorizationURI,
            'redirectUri' => $redirectURI,
            'tokenCredentialUri' => CredentialsLoader::TOKEN_CREDENTIAL_URI,
            'clientId' => $clientId,
            'clientSecret' => $clientSecret,
            'scope' => $scopes
        ];

        // Create an auth object.
        $this->authObject = new AdWordsAuth(NULL, 'my_adwords_config_file_path');
        
        // Get the oAuth object from the 
        $this->oauth2 = $this->authObject->buildOAuthObject($this->config);
    }

    // These two are explained below.
    public function redirectToGoogle();
    public function googleCallback();
}

public function redirectToGoogle(){
    
    // Set the state for the request.
    $this->oauth2->setState(sha1(openssl_random_pseudo_bytes(1024)));
    $_SESSION['oauth2state'] = $oauth2->getState();

    $accessConfig = ['access_type' => 'offline'];
    header('Location: ' . $oauth2->buildFullAuthorizationUri($accessConfig));
    exit;
}

public function googleCallback(){
    
    // Check the state of the callback request.
    if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])){
        unset($_SESSION['oauth2state']);
        exit('Invalid state.');
    } else {

        // Set the auth code and get the credentials.
        $this->oauth2->setCode($request->code);
        $credentials = $this->oauth2->fetchAuthToken();

        // Build the oAuth session for service usage.
        $this->authObject->setOAuthCredentials($this->oauth2);
        $this->authObject->buildSession();

        // Create the service and get the AdWords customers of the account.
        $customerService = $this->authObject->getAdWordsService(CustomerService::class);
        $customers = $customerService->getCustomers();
    }   
}

use EasyAdwords\Reports\ReportConfig;

$config = new ReportConfig([
    "adwordsConfigPath" => 'my_adwords_config_file_path',
    "clientCustomerId"  => 'my_client_customer_id',
    "refreshToken"      => 'my_oauth_refresh_token',
    "fields"            => ['Date', 'Clicks', 'Impressions'],
    "startDate"         => '2017-01-22',
    "endDate"           => '2017-01-25',
    "predicates"        => [new Predicate('Clicks', PredicateOperator::GREATER_THAN, [10])]
]);

use EasyAdWords\Reports\AccountPerformanceReport;

// The report object is initialized.
$report = new AccountPerformanceReport($config);     

// Download the report and store it as a CSV string.   
$report->download();    

// Format the report CSV into a flat array.    
$report->format();     

// Access the report property of the object.    
$report->getReport();    

use EasyAdWords\Reports\CustomReport;

$reportType =  ReportDefinitionReportType::URL_PERFORMANCE_REPORT;

// The custom report object is initialized.
$report = new CustomReport($config, $reportType);     

// Download the URL Performance Report and store it as a CSV string.   
$report->download();    

// Format the report CSV into a flat array.    
$report->format();     

// Access the report property of the object.    
$report->getReport();    

$accountList = $account->get(); 
print_r($accountList);

/* The result is as follows.
Array
(
    [0] => Google\AdsApi\AdWords\v201609\mcm\ManagedCustomer Object
        (
            [name:protected] => account_name
            [customerId:protected] => customer_id_of_account
            [canManageClients:protected] => 
            [currencyCode:protected] => currency_code_of_account
            [dateTimeZone:protected] => date_time_zone_of_account
            [testAccount:protected] => 
            [accountLabels:protected] => 
            [excludeHiddenAccounts:protected] => 
        )
)
*/

// The fields can be accessed by appropriate getters.
$accountList[0]->getName(); // account_name
$accountList[0]->getCustomerId(); // customer_id_of_account


use EasyAdWords\Accounts\AccountConfig;
use EasyAdWords\Accounts\Account;

$fields = array('CustomerId', 'Name', 'CanManageClients');

// Create the account configuration object.
$accountConfig = new AccountConfig([
    "adwordsConfigPath" => 'my_adwords_config_file_path',
    "clientCustomerId"  => 'my_client_customer_id',
    "refreshToken"      => 'my_oauth_refresh_token',
    "fields"            => $fields
]);

// Create the campaign object with the config object.
$account = new Account($accountConfig);

// Get the account list from  Google AdWords.
$account->get();

use Google\AdsApi\AdWords\v201609\cm\AdvertisingChannelType;
use Google\AdsApi\AdWords\v201609\cm\CampaignStatus;
use Google\AdsApi\AdWords\v201609\cm\BudgetBudgetDeliveryMethod;
use Google\AdsApi\AdWords\v201609\cm\BiddingStrategyType;
use Google\AdsApi\AdWords\v201609\cm\ServingStatus;
use EasyAdWords\Campaigns\CampaignConfig;
use EasyAdWords\Campaigns\Campaign;

// Create the campaign configuration object.
$config = new CampaignConfig([
    "adwordsConfigPath"     => 'my_adwords_config_file_path',
    "clientCustomerId"      => 'my_client_customer_id',
    "refreshToken"          => 'my_oauth_refresh_token',
    "startDate"             => '2017-06-22',
    "campaignName"          => "EasyAdWords_TestCampaign_".uniqid(),
    "budget"                => 100,
    "advertisingChannelType" => AdvertisingChannelType::SEARCH,
    "status"                => CampaignStatus::PAUSED,
    "biddingStrategyType"   => BiddingStrategyType::MANUAL_CPC,
    "budgetDeliveryMethod"  => BudgetBudgetDeliveryMethod::STANDARD,
    "servingStatus"         => ServingStatus::SERVING,
    "targetGoogleSearch"    => true,
    "targetSearchNetwork"   => true,
    "targetContentNetwork"  => true,
    "startDate"             => date('Ymd'),
]);

// Create a new campaign configuration with 'useDefaults' option.
$config = new CampaignConfig([
    "adwordsConfigPath"     => 'my_adwords_config_file_path',
    "clientCustomerId"      => 'my_client_customer_id',
    "refreshToken"          => 'my_oauth_refresh_token',
    "startDate"             => '2017-06-22',
    "campaignName"          => "EasyAdWords_TestCampaign_".uniqid(),
    "useDefaults"           => true
]);

// Create the campaign object with the config object.
$campaign = new Campaign($config);

// Create the campaign on Google AdWords.
$campaign->create();

// Get the result of the campaign creation.
$campaign->getOperationResult();


use EasyAdWords\AdGroups\AdGroup;
use EasyAdWords\AdGroups\AdGroupConfig;

// Create the ad group configuration object.
$config = new AdGroupConfig([
    "adwordsConfigPath" => 'my_adwords_config_file_path',
    "clientCustomerId"  => 'my_client_customer_id',
    "refreshToken"      => 'my_oauth_refresh_token',
    "campaignId"        => 'my_campaign_id',
    "adGroupName"       => 'EasyAdWords_AdGroup_TEST',
    "bid"               => 25
]);

// Create the ad group object with the config object.
$adGroup = new AdGroup($config);

// Create the ad group on Google AdWords.
$adGroup->create();

// Get the result of the ad group creation.
$adGroup->getOperationResult();


use EasyAdWords\Keywords\Keyword;
use EasyAdWords\Keywords\KeywordConfig

// Create the keyword configuration object.
$config = new KeywordConfig([
    "adwordsConfigPath" => 'my_adwords_config_file_path',
    "clientCustomerId"  => 'my_client_customer_id',
    "refreshToken"      => 'my_oauth_refresh_token',
    "adGroupId"         => 'my_ad_group_id',
    "keyword"           => 'space invaders',
    "matchType"         => KeywordMatchType::EXACT,
    "finalUrls"         => 'http://example.com',
    "bid"               => 25,
    "status"            => UserStatus::ENABLED
]);

// Create the keyword object with the config object.
$keyword = new Keyword($config);

// Create the keyword on Google AdWords.
$keyword->create();

// Get the result of the keyword creation.
$keyword->getOperationResult();



use EasyAdWords\Keywords\KeywordBatchConfig;
use EasyAdWords\Keywords\KeywordBatch;

// Keywords to add.
$keywords = ['quick brown fox','jumps over','the lazy dog'];

// Create the keyword batch configuration object.
$config = new KeywordBatchConfig([
        "adwordsConfigPath" => 'my_adwords_config_file_path',
        "clientCustomerId"  => 'my_client_customer_id',
        "refreshToken"      => 'my_oauth_refresh_token',
        "batchSize"         => 500
]);

// Create the keyword batch object with the config object.
$keywordBatch = new KeywordBatch($config);

// Loop over the keywords and append them to the batch object. 
foreach($keywords as $keyword) {
    $keywordConfig = new KeywordConfig([
        "adGroupId"         => 'my_ad_group_id',
        "keyword"           => $keyword,
        "matchType"         => KeywordMatchType::EXACT,
        "finalUrls"         => 'http://example.com',
        "bid"               => 25,
        "status"            => UserStatus::ENABLED
    ]);

    $keywordBatch->append($keywordConfig);
}

// Apply the new keywords to the Google AdWords.
$keywordBatch->mutate();