使用入门

本指南将简要介绍如何开始使用 Google Ads API .NET 库。

安装

客户端库二进制文件使用 NuGet 进行分发。将 Nuget 引用添加到项目中的 Google.Ads.GoogleAds 软件包,以使用客户端库。

设置授权

如需为您的 API 调用授权,您需要为库指定您的客户端 ID、客户端密钥、刷新令牌和开发者令牌。

如果您已有凭据...

  • GitHub 中的 App.config 文件configSections 节点下的 GoogleAdsApi 节点和 GoogleAdsApi 部分复制到 App.config / Web.config 文件中。如果您使用 NuGet 安装软件包,这些节点将自动插入到您的 App.config / Web.config 文件中。
  • 在应用的 App.config / Web.config 中添加开发者令牌、客户端 ID、客户端密钥和刷新令牌。GitHub 中包含的 App.config 文件详尽无遗,但您还可以参阅配置指南,详细了解如何使用备用配置设置。

如果您需要生成凭据...

  • 如果您还没有开发者令牌,请按照开发者令牌指南获取。
  • 按照 OAuth 桌面应用流程指南生成客户端 ID、客户端密钥和刷新令牌。
  • GitHub 中的 App.config 文件configSections 节点下的 GoogleAdsApi 节点和 GoogleAdsApi 部分复制到 App.config / Web.config 文件中。如果您使用 NuGet 安装软件包,这些节点将自动插入到您的 App.config / Web.config 文件中。
  • 在应用的 App.config / Web.config 中添加开发者令牌、客户端 ID、客户端密钥和刷新令牌。GitHub 中包含的 App.config 文件详尽无遗,但您还可以参阅配置指南,详细了解如何使用备用配置设置。

进行 API 调用

客户端库的基本用法如下所示:

// Create a Google Ads client.
GoogleAdsClient client = new GoogleAdsClient();

// Create the required service.
CampaignServiceClient campaignService =
    client.GetService(Services.V16.CampaignService);

// Make more calls to service class.

创建 GoogleAdsClient 实例

Google Ads API .NET 库中最重要的类是 GoogleAdsClient 类。它允许您创建可用于进行 API 调用的预配置服务类。GoogleAdsClient 提供了一个默认构造函数,该构造函数使用在应用的 App.config / Web.config 中指定的设置来创建用户对象。如需了解各种配置选项,请参阅配置指南

// Create a new GoogleAdsClient with the App.config settings.
GoogleAdsClient user = new GoogleAdsClient();

创建服务

GoogleAdsClient 提供了可用于创建广告服务的 GetService 方法。

CampaignServiceClient campaignService = client.GetService(Services.V16.CampaignService);
// Now make calls to CampaignService.

我们提供了 Services 类,用于枚举所有受支持的 API 版本和服务。创建服务时,GetService 方法接受这些枚举对象作为参数。例如,要为 Google Ads API 版本 V16 创建 CampaignServiceClient 实例,需要以 Services.V16.CampaignService 为参数调用 GoogleAdsClient.GetService 方法,如上所示。

线程安全

在多个线程之间共享 GoogleAdsClient 实例并不安全,因为您在一个线程中对实例进行的配置更改可能会影响您在其他线程中创建的服务。从 GoogleAdsClient 实例获取新的服务实例、并行调用多个服务等操作是线程安全的。

多线程应用将如下所示:

GoogleAdsClient client1 = new GoogleAdsClient();
GoogleAdsClient client2 = new GoogleAdsClient();

Thread userThread1 = new Thread(addAdGroups);
Thread userThread2 = new Thread(addAdGroups);

userThread1.start(client1);
userThread2.start(client2);

userThread1.join();
userThread2.join();

public void addAdGroups(object data) {
  GoogleAdsClient client = (GoogleAdsClient) data;
  // Do more operations here.
  ...
}

避免 .NET Framework 应用冻结

同步方法可能会导致某些 .NET Framework 应用冻结。一个常见示例是通过 WinForm 应用的事件处理脚本方法进行 API 调用。

可以通过两种方法解决此问题:

  1. 使用旧版 Grpc 库

    您可以将 GoogleAdsConfigUseGrpcCore 属性设为使用旧版 Grpc.Core 库,而不是默认的 Grpc.Net.Client 库。此方法尚未在 .NET Framework 应用中进行全面测试,因此可能无法解决问题。以下是一个示例代码段:

    GoogleAdsConfig config = new GoogleAdsConfig();
    config.UseGrpcCore = true;
    GoogleAdsClient client = new GoogleAdsClient(config);
    
  2. 使用异步方法

    您可以使用异步方法来避免冻结。下面是一些示例:

    SearchStream

    系统会调用 SearchStream(),并将结果填充到列表视图中。

    private async void button1_Click(object sender, EventArgs e)
    {
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V16.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";
     
    List items = new List();
    Task t =  googleAdsService.SearchStreamAsync(customerId.ToString(), query,
        delegate (SearchGoogleAdsStreamResponse resp)
        {
            foreach (GoogleAdsRow googleAdsRow in resp.Results)
            {
                ListViewItem item = new ListViewItem();
                item.Text = googleAdsRow.Campaign.Id.ToString();
                item.SubItems.Add(googleAdsRow.Campaign.Name);
                items.Add(item);
            }
        }
    );
    await t;
    listView1.Items.AddRange(items.ToArray());
    }
    

    广告系列预算

    创建 CampaignBudget 调用,使用 MessageBox 提醒显示新预算的资源名称。

    private async void button2_Click(object sender, EventArgs e)
    {
    // Get the BudgetService.
    CampaignBudgetServiceClient budgetService = client.GetService(
        Services.V16.CampaignBudgetService);
     
    // Create the campaign budget.
    CampaignBudget budget = new CampaignBudget()
    {
        Name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(),
        DeliveryMethod = BudgetDeliveryMethod.Standard,
        AmountMicros = 500000
    };
     
    // Create the operation.
    CampaignBudgetOperation budgetOperation = new CampaignBudgetOperation()
    {
        Create = budget
    };
     
    // Create the campaign budget.
    Task t = budgetService.MutateCampaignBudgetsAsync(
        customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation });
     
    await t;
    MutateCampaignBudgetsResponse response = t.Result;
    MessageBox.Show(response.Results[0].ResourceName);
    }
    

取消异步方法

对于异步编程,您可以使用 callSettings 参数来传递 CancellationToken

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.CancelAfter(3000);
CallSettings callSettings = CallSettings.FromCancellationToken(cancellationTokenSource.Token);

string query = "SELECT campaign.name FROM campaign";
var request = new SearchGoogleAdsStreamRequest()
{
    CustomerId = customerId.ToString(),
    Query = query,
};

GoogleAdsServiceClient googleAdsService = client.GetService(
    Services.V16.GoogleAdsService);

googleAdsService.SearchStream(request,
    delegate (SearchGoogleAdsStreamResponse resp)
    {
        foreach (GoogleAdsRow googleAdsRow in resp.Results)
        {
            // Process the row.
        }
    }, callSettings
);

错误处理

并非所有 API 调用都会成功。如果您的 API 调用由于某种原因而失败,则服务器可能会抛出错误。捕获 API 错误并妥善处理非常重要。

发生 API 错误时,系统会抛出 GoogleAdsException 实例。其中包含的详细信息可帮助您找出问题所在:

// Get the CampaignService.
CampaignServiceClient campaignService = client.GetService(Services.V16.CampaignService);

// Create a campaign for update.
Campaign campaignToUpdate = new Campaign()
{
    ResourceName = ResourceNames.Campaign(customerId, campaignId),
    // More fields to update.
    // ...
};

// Create the operation.
CampaignOperation operation = new CampaignOperation()
{
    Update = campaignToUpdate,
    UpdateMask = FieldMasks.AllSetFieldsOf(campaignToUpdate)
};

try
{
    // Update the campaign.
    MutateCampaignsResponse response = campaignService.MutateCampaigns(
        customerId.ToString(), new CampaignOperation[] { operation });

    // Display the results.
    // ...
}
catch (GoogleAdsException e)
{
    Console.WriteLine("Failure:");
    Console.WriteLine($"Message: {e.Message}");

    // Can examine to get more error details.
    Console.WriteLine($"Failure: {e.Failure}");

    // Can be shared with Google for further troubleshooting.
    Console.WriteLine($"Request ID: {e.RequestId}");
}