Uso básico

O uso básico da biblioteca de cliente .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.V26.CampaignService);

// Make calls to the service client.

Inicializar o cliente e os serviços

Para interagir com a API Google Ads, primeiro configure e instancie um GoogleAdsClient e use-o 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. Ela 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

GoogleAdsClient fornece um método GetService que pode ser usado para criar um cliente de serviço de API.

CampaignServiceClient campaignService = client.GetService(
    Services.V26.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 V26 da API Google Ads, chame o método GoogleAdsClient.GetService com Services.V26.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 tratá-los adequadamente.

Uma instância GoogleAdsException é gerada quando ocorre um erro de API. Ela 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.V26.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;
    }
}
      

Concorrência segura

Modificar o estado de configuração de uma instância GoogleAdsClient compartilhada em vários threads não é thread-safe, porque as mudanças de configuração feitas em uma instância em um thread podem afetar os serviços criados em outros threads. 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 thread-safe.

Para isolar as mudanças de configuração por thread, instancie um GoogleAdsClient separado por tarefa ou thread 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 um tempo para serem concluídas, dependendo do tamanho das solicitações. Para manter seu 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 usar uma tecnologia de interface legada, como o ASP.NET Web Forms ou o WinForms, poderá ativar 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 seu aplicativo responsivo. Confira alguns exemplos.

Recuperar a lista de campanhas e preencher uma ListView

private async void OnRetrieveCampaignsButtonClick(object sender, EventArgs e)
{
    try
    {
        // Get the GoogleAdsService.
        GoogleAdsServiceClient googleAdsService = client.GetService(
            Services.V26.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 um alerta de caixa de mensagem

private async void OnUpdateBudgetButtonClick(object sender, EventArgs e)
{
    try
    {
        // Get the CampaignBudgetService.
        CampaignBudgetServiceClient budgetService = client.GetService(
            Services.V26.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}");
    }
}