客户端库

我们的客户端库提供了 Google Ads API 功能,让您能够更轻松地快速开发应用。我们建议 如果是刚开始接触 API

客户端库 来源 分布 代码示例
Java google-ads-java Maventar.gz 在 GitHub 上查看
.NET google-ads-dotnet nugettar.gz、zip 在 GitHub 上查看
PHP google-ads-php tar.gz 在 GitHub 上查看
Python google-ads-python tar.gz、zip 在 GitHub 上查看
Ruby google-ads-ruby gem、tar.gz、zip 在 GitHub 上查看
Perl google-ads-perl tar.gz、zip 在 GitHub 上查看

支持的 API 版本

下表显示了哪些客户端库支持哪些 API 版本。

Java

Java 版客户端库
v17 Min: 32.0.0
Max: -
v16 Min: 30.0.0
Max: -
v15 Min: 28.0.0
Max: -

C#

适用于 .NET 的客户端库
v17 Min: 20.1.0
Max: -
v16 Min: 18.1.0
Max: -
v15 Min: 17.1.0
Max: -

PHP

PHP 版客户端库
v17 Min: 23.1.0
Max: -
v16 Min: 22.1.0
Max: -
v15 Min: 21.1.0
Max: -

Python

适用于 Python 的客户端库
v17 Min: 24.1.0
Max: -
v16 Min: 23.1.0
Max: -
v15 Min: 22.1.0
Max: -

Ruby

适用于 Ruby 的客户端库
v17 Min: 29.0.0
Max: -
v16 Min: 27.0.0
Max: -
v15 Min: 25.0.0
Max: -

Perl

适用于 Perl 的客户端库
v17 Min: 23.0.0
Max: -
v16 Min: 21.0.0
Max: -
v15 Min: 19.0.0
Max: -

配置

每个 Ads API 客户端库都提供不同的配置设置 这些加载方法可用于自定义其行为。

以下是所有客户端库和 (可加载以配置设置):

  • 客户端库 <ph type="x-smartling-placeholder">
      </ph>
    • GOOGLE_ADS_CONFIGURATION_FILE_PATH:配置文件的路径。
  • OAuth2 <ph type="x-smartling-placeholder">
      </ph>
    • 应用模式 <ph type="x-smartling-placeholder">
        </ph>
      • GOOGLE_ADS_CLIENT_ID:将此值设置为您的 OAuth2 客户端 ID。
      • GOOGLE_ADS_CLIENT_SECRET:将此值设置为您的 OAuth2 客户端密钥。
      • GOOGLE_ADS_REFRESH_TOKEN:将此值设置为预先生成的 OAuth2 刷新令牌 如果您想重复使用 OAuth2 令牌此设置是可选的。
    • 服务账号模式 <ph type="x-smartling-placeholder">
        </ph>
      • GOOGLE_ADS_JSON_KEY_FILE_PATH:将此值设置为 OAuth2 JSON 配置 文件路径。
      • GOOGLE_ADS_IMPERSONATED_EMAIL:将此值设置为 。
  • Google Ads API <ph type="x-smartling-placeholder">
      </ph>
    • GOOGLE_ADS_DEVELOPER_TOKEN:将此项设置为您的开发者令牌。
    • GOOGLE_ADS_LOGIN_CUSTOMER_ID:这是获授权客户使用的客户 ID 不带连字符 (-)。
    • GOOGLE_ADS_LINKED_CUSTOMER_ID:只有更新 实体资源(通过 Google Ads 界面(Google Ads API 中的 AccountLink 资源)。设置此值 数据提供商的客户 ID(更新该提供商的资源) 指定客户 ID。设置时不得使用连字符 (-)。了解详情 如需了解关联的账号,请访问帮助中心

环境变量通常在 bash 配置文件中定义,例如 指定为位于 $HOME 目录中的 .bashrc.bash_profile 文件。他们 也可以使用命令行进行定义

以下是使用 .bashrc 定义环境变量的一些基本步骤 查看文件:

# Append the line "export GOOGLE_ADS_CLIENT_ID=1234567890" to
# the bottom of your .bashrc file.
echo "export GOOGLE_ADS_CLIENT_ID=1234567890" >> ~/.bashrc

# Update your bash environment to use the most recently updated
# version of your .bashrc file.
src ~/.bashrc

您也可以直接通过以下命令在终端实例中设置环境变量: 请在命令行中运行以下命令:

export GOOGLE_ADS_CLIENT_ID=1234567890

另一种方法是在调用命令时设置环境变量 使用它们:

GOOGLE_ADS_CLIENT_ID=1234567890 php /path/to/script/that/uses/envvar.php

搜索分页

GoogleAdsService.Search 通常为 在显示结果页面的交互式应用中使用。

我们的客户端库会自动实现 对结果进行迭代更新,以便 依序下载和一次性处理所有请求,例如:

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    String query = "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id";
    // Constructs the SearchGoogleAdsStreamRequest.
    SearchGoogleAdsStreamRequest request =
        SearchGoogleAdsStreamRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .setQuery(query)
            .build();

    // Creates and issues a search Google Ads stream request that will retrieve all campaigns.
    ServerStream<SearchGoogleAdsStreamResponse> stream =
        googleAdsServiceClient.searchStreamCallable().call(request);

    // Iterates through and prints all of the results in the stream response.
    for (SearchGoogleAdsStreamResponse response : stream) {
      for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
        System.out.printf(
            "Campaign with ID %d and name '%s' was found.%n",
            googleAdsRow.getCampaign().getId(), googleAdsRow.getCampaign().getName());
      }
    }
  }
}
      

C#

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V17.GoogleAdsService);

    // Create a query that will retrieve all campaigns.
    string query = @"SELECT
                    campaign.id,
                    campaign.name,
                    campaign.network_settings.target_content_network
                FROM campaign
                ORDER BY campaign.id";

    try
    {
        // Issue a search request.
        googleAdsService.SearchStream(customerId.ToString(), query,
            delegate (SearchGoogleAdsStreamResponse resp)
            {
                foreach (GoogleAdsRow googleAdsRow in resp.Results)
                {
                    Console.WriteLine("Campaign with ID {0} and name '{1}' was found.",
                        googleAdsRow.Campaign.Id, googleAdsRow.Campaign.Name);
                }
            }
        );
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      

PHP

public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
{
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    // Creates a query that retrieves all campaigns.
    $query = 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id';
    // Issues a search stream request.
    /** @var GoogleAdsServerStreamDecorator $stream */
    $stream = $googleAdsServiceClient->searchStream(
        SearchGoogleAdsStreamRequest::build($customerId, $query)
    );

    // Iterates over all rows in all messages and prints the requested field values for
    // the campaign in each row.
    foreach ($stream->iterateAllElements() as $googleAdsRow) {
        /** @var GoogleAdsRow $googleAdsRow */
        printf(
            "Campaign with ID %d and name '%s' was found.%s",
            $googleAdsRow->getCampaign()->getId(),
            $googleAdsRow->getCampaign()->getName(),
            PHP_EOL
        );
    }
}
      

Python

def main(client, customer_id):
    ga_service = client.get_service("GoogleAdsService")

    query = """
        SELECT
          campaign.id,
          campaign.name
        FROM campaign
        ORDER BY campaign.id"""

    # Issues a search request using streaming.
    stream = ga_service.search_stream(customer_id=customer_id, query=query)

    for batch in stream:
        for row in batch.results:
            print(
                f"Campaign with ID {row.campaign.id} and name "
                f'"{row.campaign.name}" was found.'
            )
      

Ruby

def get_campaigns(customer_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  responses = client.service.google_ads.search_stream(
    customer_id: customer_id,
    query: 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id',
  )

  responses.each do |response|
    response.results.each do |row|
      puts "Campaign with ID #{row.campaign.id} and name '#{row.campaign.name}' was found."
    end
  end
end
      

Perl

sub get_campaigns {
  my ($api_client, $customer_id) = @_;

  # Create a search Google Ads stream request that will retrieve all campaigns.
  my $search_stream_request =
    Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
    ->new({
      customerId => $customer_id,
      query      =>
        "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id"
    });

  # Get the GoogleAdsService.
  my $google_ads_service = $api_client->GoogleAdsService();

  my $search_stream_handler =
    Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
      service => $google_ads_service,
      request => $search_stream_request
    });

  # Issue a search request and process the stream response to print the requested
  # field values for the campaign in each row.
  $search_stream_handler->process_contents(
    sub {
      my $google_ads_row = shift;
      printf "Campaign with ID %d and name '%s' was found.\n",
        $google_ads_row->{campaign}{id}, $google_ads_row->{campaign}{name};
    });

  return 1;
}
      

根据用例的不同,您可能需要执行以下操作:

  • 优化抓取的网页数量。
  • 优化一次存储的结果数量。
  • 按特定顺序下载和处理结果页。

这可以通过存储页面令牌而不是结果来实现,这会增加 让代码更加复杂

代码示例

您可以查看代码示例,了解 Google Ads API。