进行 API 调用

本指南需要在前面的步骤中配置的几个前提条件设置。如果您尚未阅读简介,请先阅读。

本指南还使用了刷新令牌,这种工作流程可让对 Google Ads 账号拥有足够访问权限的用户通过一次性设置授权您的应用对该账号进行离线 API 调用,而无需用户进一步干预。您可以使用刷新令牌构建离线工作流(例如 Cron 作业或数据流水线)和互动式工作流(例如 Web 或移动应用)。

提取刷新令牌

Google Ads API 使用 OAuth 2.0 作为授权机制。默认情况下,OAuth 2.0 身份验证会发出一个在限定时间后过期的访问令牌。如需自动续期访问令牌,请改为发出刷新令牌

oauth2l

  1. 运行 oauth2l 工具生成刷新令牌:

    oauth2l fetch --credentials credentials.json --scope adwords \
        --output_format refresh_token

    credentials.json 文件来自上一步

  2. oauth2l 命令会在新浏览器窗口中打开 Google 账号登录窗口,并引导您完成 OAuth 2.0 身份验证步骤。

    请务必使用您在登录客户 ID 时使用的电子邮件地址登录。

    如果您的应用未经验证,您可能会看到警告界面。在这种情况下,您可以放心地点击显示高级链接,然后点击前往 PROJECT_NAME(未经验证)选项。

  3. 验证范围后,点击继续按钮授予权限。

    浏览器中会显示一条提示,其中包含以下文本:

    Authorization code granted. Close this tab.
    

    oauth2l 命令会输出以下 JSON 代码段:

    {
      "client_id": "******.apps.googleusercontent.com",
      "client_secret": "******",
      "token_uri": "https://oauth2.googleapis.com/token",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "refresh_token": "******",
      "type": "authorized_user"
    }
    

gcloud CLI

  1. 运行 gcloud CLI 工具生成刷新令牌:

    gcloud auth application-default \
      login --scopes=https://www.googleapis.com/auth/adwords,https://www.googleapis.com/auth/cloud-platform \
      --client-id-file=<path_to_credentials.json>

    credentials.json 文件来自上一步

  2. gcloud 命令会在新浏览器窗口中打开 Google 账号登录窗口,并引导您完成 OAuth 2.0 身份验证步骤。

    请务必使用您在登录客户 ID 时使用的电子邮件地址登录。

    如果您的应用未经验证,您可能会看到警告界面。在这种情况下,您可以放心地点击显示高级链接,然后点击前往 PROJECT_NAME(未经验证)选项。

  3. 验证范围后,点击继续按钮以授予权限。

    浏览器会转到 https://cloud.google.com/sdk/auth_success,表示身份验证已成功。

    Authorization code granted. Close this tab.
    

    gcloud 命令会输出如下内容:

    Credentials saved to file: [/****/.config/gcloud/application_default_credentials.json]
    

    现在,打开 application_default_credentials.json 文件。其内容应如下所示:

    {
      "account": "",
      "client_id": "******.apps.googleusercontent.com",
      "client_secret": "******",
      "refresh_token": "******",
      "type": "authorized_user",
      "universe_domain": "googleapis.com"
    }
    

其他

如果您更喜欢使用 curl 或您自己的 HTTP 客户端,请参阅适用于移动和桌面应用的 OAuth 2.0 指南中的示例。

进行 API 调用

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

Java

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

Maven 依赖项为:

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

Gradle 依赖项为:

implementation 'com.google.api-ads:google-ads:34.0.0'

创建一个包含以下内容的 ~/ads.properties 文件。

api.googleads.clientId=INSERT_CLIENT_ID_HERE
api.googleads.clientSecret=INSERT_CLIENT_SECRET_HERE
api.googleads.refreshToken=INSERT_REFRESH_TOKEN_HERE
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 代码库。首先,将 nuget 引用添加到 Google.Ads.GoogleAds 软件包。

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

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

GoogleAdsConfig config = new GoogleAdsConfig()
{
    DeveloperToken = "******",
    OAuth2Mode = "APPLICATION",
    OAuth2ClientId = "******.apps.googleusercontent.com",
    OAuth2ClientSecret = "******",
    OAuth2RefreshToken = "******",
    LoginCustomerId = ******
};
GoogleAdsClient client = new GoogleAdsClient(config);

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

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

复制 GitHub 代码库中的 google_ads_php.ini 文件,并将其修改为包含您的凭据。

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

[OAUTH2]
clientId = "INSERT_OAUTH2_CLIENT_ID_HERE"
clientSecret = "INSERT_OAUTH2_CLIENT_SECRET_HERE"
refreshToken = "INSERT_OAUTH2_REFRESH_TOKEN_HERE"

创建 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 文件,并对其进行修改以添加您的凭据。

client_id: INSERT_OAUTH2_CLIENT_ID_HERE
client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE
refresh_token: INSERT_REFRESH_TOKEN_HERE
developer_token: INSERT_DEVELOPER_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_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")

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

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

客户端库的 Ruby gem 会发布到 Rubygems gem 托管网站。建议使用 Bundler 进行安装。将以下代码行添加到 Gemfile 中:

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

然后运行以下命令:

bundle install

复制 GitHub 代码库中的 google_ads_config.rb 文件,并将其修改为包含您的凭据。

Google::Ads::GoogleAds::Config.new do |c|
  c.client_id = 'INSERT_CLIENT_ID_HERE'
  c.client_secret = 'INSERT_CLIENT_SECRET_HERE'
  c.refresh_token = 'INSERT_REFRESH_TOKEN_HERE'
  c.developer_token = 'INSERT_DEVELOPER_TOKEN_HERE'
  c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE'
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 文件,并将其修改为包含您的凭据。

clientId=INSERT_OAUTH2_CLIENT_ID_HERE
clientSecret=INSERT_OAUTH2_CLIENT_SECRET_HERE
refreshToken=INSERT_OAUTH2_REFRESH_TOKEN_HERE
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::V18::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;
}

REST

首先,使用 HTTP 客户端提取 OAuth 2.0 访问令牌。本指南使用 curl 命令。

curl \
  --data "grant_type=refresh_token" \
  --data "client_id=CLIENT_ID" \
  --data "client_secret=CLIENT_SECRET" \
  --data "refresh_token=REFRESH_TOKEN" \
  https://www.googleapis.com/oauth2/v3/token

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

curl -i -X POST https://googleads.googleapis.com/v18/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"
}