快速入门

本快速入门指南可帮助您首次调用 Google Ads API。

主要概念

  • 开发者令牌:开发者令牌是一个字母数字字符串,长度为 22 个字符,用于向 Google Ads API 服务器标识您的应用。进行 API 调用时需要此权限。
  • API 访问权限级别开发者令牌的 API 访问权限级别会控制您每天可以进行的 API 调用次数以及可以进行 API 调用的环境。
  • Google Ads 经理账号Google Ads 经理账号用于管理其他 Google Ads 账号。Google Ads 经理账号可用于管理 Google Ads 客户账号或其他 Google Ads 经理账号。您需要拥有 Google Ads 经理账号才能获取开发者令牌。
  • Google Ads 客户账号:您要针对其发出 API 调用请求的 Google Ads 账号。
  • 客户客户 ID:用于标识 Google Ads 客户账号的 10 位数。
  • OAuth 2.0OAuth 2.0 是一种行业标准授权协议,所有 Google API 都使用该协议。您需要服务账号和密钥才能生成 OAuth 2.0 凭据来执行 API 调用。
  • Google Cloud 项目Google Cloud 项目是创建、启用和使用所有 Google 服务的基础,包括管理 API 和 OAuth 2.0 API 凭据。您可以通过 Google Cloud 控制台创建。
  • 服务账号一种特殊类型的 Google 账号,属于您的应用,而非单个用户。它用于向 Google Ads API 验证您的应用。您需要拥有 Google Cloud 项目才能获取服务账号。
  • 服务账号密钥:包含服务账号私钥的 JSON 应用凭据文件。它用于生成 OAuth 2.0 凭据,以便在进行 Google Ads API 调用时对服务账号进行身份验证。您需要一个服务账号才能获取服务账号密钥。

前提条件

如需进行 Google Ads API 调用,您应完成以下步骤。

获取开发者令牌

如果您之前申请过开发者令牌,可以在登录 Google Ads 经理账号后访问 API 中心来查找该令牌。

访问 API 中心

如果您没有开发者令牌,可以在 API 中心内申请一个。

如何申请开发者令牌

  1. 在网络浏览器中前往 API 中心。如果系统提示,请登录您的 Google Ads 经理账号。 如果您还没有 Google Ads 经理账号,请创建一个
  2. 填写 API 访问权限表单并接受条款及条件
    • 确保您的信息正确无误,并且公司网站网址有效。如果网站未上线,Google 可能无法处理您的申请并会拒绝该申请。
    • 确保您提供的 API 联系人电子邮件地址指向的是经常有人监控的收件箱。在审核过程中,Google 的 API 合规性团队可能会通过此电子邮件地址与您联系,以寻求澄清。如果您无法接听电话,Google 可能不会继续处理您的申请。
    • 您可以在 API 中心内修改 API 联系电子邮件地址。 即使在申请流程结束后,也请务必及时更新此信息,以便 Google 向您发送重要的服务通知。

完成申请流程后,开发者令牌会显示在 API 中心内,状态为待批准。您的开发者令牌现在具有测试账号访问权限级别。

配置 Google API 控制台项目

Google API 控制台项目用于管理 Google API 和 OAuth 2.0 API 凭据。您可以访问 Google API 控制台,查找现有的 Google API 控制台项目或创建一个项目。

打开 Google API 控制台

首先,在项目中启用 Google Ads API:

启用 Google Ads API

接下来,您需要一个服务账号和服务账号密钥才能进行 API 调用。如果您已在使用其他 Google API,并且已创建 OAuth 2.0 服务账号和密钥,则可以跳过此步骤并重复使用现有凭据。

如何创建服务账号和密钥

  1. 在 Google Cloud 控制台中,依次前往“菜单”图标 > IAM 和管理 > 服务账号

    前往“服务账号”

  2. 选择您的服务账号。
  3. 依次点击密钥 > 添加密钥 > 创建新密钥
  4. 选择 JSON,然后点击创建

    系统会生成新的公钥/私钥对,并以新文件的形式下载到您的计算机。将下载的 JSON 文件另存为工作目录中的 credentials.json。此文件是相应密钥的唯一副本。

  5. 点击关闭

首先,确定您要针对哪个 Google Ads 账号发起 API 调用。您可以向哪种类型的账号发起 API 调用取决于您的开发者令牌的 API 访问权限级别。查看 API 中心,了解您的 API 访问权限级别。

基本权限和标准权限

您可以向 Google Ads 生产账号发出调用。不过,您可以按照测试账号访问权限标签页中的说明创建 Google Ads 测试账号(如果需要)。

测试账号访问权限

您的开发者令牌无法用于向 Google Ads 生产账号发出 API 调用。您只能针对 Google Ads 测试账号进行 API 调用。

如何创建 Google Ads 测试账号

以下说明将创建一个 Google Ads 测试经理账号,并在该账号下创建一个 Google Ads 测试 Google Ads 广告客户账号。

  1. 点击蓝色按钮,创建 Google Ads 测试经理账号。 如果系统提示,请使用未与您的 Google Ads 正式版经理账号相关联的 Google 账号登录。如果您没有 Google 账号,请使用该页面上的创建账号按钮创建一个新的 Google 账号。

    创建 Google Ads 测试经理账号

  2. 在 Google Ads 测试经理账号中,创建一个 Google Ads 测试客户账号:依次点击账号 > > 创建新账号,然后填写表单。通过 Google Ads 测试经理账号创建的任何 Google Ads 账号都会自动成为 Google Ads 测试账号。
  3. (可选)在 Google Ads 页面中,在 Google Ads 测试客户账号下创建几个广告系列。

如需向 Google Ads 客户账号发出 API 调用,您必须向您的服务账号授予对该 Google Ads 客户账号的访问权限和相应权限。为此,您需要拥有客户账号的管理员权限。

如何向服务账号授予对 Google Ads 账号的访问权限

  1. 首先以管理员身份登录您的 Google Ads 账号。
  2. 前往管理员 > 访问权限和安全
  3. 点击用户标签页下方的 按钮。
  4. 电子邮件输入框中输入服务账号电子邮件地址。 选择适当的账号访问权限级别,然后点击添加账号按钮。请注意,服务账号不支持电子邮件访问权限级别。
  5. 系统会向服务账号授予访问权限。
  6. [可选] 默认情况下,您无法向服务账号授予管理员访问权限。如果您的 API 调用需要管理员访问权限,您可以按如下方式升级访问权限。
    1. 点击访问权限级别列中服务账号的访问权限级别旁边的下拉箭头。
    2. 从下拉列表中选择管理员

下载工具和客户端库

您可以选择下载客户端库或 HTTP 客户端,具体取决于您希望如何进行 API 调用。

使用客户端库

下载并安装您选择的客户端库

使用 HTTP 客户端 (REST)

curl

下载并安装 curl,这是一款通过网址传输数据的命令行工具。

Google Cloud CLI

按照说明安装 gcloud CLI。

本指南其余部分的说明已通过验证,可与以下版本的 gcloud 工具搭配使用,但由于应用行为或命令行选项存在差异,可能无法与之前的版本搭配使用。

:~$ gcloud version
Google Cloud SDK 492.0.0
alpha 2024.09.06
beta 2024.09.06
bq 2.1.8
bundled-python3-unix 3.11.9
core 2024.09.06
enterprise-certificate-proxy 0.3.2
gcloud-crc32c 1.0.0
gsutil 5.30

进行 API 调用

选择您偏好的客户端,了解如何进行 API 调用:

Java

客户端库工件已发布到 Maven 中央制品库。将客户端库作为依赖项添加到您的项目中,如下所示:

Maven 依赖项为:

<dependency>
  <groupId>com.google.api-ads</groupId>
  <artifactId>google-ads</artifactId>
  <version>40.0.0</version>
</dependency>

Gradle 依赖项为:

implementation 'com.google.api-ads:google-ads:40.0.0'
api.googleads.serviceAccountSecretsPath=JSON_KEY_FILE_PATH
api.googleads.developerToken=INSERT_DEVELOPER_TOKEN_HERE
api.googleads.loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE

按如下方式创建一个 GoogleAdsClient 对象:

GoogleAdsClient googleAdsClient = null;
try {
  googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
  System.err.printf(
      "Failed to load GoogleAdsClient configuration from file. Exception: %s%n",
      fnfe);
  System.exit(1);
} catch (IOException ioe) {
  System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
  System.exit(1);
}

接下来,使用 GoogleAdsService.SearchStream 方法运行广告系列报告,以检索您账号中的广告系列。本指南不涉及报告的详细信息。

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#

客户端库软件包会发布到 Nuget.org 存储库。首先,添加对 Google.Ads.GoogleAds 软件包的 NuGet 引用。

dotnet add package Google.Ads.GoogleAds --version 18.1.0

创建具有相关设置的 GoogleAdsConfig 对象,并使用该对象创建 GoogleAdsClient 对象。

GoogleAdsConfig config = new GoogleAdsConfig()
{
    DeveloperToken = "******",
    OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
    OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
    LoginCustomerId = ******
};
GoogleAdsClient client = new GoogleAdsClient(config);

接下来,使用 GoogleAdsService.SearchStream 方法运行广告系列报告,以检索您账号中的广告系列。本指南不涉及报告的详细信息。

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V21.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

客户端库软件包发布到 Packagist 代码库。进入项目的根目录,然后运行以下命令,将库及其所有依赖项安装到项目根目录的 vendor/ 目录中。

composer require googleads/google-ads-php:31.0.0

从 GitHub 代码库中复制 google_ads_php.ini 文件,并对其进行修改以添加您的凭据。

[GOOGLE_ADS]
developerToken = "INSERT_DEVELOPER_TOKEN_HERE"
loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"

[OAUTH2]
jsonKeyFilePath = "INSERT_ABSOLUTE_PATH_TO_OAUTH2_JSON_KEY_FILE_HERE"
scopes = "https://www.googleapis.com/auth/adwords"

创建 GoogleAdsClient 对象的实例。

$oAuth2Credential = (new OAuth2TokenBuilder())
    ->fromFile('/path/to/google_ads_php.ini')
    ->build();

$googleAdsClient = (new GoogleAdsClientBuilder())
    ->fromFile('/path/to/google_ads_php.ini')
    ->withOAuth2Credential($oAuth2Credential)
    ->build();

接下来,使用 GoogleAdsService.SearchStream 方法运行广告系列报告,以检索您账号中的广告系列。本指南不涉及报告的详细信息。

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

客户端库在 PyPI 上分发,可以使用 pip 命令进行安装,如下所示:

python -m pip install google-ads==21.3.0

从 GitHub 代码库中复制 google-ads.yaml 文件,并对其进行修改以添加您的凭据。

developer_token: INSERT_DEVELOPER_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE
json_key_file_path: JSON_KEY_FILE_PATH_HERE

通过调用 GoogleAdsClient.load_from_storage 方法创建 GoogleAdsClient 实例。在调用该方法时,将 google-ads.yaml 的路径作为字符串传递给该方法:

from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage("path/to/google-ads.yaml")

向库的记录器添加一个处理程序,告知记录器将日志输出到何处。 以下代码将指示库的记录器输出到控制台 (stdout)。

import logging
import sys

logger = logging.getLogger('google.ads.googleads.client')
logger.addHandler(logging.StreamHandler(sys.stdout))

接下来,使用 GoogleAdsService.SearchStream 方法运行广告系列报告,以检索您账号中的广告系列。本指南不涉及报告的详细信息。

def main(client: GoogleAdsClient, customer_id: str) -> None:
    ga_service: GoogleAdsServiceClient = client.get_service("GoogleAdsService")

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

    # Issues a search request using streaming.
    stream: Iterator[SearchGoogleAdsStreamResponse] = ga_service.search_stream(
        customer_id=customer_id, query=query
    )

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

Ruby

客户端库的 Ruby gem 发布到 Rubygems gem 托管网站。建议使用 bundler 进行安装。向 Gemfile 添加一行:

gem 'google-ads-googleads', '~> 35.2.0'

然后运行以下命令:

bundle install

从 GitHub 代码库中复制 google_ads_config.rb 文件,并对其进行修改以添加您的凭据。

Google::Ads::GoogleAds::Config.new do |c|
  c.developer_token = 'INSERT_DEVELOPER_TOKEN_HERE'
  c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE'
  c.keyfile = 'JSON_KEY_FILE_PATH'
end

通过传递此文件的保存路径来创建 GoogleAdsClient 实例。

client = Google::Ads::GoogleAds::GoogleAdsClient.new('path/to/google_ads_config.rb')

接下来,使用 GoogleAdsService.SearchStream 方法运行广告系列报告,以检索您账号中的广告系列。本指南不涉及报告的详细信息。

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

该库在 CPAN 上分发。首先,在您选择的目录中克隆 google-ads-perl 代码库。

git clone https://github.com/googleads/google-ads-perl.git

切换到 google-ads-perl 目录,然后在命令提示符下运行以下命令,以安装使用该库所需的所有依赖项。

cd google-ads-perl
cpan install Module::Build
perl Build.PL
perl Build installdeps

从 GitHub 代码库中复制 googleads.properties 文件,并对其进行修改以添加您的凭据。

jsonKeyFilePath=JSON_KEY_FILE_PATH
developerToken=INSERT_DEVELOPER_TOKEN_HERE
loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE

通过传递此文件的保存路径来创建 Client 实例。

my $properties_file = "/path/to/googleads.properties";

my $api_client = Google::Ads::GoogleAds::Client->new({
  properties_file => $properties_file
});

接下来,使用 GoogleAdsService.SearchStream 方法运行广告系列报告,以检索您账号中的广告系列。本指南不涉及报告的详细信息。

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::V21::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;
}

curl

首先,在 gcloud CLI 中将服务账号设置为有效凭据。

gcloud auth login --cred-file=PATH_TO_CREDENTIALS_JSON

接下来,获取 Google Ads API 的 OAuth 2.0 访问令牌。

gcloud auth \
  print-access-token \
  --scopes='https://www.googleapis.com/auth/adwords'

接下来,使用 GoogleAdsService.SearchStream 方法运行广告系列报告,以检索您账号中的广告系列。本指南不涉及报告的详细信息。

curl -i -X POST https://googleads.googleapis.com/v21/customers/CUSTOMER_ID/googleAds:searchStream \
   -H "Content-Type: application/json" \
   -H "Authorization: Bearer ACCESS_TOKEN" \
   -H "developer-token: DEVELOPER_TOKEN" \
   -H "login-customer-id: LOGIN_CUSTOMER_ID" \
   --data-binary "@query.json"

query.json 的内容如下所示:

{
  "query": "SELECT campaign.id, campaign.name, campaign.network_settings.target_content_network FROM campaign ORDER BY campaign.id"
}