O uso básico da biblioteca de cliente do .NET é o seguinte:
// 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.
Inicializar o cliente e os serviços
Para interagir com a API Google Ads, primeiro configure e crie uma instância de GoogleAdsClient e use-a para criar os clientes de serviço de API específicos de que você precisa.
Criar uma instância GoogleAdsClient
A classe mais importante na biblioteca .NET da API Google Ads é a GoogleAdsClient
class. Ele permite criar um cliente de serviço pré-configurado que pode ser usado para
fazer chamadas de API. Para configurar um objeto GoogleAdsClient, crie um objeto
GoogleAdsConfig e defina as propriedades necessárias. Consulte o guia de configuração para saber mais.
// 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";
Criar um serviço
O GoogleAdsClient fornece um método GetService que pode ser usado para criar um
cliente de serviço de API.
CampaignServiceClient campaignService = client.GetService(
Services.V25.CampaignService);
// Now make calls to CampaignService.
A biblioteca fornece uma classe Services que enumera todas as versões de API compatíveis (em que versões secundárias, como v25.1, usam a enumeração da versão principal, Services.V25) e serviços. O método GetService aceita esses objetos de enumeração como um argumento ao criar o serviço. Por exemplo, para criar uma instância de CampaignServiceClient para a versão V25 da API Google Ads, chame o método GoogleAdsClient.GetService com Services.V25.CampaignService como argumento, conforme mostrado no exemplo anterior.
Tratamento de erros
Nem todas as chamadas de API são bem-sucedidas. O servidor pode retornar erros se as chamadas de API falharem por algum motivo. É importante capturar erros de API e processá-los de maneira adequada.
Uma instância GoogleAdsException é gerada quando ocorre um erro de API. Ele contém detalhes para ajudar você a descobrir o que deu errado:
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; } }
Segurança de linha de execução
Modificar o estado de configuração de uma instância GoogleAdsClient compartilhada em
várias linhas de execução não é seguro para linhas de execução, porque as mudanças de configuração feitas em
uma instância em uma linha de execução podem afetar os serviços criados em outras linhas de execução.
No entanto, operações somente leitura, como a obtenção de novas instâncias de serviço de uma instância GoogleAdsClient imutável e a realização de chamadas para vários serviços em paralelo, são seguras para linhas de execução.
Para isolar as mudanças de configuração por linha de execução, crie uma instância de um GoogleAdsClient separado por tarefa ou linha de execução de worker:
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.
}
Manter seu aplicativo responsivo
As chamadas de método da API Google Ads podem levar algum tempo para serem concluídas, dependendo do tamanho das solicitações. Para manter o aplicativo responsivo, siga estas etapas:
Usar a biblioteca Grpc.Core para frameworks de interface legados
Se você estiver desenvolvendo um aplicativo destinado ao .NET Framework e usando uma tecnologia de interface legada, como ASP.NET Web Forms ou WinForms, ative a biblioteca de transporte Grpc.Core legada da seguinte maneira:
GoogleAdsConfig config = new GoogleAdsConfig();
config.UseGrpcCore = true;
GoogleAdsClient client = new GoogleAdsClient(config);
usar métodos assíncronos
Você pode usar métodos assíncronos para manter o aplicativo responsivo. Confira alguns exemplos.
Recupere a lista de campanhas e preencha um 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}");
}
}
Atualizar o orçamento da campanha e mostrar uma caixa de mensagem de alerta
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}");
}
}