基本用法

.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";

建立服務

提供 GetService 方法,可用於建立 API 服務用戶端。GoogleAdsClient

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 程式庫處理舊版 UI 架構

如果您要開發以 .NET Framework 為目標的應用程式,並使用 ASP.NET 網頁表單或 WinForms 等舊版 UI 技術,可以按照下列步驟啟用舊版 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}");
    }
}