adprolabs / easy-adwords
一个包装库,用于轻松使用新的AdWords PHP客户端库。
Requires
- googleads/googleads-php-lib: 28.0.*
This package is not auto-updated.
Last update: 2023-04-15 12:01:42 UTC
README
EasyAdWords 是一个易于使用和可定制的库,它简化了当前 v25.3 PHP 客户端库的 AdWords API 的基本用法。它基本上允许通过 下载和解析 报告来实现更简单的 报告过程,还允许执行实体操作,如 获取、创建 和 删除 营销活动、广告组和关键词。
例如,可以轻松下载并格式化以下简单的代码片段 Account Performance Report
$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();
目录
安装
composer require adprolabs/easy-adwords
认证
大部分的包都是在考虑用户通过 Google 登录的情况下开发的。因此,EasyAdWords 中有一些认证过程的帮助程序。首先,你需要客户端 ID 和客户端密钥,有关详细信息,请参阅此处。创建您的客户端 ID 和密钥后,您可以使用它们创建一个 OAuth 对象,然后使用它来注册您的用户。
假设您在构造函数中使用了这部分,这意味着这部分用于重定向和回调部分
use EasyAdWords\AdWordsAuth\AdWordsAuth; use Google\AdsApi\AdWords\v201609\mcm\CustomerService; class MyAuth { public function __construct(){ // Parameters for the authentication process. $authorizationURI = "https://#/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(); }
这部分用于重定向到 Google
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; }
用户被重定向到 Google 并允许您的应用程序访问数据后,Google 会将用户重定向到您的 "redirectUri" 地址,这需要是一个回调。以下是一个示例回调
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(); } }
就是这样,现在您在 $credentials
参数中有了访问令牌和刷新令牌,您已经下载了账户的客户信息,现在您可以做任何您想做的事情。请注意,$this->authObject->buildOAuthObject($this->config);
行返回一个 Google\Auth\OAuth2
对象的实例,因此您可以使用该对象的任何方法,并从AdWords API 文档 中获得帮助。
配置
基本上,EasyAdWords 致力于在开发者和 AdWords PHP 客户端库 之间创建一个易于使用的接口。为了保持这个过程简单,EasyAdWords 在不同的实体和操作中使用了配置对象。所有这些配置对象都是针对它们使用的服务专门化的;然而,它们都扩展了基类 Config
。
必填字段
Config
类包含以下字段作为必填字段,因为它们对于与 EasyAdWords 一起使用的每个服务都是必需的
adwordsConfigPath
=> AdWords 配置文件的路径。如果没有提供,包将在项目根目录中查找adsapi_php.ini
文件。clientCustomerId
=> 要操作的客户的 ID。 必需。refreshToken
=> 已认证用户的刷新令牌。 必需。fields
=> 要获取的字段。 获取操作时必需。
请注意,这些字段对所有配置对象都是必需的,除了 adwordsConfigPath
键,这似乎不是必需的,但如果未提供,AdWords PHP 客户端库将在项目根目录中查找 adsapi_php.ini
文件,因此 必须存在此文件。
可选字段
以下是可以与任何配置对象一起用于实体操作的可选值。请注意,报告允许使用分页,而不是您需要使用适当的谓词过滤报告,如果响应太大。
paginated
=> 用于确定操作是否将分页进行的布尔值,如果在对实体的get
操作中遇到SizeLimitError.RESPONSE_SIZE_LIMIT_EXCEEDED
错误,则很有用。pageSize
=>get
操作的页面大小,默认为 10000,允许的最大数量。
报告
EasyAdWords 包含一些基本类,可以轻松从 AdWords 获取报告。以下是目前可用的报告类
AccountPerformanceReport
AdGroupPerformanceReport
AdPerformanceReport
CampaignPerformanceReport
CustomReport
FinalUrlReport
KeywordsPerformanceReport
SearchQueryPerformanceReport
所有这些类都实现了相同的 接口,因此它们都具有相同的方法来使用。基本上,所有这些报告类都需要使用 ReportConfig
实例来构造报告对象。以下是一个 ReportConfig
对象的示例
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])] ]);
此 ReportConfig
对象是在一个简单的数组上构建的。数组中可用的字段如下
startDate
=> 报告的开始日期。 必需。endDate
=> 报告的结束日期。 必需。predicates
=> 用于过滤报告的谓词。
现在可以使用新创建的 ReportConfig
对象初始化报告对象。在创建报告实例后,我们可以在对象上简单地调用 download()
和 format()
方法,以将报告下载为 CSV 并将其格式化为简单的单维数组。以下是一个使用示例
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();
此过程适用于所有报告。除了可用的报告类之外,您还可以使用具有相同配置对象和方法的 CustomReport
类创建 自定义报告。唯一的区别是,使用自定义报告,需要向报告对象的 download()
方法提供一个参数,指示报告的类型。提供的参数必须是 AdWords PHP 客户端库的 ReportDefinitionReportType
类的常量。以下是一个使用相同配置对象的示例报告
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();
请注意,在格式化报告后,报告的 CSV 版本不可用。
报告的可用的方法如下
download()
:下载报告并将其存储在对象的report
属性中。format()
:将 CSV 报告格式化为扁平数组。saveToFile($filePath)
:将对象的report
属性保存到指定的文件。downloadToFile($filePath)
:下载并将报告存储在给定的文件路径。请注意,此方法在下载和写入文件后不会在报告对象中保留报告。
实体
EasyAdWords为活动、广告组和关键词提供了基本的实体操作。基本上,这三个实体都能执行3个基本操作:
创建
=> 在Google AdWords中创建实体的实例。获取
=> 获取符合指定标准的实体实例。删除
=> 从Google AdWords中删除实体的实例。
还有一个账户实体,目前仅包含获取
操作。
基本上,所有这些实体对象都使用特殊的配置对象进行操作,就像报告对象一样。因此,必须创建适当的配置对象,然后,可以使用这个配置对象构造实体对象。
所有实体对象都扩展了基类Entity
并实现了EntityInterface
。因此,在每个操作之后,操作的结果都可以作为实体对象的属性访问,称为operationResult
,可以通过使用方法getOperationResult()
来访问。
目前可用的实体有:账户、活动、广告组和关键词。所有实体都有其对应的配置对象,如CampaignConfig
。
实体方法创建
、获取
和删除
的用法相同。由于获取
操作的性质,可以通过指定predicates
参数进行过滤,或者通过ordering
参数进行排序。如果没有设置predicates,将列出所有实体的实例。所有获取
操作将返回Google AdWords PHP库中的实体对象数组,可以根据Google AdWords API文档进行使用。以下是一个在Account
实体上执行获取
操作的示例结果:
$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
账户
账户实体是该包中最简单的实体。它只包含一个用于对象的获取
方法。实体操作在AccountConfig
对象上,此对象必须包含fields
参数以及上述所需字段,以确定AdWords作为结果返回的字段。
以下是一个示例用法:
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();
活动
与所有实体一样,活动实体在CampaignConfig
类的配置对象上操作。除了基Config
类中的字段外,CampaignConfig
类还包含以下字段
'campaignId' => ID of the campaign.
'campaignName' => Name of the campaign.
'advertisingChannelType' => Advertising channel of the campaign. Default is 'SEARCH'.
'status' => Status of the campaign. Default is 'PAUSED'.
'budget' => Budget of the campaign, e.g. 50 means 50$. Default is 50.
'budgetName' => Name of the budget.
'biddingStrategyType' => Bidding strategy type of the campaign. Default is 'MANUAL_CPC'.
'budgetDeliveryMethod' => Budget delivery method of the campaign. Default is 'STANDARD'.
'targetGoogleSearch' => Target Google search if true. Default is true.
'targetSearchNetwork' => Target search network if true. Default is true.
'targetContentNetwork' => Target content network if true. Default is true.
'startDate' => Start date of the campaign. Default is today.
'endDate' => End date of the campaign.
'adServingOptimizationStatus' => Ad serving optimization status of the campaign.
'servingStatus' => Serving status of the campaign. Default is 'SERVING'.
'useDefaults' => Boolean value, allows to use defaults if true.
并非所有这些参数都是所有活动操作所必需的,一些参数是创建
操作所需的,而一些参数是删除
操作所需的。然而,如果您不提供一些重要的属性,尤其是在创建活动时,您可能会遇到一些错误。如果您不想为活动提供每个选项并使用默认值,只需将useDefaults
设置为true
,它将使用默认值。请注意,当创建活动时,EasyAdWords将活动状态设置为'暂停',以防止在默认情况下因配置错误而花费金钱,除非另有说明。另外,即使使用默认值,您仍然需要提供活动名称。
活动实体的基本用法如下:
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();
广告组
AdGroup
实体使用相同的简单方法和配置逻辑。它通过使用AdGroupConfig
对象工作。该AdGroupConfig
对象包含以下字段:
'campaignId' => The campaign ID of the ad group.
'adGroupName' => The name of the ad group.
'adGroupId' => The ID of the ad group to operate on.
'status' => The status of the ad group, must be an AdGroupStatus instance. Default is 'PAUSED'.
'bid' => The bid amount to give the ad group, without extra zeros, e.g. 50 means 50$.
一些字段对于某些操作是必需的。例如,创建广告组时,campaignId
、adGroupName
和 bid
是必需字段。
AdGroup
实体的基本用法如下:
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();
关键词
关键词实体既适用于单条操作也适用于批量操作。因此,存在两个不同的关键词实体类。其中一个类是 Keyword
实体,其用法类似于 Campaign
和 AdGroup
实体;使用相同的集合和方法以及与 KeywordConfig
对象相同的初始化过程。然而,这个类旨在用于单个实体操作,而在关键词的情况下,这并不太有用。批量关键词操作的需求存在,并且 AdWords 客户端库允许在单个请求中发送多个操作。因此,实现了第二个类 KeywordBatch
,用于批量关键词添加操作。
这两个类都扩展了同一个 KeywordBase
类。
Keyword
Keyword
类可以使用与其他实体相同的集合和方法。它使用 KeywordConfig
对象进行初始化。该 KeywordConfig
对象包含以下字段:
'keyword' => Name of the keyword.
'keywordId' => ID of the keyword to operate on.
'matchType' => Match type of the keyword.
'finalUrls' => Array of the final URLs for the keyword.
'adGroupId' => ID of the ad group of the keyword.
'bid' => Bid of the keyword.
'status' => Status of the keyword.
该类的用法几乎与其他实体相同
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();
KeywordBatch
KeywordBatch
类允许一次在 Google AdWords 中创建多个关键词。该类基于简单的 KeywordBatchConfig
对象构建,除了必需的基本值之外,只有一个额外的值,即 batchSize
。batchSize
值决定了多少个关键词将被分组到单个请求中。批次大小最多为 5000,但是 AdWords API 文档建议每个请求最多传递 2000 个操作,因此 KeywordBatchConfig
对象中的默认批次大小为 2000。
KeywordBatch
对象简单地在配置对象上构建。创建实例后,该对象就准备好获取关键词列表。对于要创建的每个关键词,您需要创建一个 KeywordConfig
对象来定义关键词的属性,并将此配置对象追加到 KeywordBatch
对象中。这样,您可以将**您想添加的任意数量的关键词**追加到批次对象中,它将以大小为 batchSize
的批次处理所有这些对象。请注意,要追加关键词的 KeywordConfig
对象不需要包含 adWordsConfigPath
、clientCustomerId
和 refreshToken
参数,因为这些已在 KeywordBatchConfig
对象中给出。为了完成操作并在 Google AdWords 上创建关键词,您需要在 KeywordBatch
对象上调用 mutate()
方法。在您调用 mutate()
方法之前,所有关键词都只是对象内的一个数组。
KeywordBatch
的一个示例用法如下:
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();
使用批次配置类,您可以批量创建关键词,从而减少创建关键词的网络请求。**目前 KeywordBatch
类仅适用于批量关键词添加操作**。
贡献
非常欢迎您以任何形式参与 EasyAdWords 的发展!为了对包做出贡献,您需要克隆项目,并在您的 composer.json
文件中使用 repositories
选项包含它。以下是一个示例用法:
"repositories": [{ "type": "vcs", "url": "path/to/easy-adwords" }], "require": { "adprolabs/easy-adwords": "dev-master" },
请注意,repositories
与 require
键处于同一级别,而不是嵌套在其他内容中。当 repositories
选项与 type
中的 vcs
值一起使用时,它会正常工作。因此,为了在其他项目中以包的形式包含并测试此包,您需要在包上提交更改,然后在测试项目中执行 composer update
,以获取您所做更改的最新版本。
在成功更新项目并附带自解释的提交信息,以及用 PHPDoc 风格添加适当的注释来解释代码之后,您可以提交一个 pull request,并解释为什么需要更新以及您为解决这个问题所采取的解决方案。
此外,您可以通过创建一个定义明确且可复现的问题的 issue 或提供对包及其设计的反馈来为 EasyAdWords 做出贡献。任何形式的参与都非常受欢迎。
许可协议
EasyAdWords 以 MIT 许可协议发布。有关更多信息,请参阅 LICENSE.md。