使用入门

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

安装

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

设置授权

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

如果您已有凭据...

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

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

  • 如果您还没有开发者令牌,请按照开发者令牌指南获取。
  • 按照 OAuth 桌面应用流程指南生成客户端 ID、客户端密钥和刷新令牌。
  • GitHub 中的 App.config 文件GoogleAdsApi 节点和 configSections 节点下的 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.V17.CampaignService);

// Make more calls to service class.

创建 GoogleAdsClient 实例

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

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

创建 Service

GoogleAdsClient 提供了 GetService 方法,可用于创建 Google Ads 服务。

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

我们提供了 Services 类,用于枚举所有受支持的 API 版本和服务。创建服务时,GetService 方法接受这些枚举对象作为参数。例如,如需为 Google Ads API 的 V17 版本创建 CampaignServiceClient 实例,您需要使用 Services.V17.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.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";
     
    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.V17.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.V17.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.V17.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}");
}