.NET 客户端库的基本用法如下:
// Initialize a GoogleAdsConfig instance.
GoogleAdsConfig config = new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
};
// Initialize a GoogleAdsClient instance.
GoogleAdsClient client = new GoogleAdsClient(config);
// Create the required service.
CampaignServiceClient campaignService =
client.GetService(Services.V25.CampaignService);
// Make calls to the service client.
初始化客户端和服务
如需与 Google Ads API 进行交互,请先配置并实例化 GoogleAdsClient,然后使用它来创建所需的特定 API 服务客户端。
创建 GoogleAdsClient 实例
Google Ads API .NET 库中最重要的类是 GoogleAdsClient 类。它可让您创建预配置的服务客户端,用于进行 API 调用。如需配置 GoogleAdsClient 对象,请创建 GoogleAdsConfig 对象并设置必需的属性。如需了解详情,请参阅配置指南。
// Initialize a GoogleAdsConfig instance.
GoogleAdsConfig config = new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
};
// Initialize a GoogleAdsClient instance.
GoogleAdsClient client = new GoogleAdsClient(config);
// Modify the GoogleAdsClient configuration afterwards if needed.
client.Config.LoginCustomerId = "INSERT_UPDATED_LOGIN_CUSTOMER_ID_HERE";
创建服务
GoogleAdsClient 提供了一个 GetService 方法,可用于创建 API 服务客户端。
CampaignServiceClient campaignService = client.GetService(
Services.V25.CampaignService);
// Now make calls to CampaignService.
该库提供了一个 Services 类,用于枚举所有受支持的 API 版本(其中次要版本(例如 v25.1)使用其主要版本枚举 Services.V25)和服务。创建服务时,GetService 方法接受这些枚举对象作为实参。例如,如需为 Google Ads API 的版本 V25 创建 CampaignServiceClient 的实例,请使用 Services.V25.CampaignService 作为实参调用 GoogleAdsClient.GetService 方法,如上例所示。
错误处理
并非每次 API 调用都会成功。如果您的 API 调用因某种原因而失败,服务器可能会返回错误。捕获 API 错误并妥善处理非常重要。
当发生 API 错误时,系统会抛出 GoogleAdsException 实例。其中包含详细信息,可帮助您找出问题所在:
public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V25.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; } }
线程安全
跨多个线程修改共享 GoogleAdsClient 实例的配置状态不是线程安全的,因为您在一个线程中对实例所做的配置更改可能会影响您在其他线程中创建的服务。不过,从不变的 GoogleAdsClient 实例获取新服务实例以及并行调用多个服务等只读操作是线程安全的。
为了隔离每个线程的配置更改,请为每个工作器任务或线程实例化一个单独的 GoogleAdsClient:
GoogleAdsClient client1 = new GoogleAdsClient();
GoogleAdsClient client2 = new GoogleAdsClient();
Task task1 = Task.Run(() => AddAdGroups(client1));
Task task2 = Task.Run(() => AddAdGroups(client2));
await Task.WhenAll(task1, task2);
public void AddAdGroups(GoogleAdsClient client)
{
// Perform operations with client.
}
让应用保持快速响应
Google Ads API 方法调用可能需要一段时间才能完成,具体取决于请求的大小。如需让应用保持响应状态,请按以下步骤操作:
针对旧版界面框架使用 Grpc.Core 库
如果您正在开发以 .NET Framework 为目标平台且使用旧版界面技术(例如 ASP.NET Web Forms 或 WinForms)的应用,则可以按如下方式启用旧版 Grpc.Core 传输库:
GoogleAdsConfig config = new GoogleAdsConfig();
config.UseGrpcCore = true;
GoogleAdsClient client = new GoogleAdsClient(config);
使用异步方法
您可以使用异步方法来保持应用的响应能力。以下是一些示例。
检索宣传活动列表并填充 ListView
private async void OnRetrieveCampaignsButtonClick(object sender, EventArgs e)
{
try
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V25.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<ListViewItem> items = new List<ListViewItem>();
await googleAdsService.SearchStreamAsync(
customerId.ToString(),
query,
(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);
}
}
);
listView1.Items.AddRange(items.ToArray());
}
catch (GoogleAdsException ex)
{
MessageBox.Show($"API Error: {ex.Message}");
}
}
更新广告系列预算并显示消息框提醒
private async void OnUpdateBudgetButtonClick(object sender, EventArgs e)
{
try
{
// Get the CampaignBudgetService.
CampaignBudgetServiceClient budgetService = client.GetService(
Services.V25.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 asynchronously.
MutateCampaignBudgetsResponse response =
await budgetService.MutateCampaignBudgetsAsync(
customerId.ToString(),
new CampaignBudgetOperation[] { budgetOperation });
MessageBox.Show(response.Results[0].ResourceName);
}
catch (GoogleAdsException ex)
{
MessageBox.Show($"API Error: {ex.Message}");
}
}