開始使用

本指南簡要說明如何開始使用 Google Ads API .NET 程式庫。

安裝

用戶端程式庫二進位檔是透過 NuGet 發行。在專案的 Google.Ads.GoogleAds package 中新增 NuGet 參照,即可使用用戶端程式庫。

設定授權

如要授權 API 呼叫,您需要向程式庫指定用戶端 ID、用戶端密碼、更新權杖和開發人員權杖。

如需產生憑證

如果您已有憑證

GitHub 中包含的 App.config 檔案有詳細說明,您也可以參閱設定指南,瞭解更多資訊,以及使用環境變數等替代方式設定用戶端程式庫。

發出 API 呼叫

用戶端程式庫的基本用法如下:

// Create a Google Ads client.
GoogleAdsClient client = new GoogleAdsClient();

// Create the required service.
CampaignServiceClient campaignService =
    client.GetService(Services.V21.CampaignService);

// Make more calls to service class.

建立 GoogleAdsClient 執行個體

Google Ads API .NET 程式庫中最重要的類別是 GoogleAdsClient 類別。您可以使用這個類別建立預先設定的服務類別,用於發出 API 呼叫。GoogleAdsClient 提供預設建構函式,可使用應用程式 App.config / Web.config 中指定的設定建立使用者物件。如需設定選項,請參閱設定指南

// Create a new GoogleAdsClient with the App.config settings.
GoogleAdsClient user = new GoogleAdsClient();

建立服務

GoogleAdsClient 提供 GetService 方法,可用於建立 Google Ads 服務。

CampaignServiceClient campaignService = client.GetService(Services.V21.CampaignService);
// Now make calls to CampaignService.

我們提供 Services 類別,列舉所有支援的 API 版本和服務。建立服務時,GetService 方法會將這些列舉物件做為引數。舉例來說,如要為 Google Ads API 的 V21 版本建立 CampaignServiceClient 執行個體,您需要使用 Services.V21.CampaignService 做為引數呼叫 GoogleAdsClient.GetService 方法,如上一個範例所示。

執行緒安全

在多個執行緒之間共用 GoogleAdsClient 例項並不安全,因為您在一個執行緒的例項上進行的設定變更,可能會影響您在其他執行緒上建立的服務。從 GoogleAdsClient 執行個體取得新服務執行個體,以及並行呼叫多項服務等作業,都屬於執行緒安全作業。

多執行緒應用程式如下所示:

GoogleAdsClient client1 = new GoogleAdsClient();
GoogleAdsClient client2 = new GoogleAdsClient();

Thread userThread1 = new Thread(addAdGroups);
Thread userThread2 = new Thread(addAdGroups);

userThread1.start(client1);
userThread2.start(client2);

userThread1.join();
userThread2.join();

public void addAdGroups(object data) {
  GoogleAdsClient client = (GoogleAdsClient) data;
  // Do more operations here.
  ...
}

避免 .NET Framework 應用程式凍結

同步方法可能會導致部分 .NET Framework 應用程式凍結。常見的例子是從 WinForm 應用程式的事件處理常式方法發出 API 呼叫。

解決這個問題的方法有兩種:

  1. 使用舊版 Grpc 程式庫。

    您可以設定 GoogleAdsConfigUseGrpcCore 屬性,改用舊版 Grpc.Core 程式庫,而非預設的 Grpc.Net.Client 程式庫。這個方法尚未在 .NET Framework 應用程式上經過廣泛測試,因此可能無法解決問題。以下是程式碼片段範例:

    GoogleAdsConfig config = new GoogleAdsConfig();
    config.UseGrpcCore = true;
    GoogleAdsClient client = new GoogleAdsClient(config);
    
  2. 使用非同步方法。

    您可以使用非同步方法來避免凍結。以下舉幾個例子說明:

    SearchStream

    系統會呼叫 SearchStream(),並將結果填入清單檢視畫面。

    private async void button1_Click(object sender, EventArgs e)
    {
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V21.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 items = new List();
    Task t =  googleAdsService.SearchStreamAsync(customerId.ToString(), query,
        delegate (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);
            }
        }
    );
    await t;
    listView1.Items.AddRange(items.ToArray());
    }

    廣告活動預算

    系統會建立 CampaignBudget 呼叫,並使用 MessageBox 快訊顯示新預算的資源名稱。

    private async void button2_Click(object sender, EventArgs e)
    {
    // Get the BudgetService.
    CampaignBudgetServiceClient budgetService = client.GetService(
        Services.V21.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.
    Task t = budgetService.MutateCampaignBudgetsAsync(
        customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation });
     
    await t;
    MutateCampaignBudgetsResponse response = t.Result;
    MessageBox.Show(response.Results[0].ResourceName);
    }

處理錯誤

並非每次 API 呼叫都會成功。如果 API 呼叫因故失敗,伺服器可能會擲回錯誤。請務必擷取 API 錯誤並妥善處理。

發生 API 錯誤時,系統會擲回 GoogleAdsException 例項。這份報告包含詳細資料,可協助您找出問題:

// Get the CampaignService.
CampaignServiceClient campaignService = client.GetService(Services.V21.CampaignService);

// Create a campaign for update.
Campaign campaignToUpdate = new Campaign()
{
    ResourceName = ResourceNames.Campaign(customerId, campaignId),
    // More fields to update.
    // ...
};

// Create the operation.
CampaignOperation operation = new CampaignOperation()
{
    Update = campaignToUpdate,
    UpdateMask = FieldMasks.AllSetFieldsOf(campaignToUpdate)
};

try
{
    // Update the campaign.
    MutateCampaignsResponse response = campaignService.MutateCampaigns(
        customerId.ToString(), new CampaignOperation[] { operation });

    // Display the results.
    // ...
}
catch (GoogleAdsException e)
{
    Console.WriteLine("Failure:");
    Console.WriteLine($"Message: {e.Message}");

    // Can examine to get more error details.
    Console.WriteLine($"Failure: {e.Failure}");

    // Can be shared with Google for further troubleshooting.
    Console.WriteLine($"Request ID: {e.RequestId}");
}