开始使用

本指南简要介绍 Google Ads API 的使用入门 .NET 库

安装

客户端库二进制文件使用 NuGet 分发。添加 NuGet 引用 发送至 Google.Ads.GoogleAds 软件包 客户端库。

设置授权

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

如果您需要生成凭据

如果您已有凭据

  • 复制 GoogleAdsApi 节点和 GoogleAdsApi 部分(位于 App.config 文件中的“configSections”节点 GitHub 复制到您的 App.config / Web.config 文件中。如果您使用 NuGet 安装 这些节点将自动插入到 App.config / Web.config 个文件。
  • 包括开发者令牌、客户端 ID、客户端密钥和刷新令牌 在应用的 App.config / Web.config 中。

App.config GitHub 中包含的某个文件提供了充分的文档,不过,您也可以参阅 配置指南 并使用其他方式配置客户端库, 例如环境变量

进行 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。请参阅配置 配置指南 选项。

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

创建 Service

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

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

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

线程安全

在多个线程之间共享 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 应用 冻结。一个常见的示例是通过事件处理脚本方法进行 API 调用 示例。

您可以通过以下两种方式解决此问题:

  1. 使用旧版 Grpc 库。

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

    GoogleAdsConfig config = new GoogleAdsConfig();
    config.UseGrpcCore = true;
    GoogleAdsClient client = new GoogleAdsClient(config);
    

    gRPC 支持页面提供了 旧版 Grpc.Core 库与 默认的 Grpc.Net.Client 库。

  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);
    }
    

错误处理

并非所有 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}");
}