Uso básico

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.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. 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.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 as versões secundárias, como v25.1, usam o tipo enumerado da versão principal, Services.V25) e os 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 poderá 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. 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.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 compartilhada de GoogleAdsClient em várias linhas de execução não é thread-safe, 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, as operações somente leitura, como receber novas instâncias de serviço de uma instância GoogleAdsClient imutável e fazer chamadas para vários serviços em paralelo, são thread-safe.

Para isolar as mudanças de configuração por linha de execução, instancie 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 o 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 IU legados

Se você estiver desenvolvendo um aplicativo que use o .NET Framework e 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 seu aplicativo responsivo. Veja alguns exemplos.

Recuperar a lista de campanhas e preencher um 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 em uma 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}");
    }
}